diff --git a/sdk/analytics/azonlineexperimentation/CHANGELOG.md b/sdk/analytics/azonlineexperimentation/CHANGELOG.md new file mode 100644 index 000000000000..6c7b1d8ae47f --- /dev/null +++ b/sdk/analytics/azonlineexperimentation/CHANGELOG.md @@ -0,0 +1,8 @@ +# Release History + +## 0.1.0 (2025-04-27) +### Other Changes + +The package of `github.com/Azure/azure-sdk-for-go/sdk/analytics/azonlineexperimentation` 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/analytics/azonlineexperimentation/LICENSE.txt b/sdk/analytics/azonlineexperimentation/LICENSE.txt new file mode 100644 index 000000000000..dc0c2ffb3dc1 --- /dev/null +++ b/sdk/analytics/azonlineexperimentation/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/analytics/azonlineexperimentation/README.md b/sdk/analytics/azonlineexperimentation/README.md new file mode 100644 index 000000000000..5e7f07376029 --- /dev/null +++ b/sdk/analytics/azonlineexperimentation/README.md @@ -0,0 +1,90 @@ +# Azure Analytics Module for Go + +The `azonlineexperimentation` module provides operations for working with Azure Analytics. + +[Source code](https://github.com/Azure/azure-sdk-for-go/tree/main/sdk/analytics/azonlineexperimentation) + +# 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 Analytics module: + +```sh +go get github.com/Azure/azure-sdk-for-go/sdk/analytics/azonlineexperimentation +``` + +## Authorization + +When creating a client, you will need to provide a credential for authenticating with Azure Analytics. 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 Analytics 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 := azonlineexperimentation.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 := azonlineexperimentation.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.() +``` + +## 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 `Analytics` 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/analytics/azonlineexperimentation/ci.yml b/sdk/analytics/azonlineexperimentation/ci.yml new file mode 100644 index 000000000000..55ddc4b6adeb --- /dev/null +++ b/sdk/analytics/azonlineexperimentation/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/analytics/azonlineexperimentation/ + +pr: + branches: + include: + - main + - feature/* + - hotfix/* + - release/* + paths: + include: + - sdk/analytics/azonlineexperimentation/ + +extends: + template: /eng/pipelines/templates/jobs/archetype-sdk-client.yml + parameters: + ServiceDirectory: 'analytics/azonlineexperimentation' diff --git a/sdk/analytics/azonlineexperimentation/client.go b/sdk/analytics/azonlineexperimentation/client.go new file mode 100644 index 000000000000..0f235ebbfe62 --- /dev/null +++ b/sdk/analytics/azonlineexperimentation/client.go @@ -0,0 +1,391 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package azonlineexperimentation + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strconv" + "strings" + "time" +) + +// Client contains the methods for the group. +// Don't use this type directly, use a constructor function instead. +type Client struct { + internal *azcore.Client + endpoint string +} + +// CreateOrUpdateMetric - Creates or updates an experiment metric. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2025-05-31-preview +// - experimentMetricID - Identifier for this experiment metric. Must start with a lowercase letter and contain only lowercase +// letters, numbers, and underscores. +// - resource - The resource instance. +// - options - CreateOrUpdateMetricOptions contains the optional parameters for the Client.CreateOrUpdateMetric method. +func (client *Client) CreateOrUpdateMetric(ctx context.Context, experimentMetricID string, resource ExperimentMetric, options *CreateOrUpdateMetricOptions) (CreateOrUpdateMetricResponse, error) { + var err error + const operationName = "Client.CreateOrUpdateMetric" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createOrUpdateMetricCreateRequest(ctx, experimentMetricID, resource, options) + if err != nil { + return CreateOrUpdateMetricResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return CreateOrUpdateMetricResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return CreateOrUpdateMetricResponse{}, err + } + resp, err := client.createOrUpdateMetricHandleResponse(httpResp) + return resp, err +} + +// createOrUpdateMetricCreateRequest creates the CreateOrUpdateMetric request. +func (client *Client) createOrUpdateMetricCreateRequest(ctx context.Context, experimentMetricID string, resource ExperimentMetric, options *CreateOrUpdateMetricOptions) (*policy.Request, error) { + host := "{endpoint}" + host = strings.ReplaceAll(host, "{endpoint}", client.endpoint) + urlPath := "/experiment-metrics/{experimentMetricId}" + if experimentMetricID == "" { + return nil, errors.New("parameter experimentMetricID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{experimentMetricId}", url.PathEscape(experimentMetricID)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2025-05-31-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.IfMatch != nil { + req.Raw().Header["If-Match"] = []string{*options.IfMatch} + } + if options != nil && options.IfModifiedSince != nil { + req.Raw().Header["If-Modified-Since"] = []string{options.IfModifiedSince.Format(time.RFC1123)} + } + if options != nil && options.IfNoneMatch != nil { + req.Raw().Header["If-None-Match"] = []string{*options.IfNoneMatch} + } + if options != nil && options.IfUnmodifiedSince != nil { + req.Raw().Header["If-Unmodified-Since"] = []string{options.IfUnmodifiedSince.Format(time.RFC1123)} + } + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["x-ms-client-request-id"] = []string{*options.ClientRequestID} + } + req.Raw().Header["Content-Type"] = []string{"application/merge-patch+json"} + if err := runtime.MarshalAsJSON(req, resource); err != nil { + return nil, err + } + return req, nil +} + +// createOrUpdateMetricHandleResponse handles the CreateOrUpdateMetric response. +func (client *Client) createOrUpdateMetricHandleResponse(resp *http.Response) (CreateOrUpdateMetricResponse, error) { + result := CreateOrUpdateMetricResponse{} + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = &val + } + if val := resp.Header.Get("x-ms-client-request-id"); val != "" { + result.XMSClientRequestID = &val + } + if err := runtime.UnmarshalAsJSON(resp, &result.ExperimentMetric); err != nil { + return CreateOrUpdateMetricResponse{}, err + } + return result, nil +} + +// DeleteMetric - Deletes an experiment metric. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2025-05-31-preview +// - experimentMetricID - Identifier for this experiment metric. Must start with a lowercase letter and contain only lowercase +// letters, numbers, and underscores. +// - options - DeleteMetricOptions contains the optional parameters for the Client.DeleteMetric method. +func (client *Client) DeleteMetric(ctx context.Context, experimentMetricID string, options *DeleteMetricOptions) (DeleteMetricResponse, error) { + var err error + const operationName = "Client.DeleteMetric" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteMetricCreateRequest(ctx, experimentMetricID, options) + if err != nil { + return DeleteMetricResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DeleteMetricResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return DeleteMetricResponse{}, err + } + resp, err := client.deleteMetricHandleResponse(httpResp) + return resp, err +} + +// deleteMetricCreateRequest creates the DeleteMetric request. +func (client *Client) deleteMetricCreateRequest(ctx context.Context, experimentMetricID string, options *DeleteMetricOptions) (*policy.Request, error) { + host := "{endpoint}" + host = strings.ReplaceAll(host, "{endpoint}", client.endpoint) + urlPath := "/experiment-metrics/{experimentMetricId}" + if experimentMetricID == "" { + return nil, errors.New("parameter experimentMetricID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{experimentMetricId}", url.PathEscape(experimentMetricID)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2025-05-31-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.IfMatch != nil { + req.Raw().Header["If-Match"] = []string{*options.IfMatch} + } + if options != nil && options.IfModifiedSince != nil { + req.Raw().Header["If-Modified-Since"] = []string{options.IfModifiedSince.Format(time.RFC1123)} + } + if options != nil && options.IfNoneMatch != nil { + req.Raw().Header["If-None-Match"] = []string{*options.IfNoneMatch} + } + if options != nil && options.IfUnmodifiedSince != nil { + req.Raw().Header["If-Unmodified-Since"] = []string{options.IfUnmodifiedSince.Format(time.RFC1123)} + } + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["x-ms-client-request-id"] = []string{*options.ClientRequestID} + } + return req, nil +} + +// deleteMetricHandleResponse handles the DeleteMetric response. +func (client *Client) deleteMetricHandleResponse(resp *http.Response) (DeleteMetricResponse, error) { + result := DeleteMetricResponse{} + if val := resp.Header.Get("x-ms-client-request-id"); val != "" { + result.XMSClientRequestID = &val + } + return result, nil +} + +// GetMetric - Fetches an experiment metric by ID. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2025-05-31-preview +// - experimentMetricID - Identifier for this experiment metric. Must start with a lowercase letter and contain only lowercase +// letters, numbers, and underscores. +// - options - GetMetricOptions contains the optional parameters for the Client.GetMetric method. +func (client *Client) GetMetric(ctx context.Context, experimentMetricID string, options *GetMetricOptions) (GetMetricResponse, error) { + var err error + const operationName = "Client.GetMetric" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getMetricCreateRequest(ctx, experimentMetricID, options) + if err != nil { + return GetMetricResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return GetMetricResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return GetMetricResponse{}, err + } + resp, err := client.getMetricHandleResponse(httpResp) + return resp, err +} + +// getMetricCreateRequest creates the GetMetric request. +func (client *Client) getMetricCreateRequest(ctx context.Context, experimentMetricID string, options *GetMetricOptions) (*policy.Request, error) { + host := "{endpoint}" + host = strings.ReplaceAll(host, "{endpoint}", client.endpoint) + urlPath := "/experiment-metrics/{experimentMetricId}" + if experimentMetricID == "" { + return nil, errors.New("parameter experimentMetricID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{experimentMetricId}", url.PathEscape(experimentMetricID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2025-05-31-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.IfMatch != nil { + req.Raw().Header["If-Match"] = []string{*options.IfMatch} + } + if options != nil && options.IfModifiedSince != nil { + req.Raw().Header["If-Modified-Since"] = []string{options.IfModifiedSince.Format(time.RFC1123)} + } + if options != nil && options.IfNoneMatch != nil { + req.Raw().Header["If-None-Match"] = []string{*options.IfNoneMatch} + } + if options != nil && options.IfUnmodifiedSince != nil { + req.Raw().Header["If-Unmodified-Since"] = []string{options.IfUnmodifiedSince.Format(time.RFC1123)} + } + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["x-ms-client-request-id"] = []string{*options.ClientRequestID} + } + return req, nil +} + +// getMetricHandleResponse handles the GetMetric response. +func (client *Client) getMetricHandleResponse(resp *http.Response) (GetMetricResponse, error) { + result := GetMetricResponse{} + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = &val + } + if val := resp.Header.Get("x-ms-client-request-id"); val != "" { + result.XMSClientRequestID = &val + } + if err := runtime.UnmarshalAsJSON(resp, &result.ExperimentMetric); err != nil { + return GetMetricResponse{}, err + } + return result, nil +} + +// NewListMetricsPager - Lists experiment metrics. +// +// Generated from API version 2025-05-31-preview +// - options - ListMetricsOptions contains the optional parameters for the Client.NewListMetricsPager method. +func (client *Client) NewListMetricsPager(options *ListMetricsOptions) *runtime.Pager[ListMetricsResponse] { + return runtime.NewPager(runtime.PagingHandler[ListMetricsResponse]{ + More: func(page ListMetricsResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ListMetricsResponse) (ListMetricsResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "Client.NewListMetricsPager") + 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.listMetricsCreateRequest(ctx, options) + }, nil) + if err != nil { + return ListMetricsResponse{}, err + } + return client.listMetricsHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listMetricsCreateRequest creates the ListMetrics request. +func (client *Client) listMetricsCreateRequest(ctx context.Context, options *ListMetricsOptions) (*policy.Request, error) { + host := "{endpoint}" + host = strings.ReplaceAll(host, "{endpoint}", client.endpoint) + urlPath := "/experiment-metrics" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2025-05-31-preview") + if options != nil && options.Maxpagesize != nil { + reqQP.Set("maxpagesize", strconv.FormatInt(int64(*options.Maxpagesize), 10)) + } + if options != nil && options.Skip != nil { + reqQP.Set("skip", strconv.FormatInt(int64(*options.Skip), 10)) + } + if options != nil && options.Top != nil { + reqQP.Set("top", strconv.FormatInt(int64(*options.Top), 10)) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["x-ms-client-request-id"] = []string{*options.ClientRequestID} + } + return req, nil +} + +// listMetricsHandleResponse handles the ListMetrics response. +func (client *Client) listMetricsHandleResponse(resp *http.Response) (ListMetricsResponse, error) { + result := ListMetricsResponse{} + if val := resp.Header.Get("x-ms-client-request-id"); val != "" { + result.XMSClientRequestID = &val + } + if err := runtime.UnmarshalAsJSON(resp, &result.PagedExperimentMetric); err != nil { + return ListMetricsResponse{}, err + } + return result, nil +} + +// ValidateMetric - Validates an experiment metric definition. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2025-05-31-preview +// - body - Experiment metric input to validate +// - options - ValidateMetricOptions contains the optional parameters for the Client.ValidateMetric method. +func (client *Client) ValidateMetric(ctx context.Context, body ExperimentMetric, options *ValidateMetricOptions) (ValidateMetricResponse, error) { + var err error + const operationName = "Client.ValidateMetric" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.validateMetricCreateRequest(ctx, body, options) + if err != nil { + return ValidateMetricResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ValidateMetricResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ValidateMetricResponse{}, err + } + resp, err := client.validateMetricHandleResponse(httpResp) + return resp, err +} + +// validateMetricCreateRequest creates the ValidateMetric request. +func (client *Client) validateMetricCreateRequest(ctx context.Context, body ExperimentMetric, options *ValidateMetricOptions) (*policy.Request, error) { + host := "{endpoint}" + host = strings.ReplaceAll(host, "{endpoint}", client.endpoint) + urlPath := "/experiment-metrics:validate" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2025-05-31-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["x-ms-client-request-id"] = []string{*options.ClientRequestID} + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// validateMetricHandleResponse handles the ValidateMetric response. +func (client *Client) validateMetricHandleResponse(resp *http.Response) (ValidateMetricResponse, error) { + result := ValidateMetricResponse{} + if val := resp.Header.Get("x-ms-client-request-id"); val != "" { + result.XMSClientRequestID = &val + } + if err := runtime.UnmarshalAsJSON(resp, &result.ExperimentMetricValidationResult); err != nil { + return ValidateMetricResponse{}, err + } + return result, nil +} diff --git a/sdk/analytics/azonlineexperimentation/constants.go b/sdk/analytics/azonlineexperimentation/constants.go new file mode 100644 index 000000000000..4f020c4960bb --- /dev/null +++ b/sdk/analytics/azonlineexperimentation/constants.go @@ -0,0 +1,107 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package azonlineexperimentation + +// DesiredDirection - Desired direction for an experiment metric value. +type DesiredDirection string + +const ( + // DesiredDirectionDecrease - A decrease to the metric value is desired. E.g., Error rate, Latency. + DesiredDirectionDecrease DesiredDirection = "Decrease" + // DesiredDirectionIncrease - An increase to the metric value is desired. E.g., Success rate, Total revenue. + DesiredDirectionIncrease DesiredDirection = "Increase" + // DesiredDirectionNeutral - Neither an increase nor a decrease to the metric value is desired, or the desired direction depends + // on other factors. E.g., Number of video play attempts, Number of user feedbacks + DesiredDirectionNeutral DesiredDirection = "Neutral" +) + +// PossibleDesiredDirectionValues returns the possible values for the DesiredDirection const type. +func PossibleDesiredDirectionValues() []DesiredDirection { + return []DesiredDirection{ + DesiredDirectionDecrease, + DesiredDirectionIncrease, + DesiredDirectionNeutral, + } +} + +// DiagnosticCode - The diagnostic error codes. +type DiagnosticCode string + +const ( + // DiagnosticCodeFailedSchemaValidation - The metric definition does not conform to the required schema. + DiagnosticCodeFailedSchemaValidation DiagnosticCode = "FailedSchemaValidation" + // DiagnosticCodeInvalidEventCondition - The filter condition is invalid. + DiagnosticCodeInvalidEventCondition DiagnosticCode = "InvalidEventCondition" + // DiagnosticCodeInvalidExperimentMetricDefinition - The provided metric definition is invalid. + // For example, defining a metric to calculate the average of a numeric property but + // including a filter condition that compares it to a string value creates a type mismatch. + DiagnosticCodeInvalidExperimentMetricDefinition DiagnosticCode = "InvalidExperimentMetricDefinition" + // DiagnosticCodeUnsupportedEventCondition - The filter condition is valid but not currently supported. + DiagnosticCodeUnsupportedEventCondition DiagnosticCode = "UnsupportedEventCondition" +) + +// PossibleDiagnosticCodeValues returns the possible values for the DiagnosticCode const type. +func PossibleDiagnosticCodeValues() []DiagnosticCode { + return []DiagnosticCode{ + DiagnosticCodeFailedSchemaValidation, + DiagnosticCodeInvalidEventCondition, + DiagnosticCodeInvalidExperimentMetricDefinition, + DiagnosticCodeUnsupportedEventCondition, + } +} + +// ExperimentMetricType - How the metric definition calculates metric values from event data. +type ExperimentMetricType string + +const ( + // ExperimentMetricTypeAverage - Calculates the average value of a specified event property. + ExperimentMetricTypeAverage ExperimentMetricType = "Average" + // ExperimentMetricTypeEventCount - Counts the occurrences of an event. Experiment analysis accounts for unequal traffic allocation. + ExperimentMetricTypeEventCount ExperimentMetricType = "EventCount" + // ExperimentMetricTypeEventRate - Calculates the percentage of events that satisfy a specified condition. + ExperimentMetricTypeEventRate ExperimentMetricType = "EventRate" + // ExperimentMetricTypePercentile - Calculates a specified percentile of an event property. + ExperimentMetricTypePercentile ExperimentMetricType = "Percentile" + // ExperimentMetricTypeSum - Calculates the sum of a specified event property. Experiment analysis accounts for unequal traffic + // allocation. + ExperimentMetricTypeSum ExperimentMetricType = "Sum" + // ExperimentMetricTypeUserCount - Counts the number of unique users who encounter an event. Experiment analysis accounts + // for unequal traffic allocation. + ExperimentMetricTypeUserCount ExperimentMetricType = "UserCount" + // ExperimentMetricTypeUserRate - Calculates the percentage of users who encounter a start event and subsequently encounter + // an end event. Users must encounter the start event before the end event to be counted. + ExperimentMetricTypeUserRate ExperimentMetricType = "UserRate" +) + +// PossibleExperimentMetricTypeValues returns the possible values for the ExperimentMetricType const type. +func PossibleExperimentMetricTypeValues() []ExperimentMetricType { + return []ExperimentMetricType{ + ExperimentMetricTypeAverage, + ExperimentMetricTypeEventCount, + ExperimentMetricTypeEventRate, + ExperimentMetricTypePercentile, + ExperimentMetricTypeSum, + ExperimentMetricTypeUserCount, + ExperimentMetricTypeUserRate, + } +} + +// LifecycleStage - Lifecycle stages of an experiment metric, determining whether the metric is included in experiment analysis. +type LifecycleStage string + +const ( + // LifecycleStageActive - The metric is included in experiment analysis. + LifecycleStageActive LifecycleStage = "Active" + // LifecycleStageInactive - The metric is excluded from experiment analysis but remains available for future use. + LifecycleStageInactive LifecycleStage = "Inactive" +) + +// PossibleLifecycleStageValues returns the possible values for the LifecycleStage const type. +func PossibleLifecycleStageValues() []LifecycleStage { + return []LifecycleStage{ + LifecycleStageActive, + LifecycleStageInactive, + } +} diff --git a/sdk/analytics/azonlineexperimentation/fake/internal.go b/sdk/analytics/azonlineexperimentation/fake/internal.go new file mode 100644 index 000000000000..d46bc9665f2e --- /dev/null +++ b/sdk/analytics/azonlineexperimentation/fake/internal.go @@ -0,0 +1,92 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "net/http" + "reflect" + "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 getHeaderValue(h http.Header, k string) string { + v := h[k] + if len(v) == 0 { + return "" + } + return v[0] +} + +func getOptional[T any](v T) *T { + if reflect.ValueOf(v).IsZero() { + return nil + } + return &v +} + +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/analytics/azonlineexperimentation/fake/server.go b/sdk/analytics/azonlineexperimentation/fake/server.go new file mode 100644 index 000000000000..64e067edb629 --- /dev/null +++ b/sdk/analytics/azonlineexperimentation/fake/server.go @@ -0,0 +1,401 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/analytics/azonlineexperimentation" + 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" + "net/http" + "net/url" + "regexp" + "strconv" + "time" +) + +// Server is a fake server for instances of the azonlineexperimentation.Client type. +type Server struct { + // CreateOrUpdateMetric is the fake for method Client.CreateOrUpdateMetric + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + CreateOrUpdateMetric func(ctx context.Context, experimentMetricID string, resource azonlineexperimentation.ExperimentMetric, options *azonlineexperimentation.CreateOrUpdateMetricOptions) (resp azfake.Responder[azonlineexperimentation.CreateOrUpdateMetricResponse], errResp azfake.ErrorResponder) + + // DeleteMetric is the fake for method Client.DeleteMetric + // HTTP status codes to indicate success: http.StatusNoContent + DeleteMetric func(ctx context.Context, experimentMetricID string, options *azonlineexperimentation.DeleteMetricOptions) (resp azfake.Responder[azonlineexperimentation.DeleteMetricResponse], errResp azfake.ErrorResponder) + + // GetMetric is the fake for method Client.GetMetric + // HTTP status codes to indicate success: http.StatusOK + GetMetric func(ctx context.Context, experimentMetricID string, options *azonlineexperimentation.GetMetricOptions) (resp azfake.Responder[azonlineexperimentation.GetMetricResponse], errResp azfake.ErrorResponder) + + // NewListMetricsPager is the fake for method Client.NewListMetricsPager + // HTTP status codes to indicate success: http.StatusOK + NewListMetricsPager func(options *azonlineexperimentation.ListMetricsOptions) (resp azfake.PagerResponder[azonlineexperimentation.ListMetricsResponse]) + + // ValidateMetric is the fake for method Client.ValidateMetric + // HTTP status codes to indicate success: http.StatusOK + ValidateMetric func(ctx context.Context, body azonlineexperimentation.ExperimentMetric, options *azonlineexperimentation.ValidateMetricOptions) (resp azfake.Responder[azonlineexperimentation.ValidateMetricResponse], errResp azfake.ErrorResponder) +} + +// NewServerTransport creates a new instance of ServerTransport with the provided implementation. +// The returned ServerTransport instance is connected to an instance of azonlineexperimentation.Client via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewServerTransport(srv *Server) *ServerTransport { + return &ServerTransport{ + srv: srv, + newListMetricsPager: newTracker[azfake.PagerResponder[azonlineexperimentation.ListMetricsResponse]](), + } +} + +// ServerTransport connects instances of azonlineexperimentation.Client to instances of Server. +// Don't use this type directly, use NewServerTransport instead. +type ServerTransport struct { + srv *Server + newListMetricsPager *tracker[azfake.PagerResponder[azonlineexperimentation.ListMetricsResponse]] +} + +// Do implements the policy.Transporter interface for ServerTransport. +func (s *ServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return s.dispatchToMethodFake(req, method) +} + +func (s *ServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result) + defer close(resultChan) + + go func() { + var intercepted bool + var res result + if serverTransportInterceptor != nil { + res.resp, res.err, intercepted = serverTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "Client.CreateOrUpdateMetric": + res.resp, res.err = s.dispatchCreateOrUpdateMetric(req) + case "Client.DeleteMetric": + res.resp, res.err = s.dispatchDeleteMetric(req) + case "Client.GetMetric": + res.resp, res.err = s.dispatchGetMetric(req) + case "Client.NewListMetricsPager": + res.resp, res.err = s.dispatchNewListMetricsPager(req) + case "Client.ValidateMetric": + res.resp, res.err = s.dispatchValidateMetric(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + select { + case resultChan <- res: + case <-req.Context().Done(): + } + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (s *ServerTransport) dispatchCreateOrUpdateMetric(req *http.Request) (*http.Response, error) { + if s.srv.CreateOrUpdateMetric == nil { + return nil, &nonRetriableError{errors.New("fake for method CreateOrUpdateMetric not implemented")} + } + const regexStr = `/experiment-metrics/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if matches == nil || len(matches) < 1 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[azonlineexperimentation.ExperimentMetric](req) + if err != nil { + return nil, err + } + experimentMetricIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("experimentMetricId")]) + if err != nil { + return nil, err + } + ifMatchParam := getOptional(getHeaderValue(req.Header, "If-Match")) + ifNoneMatchParam := getOptional(getHeaderValue(req.Header, "If-None-Match")) + ifUnmodifiedSinceParam, err := parseOptional(getHeaderValue(req.Header, "If-Unmodified-Since"), func(v string) (time.Time, error) { return time.Parse(time.RFC1123, v) }) + if err != nil { + return nil, err + } + ifModifiedSinceParam, err := parseOptional(getHeaderValue(req.Header, "If-Modified-Since"), func(v string) (time.Time, error) { return time.Parse(time.RFC1123, v) }) + if err != nil { + return nil, err + } + clientRequestIDParam := getOptional(getHeaderValue(req.Header, "x-ms-client-request-id")) + var options *azonlineexperimentation.CreateOrUpdateMetricOptions + if ifMatchParam != nil || ifNoneMatchParam != nil || ifUnmodifiedSinceParam != nil || ifModifiedSinceParam != nil || clientRequestIDParam != nil { + options = &azonlineexperimentation.CreateOrUpdateMetricOptions{ + IfMatch: ifMatchParam, + IfNoneMatch: ifNoneMatchParam, + IfUnmodifiedSince: ifUnmodifiedSinceParam, + IfModifiedSince: ifModifiedSinceParam, + ClientRequestID: clientRequestIDParam, + } + } + respr, errRespr := s.srv.CreateOrUpdateMetric(req.Context(), experimentMetricIDParam, body, options) + 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).ExperimentMetric, req) + if err != nil { + return nil, err + } + if val := server.GetResponse(respr).ETag; val != nil { + resp.Header.Set("ETag", *val) + } + if val := server.GetResponse(respr).XMSClientRequestID; val != nil { + resp.Header.Set("x-ms-client-request-id", *val) + } + return resp, nil +} + +func (s *ServerTransport) dispatchDeleteMetric(req *http.Request) (*http.Response, error) { + if s.srv.DeleteMetric == nil { + return nil, &nonRetriableError{errors.New("fake for method DeleteMetric not implemented")} + } + const regexStr = `/experiment-metrics/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + 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) + } + experimentMetricIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("experimentMetricId")]) + if err != nil { + return nil, err + } + ifMatchParam := getOptional(getHeaderValue(req.Header, "If-Match")) + ifNoneMatchParam := getOptional(getHeaderValue(req.Header, "If-None-Match")) + ifUnmodifiedSinceParam, err := parseOptional(getHeaderValue(req.Header, "If-Unmodified-Since"), func(v string) (time.Time, error) { return time.Parse(time.RFC1123, v) }) + if err != nil { + return nil, err + } + ifModifiedSinceParam, err := parseOptional(getHeaderValue(req.Header, "If-Modified-Since"), func(v string) (time.Time, error) { return time.Parse(time.RFC1123, v) }) + if err != nil { + return nil, err + } + clientRequestIDParam := getOptional(getHeaderValue(req.Header, "x-ms-client-request-id")) + var options *azonlineexperimentation.DeleteMetricOptions + if ifMatchParam != nil || ifNoneMatchParam != nil || ifUnmodifiedSinceParam != nil || ifModifiedSinceParam != nil || clientRequestIDParam != nil { + options = &azonlineexperimentation.DeleteMetricOptions{ + IfMatch: ifMatchParam, + IfNoneMatch: ifNoneMatchParam, + IfUnmodifiedSince: ifUnmodifiedSinceParam, + IfModifiedSince: ifModifiedSinceParam, + ClientRequestID: clientRequestIDParam, + } + } + respr, errRespr := s.srv.DeleteMetric(req.Context(), experimentMetricIDParam, options) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + if val := server.GetResponse(respr).XMSClientRequestID; val != nil { + resp.Header.Set("x-ms-client-request-id", *val) + } + return resp, nil +} + +func (s *ServerTransport) dispatchGetMetric(req *http.Request) (*http.Response, error) { + if s.srv.GetMetric == nil { + return nil, &nonRetriableError{errors.New("fake for method GetMetric not implemented")} + } + const regexStr = `/experiment-metrics/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + 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) + } + experimentMetricIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("experimentMetricId")]) + if err != nil { + return nil, err + } + ifMatchParam := getOptional(getHeaderValue(req.Header, "If-Match")) + ifNoneMatchParam := getOptional(getHeaderValue(req.Header, "If-None-Match")) + ifUnmodifiedSinceParam, err := parseOptional(getHeaderValue(req.Header, "If-Unmodified-Since"), func(v string) (time.Time, error) { return time.Parse(time.RFC1123, v) }) + if err != nil { + return nil, err + } + ifModifiedSinceParam, err := parseOptional(getHeaderValue(req.Header, "If-Modified-Since"), func(v string) (time.Time, error) { return time.Parse(time.RFC1123, v) }) + if err != nil { + return nil, err + } + clientRequestIDParam := getOptional(getHeaderValue(req.Header, "x-ms-client-request-id")) + var options *azonlineexperimentation.GetMetricOptions + if ifMatchParam != nil || ifNoneMatchParam != nil || ifUnmodifiedSinceParam != nil || ifModifiedSinceParam != nil || clientRequestIDParam != nil { + options = &azonlineexperimentation.GetMetricOptions{ + IfMatch: ifMatchParam, + IfNoneMatch: ifNoneMatchParam, + IfUnmodifiedSince: ifUnmodifiedSinceParam, + IfModifiedSince: ifModifiedSinceParam, + ClientRequestID: clientRequestIDParam, + } + } + respr, errRespr := s.srv.GetMetric(req.Context(), experimentMetricIDParam, options) + 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).ExperimentMetric, req) + if err != nil { + return nil, err + } + if val := server.GetResponse(respr).ETag; val != nil { + resp.Header.Set("ETag", *val) + } + if val := server.GetResponse(respr).XMSClientRequestID; val != nil { + resp.Header.Set("x-ms-client-request-id", *val) + } + return resp, nil +} + +func (s *ServerTransport) dispatchNewListMetricsPager(req *http.Request) (*http.Response, error) { + if s.srv.NewListMetricsPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListMetricsPager not implemented")} + } + newListMetricsPager := s.newListMetricsPager.get(req) + if newListMetricsPager == nil { + qp := req.URL.Query() + topUnescaped, err := url.QueryUnescape(qp.Get("top")) + if err != nil { + return nil, err + } + topParam, err := parseOptional(topUnescaped, func(v string) (int32, error) { + p, parseErr := strconv.ParseInt(v, 10, 32) + if parseErr != nil { + return 0, parseErr + } + return int32(p), nil + }) + if err != nil { + return nil, err + } + skipUnescaped, err := url.QueryUnescape(qp.Get("skip")) + if err != nil { + return nil, err + } + skipParam, err := parseOptional(skipUnescaped, func(v string) (int32, error) { + p, parseErr := strconv.ParseInt(v, 10, 32) + if parseErr != nil { + return 0, parseErr + } + return int32(p), nil + }) + if err != nil { + return nil, err + } + maxpagesizeUnescaped, err := url.QueryUnescape(qp.Get("maxpagesize")) + if err != nil { + return nil, err + } + maxpagesizeParam, err := parseOptional(maxpagesizeUnescaped, func(v string) (int32, error) { + p, parseErr := strconv.ParseInt(v, 10, 32) + if parseErr != nil { + return 0, parseErr + } + return int32(p), nil + }) + if err != nil { + return nil, err + } + clientRequestIDParam := getOptional(getHeaderValue(req.Header, "x-ms-client-request-id")) + var options *azonlineexperimentation.ListMetricsOptions + if topParam != nil || skipParam != nil || maxpagesizeParam != nil || clientRequestIDParam != nil { + options = &azonlineexperimentation.ListMetricsOptions{ + Top: topParam, + Skip: skipParam, + Maxpagesize: maxpagesizeParam, + ClientRequestID: clientRequestIDParam, + } + } + resp := s.srv.NewListMetricsPager(options) + newListMetricsPager = &resp + s.newListMetricsPager.add(req, newListMetricsPager) + server.PagerResponderInjectNextLinks(newListMetricsPager, req, func(page *azonlineexperimentation.ListMetricsResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListMetricsPager, req) + if err != nil { + return nil, err + } + if !contains([]int{http.StatusOK}, resp.StatusCode) { + s.newListMetricsPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListMetricsPager) { + s.newListMetricsPager.remove(req) + } + return resp, nil +} + +func (s *ServerTransport) dispatchValidateMetric(req *http.Request) (*http.Response, error) { + if s.srv.ValidateMetric == nil { + return nil, &nonRetriableError{errors.New("fake for method ValidateMetric not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[azonlineexperimentation.ExperimentMetric](req) + if err != nil { + return nil, err + } + clientRequestIDParam := getOptional(getHeaderValue(req.Header, "x-ms-client-request-id")) + var options *azonlineexperimentation.ValidateMetricOptions + if clientRequestIDParam != nil { + options = &azonlineexperimentation.ValidateMetricOptions{ + ClientRequestID: clientRequestIDParam, + } + } + respr, errRespr := s.srv.ValidateMetric(req.Context(), body, options) + 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).ExperimentMetricValidationResult, req) + if err != nil { + return nil, err + } + if val := server.GetResponse(respr).XMSClientRequestID; val != nil { + resp.Header.Set("x-ms-client-request-id", *val) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ServerTransport +var serverTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/sdk/analytics/azonlineexperimentation/fake/time_rfc3339.go b/sdk/analytics/azonlineexperimentation/fake/time_rfc3339.go new file mode 100644 index 000000000000..87ee11e83b32 --- /dev/null +++ b/sdk/analytics/azonlineexperimentation/fake/time_rfc3339.go @@ -0,0 +1,109 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "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 +} diff --git a/sdk/analytics/azonlineexperimentation/go.mod b/sdk/analytics/azonlineexperimentation/go.mod new file mode 100644 index 000000000000..791515df35ed --- /dev/null +++ b/sdk/analytics/azonlineexperimentation/go.mod @@ -0,0 +1,13 @@ +module github.com/Azure/azure-sdk-for-go/sdk/analytics/azonlineexperimentation + +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/analytics/azonlineexperimentation/go.sum b/sdk/analytics/azonlineexperimentation/go.sum new file mode 100644 index 000000000000..cfff861c9769 --- /dev/null +++ b/sdk/analytics/azonlineexperimentation/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/analytics/azonlineexperimentation/interfaces.go b/sdk/analytics/azonlineexperimentation/interfaces.go new file mode 100644 index 000000000000..12054bbbc5aa --- /dev/null +++ b/sdk/analytics/azonlineexperimentation/interfaces.go @@ -0,0 +1,15 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package azonlineexperimentation + +// ExperimentMetricDefinitionClassification provides polymorphic access to related types. +// Call the interface's GetExperimentMetricDefinition() method to access the common type. +// Use a type switch to determine the concrete type. The possible types are: +// - *AverageMetricDefinition, *EventCountMetricDefinition, *EventRateMetricDefinition, *ExperimentMetricDefinition, *PercentileMetricDefinition, +// - *SumMetricDefinition, *UserCountMetricDefinition, *UserRateMetricDefinition +type ExperimentMetricDefinitionClassification interface { + // GetExperimentMetricDefinition returns the ExperimentMetricDefinition content of the underlying type. + GetExperimentMetricDefinition() *ExperimentMetricDefinition +} diff --git a/sdk/analytics/azonlineexperimentation/models.go b/sdk/analytics/azonlineexperimentation/models.go new file mode 100644 index 000000000000..af3b303eb7cc --- /dev/null +++ b/sdk/analytics/azonlineexperimentation/models.go @@ -0,0 +1,234 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package azonlineexperimentation + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "time" +) + +// AggregatedValue - An event property value aggregated by a metric. +type AggregatedValue struct { + // REQUIRED; The name of the event. + EventName *string + + // REQUIRED; The key of the event property to aggregate. + EventProperty *string + + // [Optional] A condition to filter events. + Filter *string +} + +// AverageMetricDefinition - The definition of an Average metric definition. Calculates the average value of a specified event +// property. +type AverageMetricDefinition struct { + // CONSTANT; The type of metric. + // Field has constant value ExperimentMetricTypeAverage, any specified value is ignored. + Type *ExperimentMetricType + + // REQUIRED; The value to aggregate. + Value *AggregatedValue +} + +// GetExperimentMetricDefinition implements the ExperimentMetricDefinitionClassification interface for type AverageMetricDefinition. +func (a *AverageMetricDefinition) GetExperimentMetricDefinition() *ExperimentMetricDefinition { + return &ExperimentMetricDefinition{ + Type: a.Type, + } +} + +// DiagnosticDetail - Diagnostic details for validation errors. +type DiagnosticDetail struct { + // READ-ONLY; The diagnostic error code. + Code *DiagnosticCode + + // READ-ONLY; A human-readable error message. + Message *string +} + +// EventCountMetricDefinition - The definition of an EventCount metric definition. Counts the occurrences of a specified event. +type EventCountMetricDefinition struct { + // REQUIRED; Event to observe. + Event *ObservedEvent + + // CONSTANT; The type of metric. + // Field has constant value ExperimentMetricTypeEventCount, any specified value is ignored. + Type *ExperimentMetricType +} + +// GetExperimentMetricDefinition implements the ExperimentMetricDefinitionClassification interface for type EventCountMetricDefinition. +func (e *EventCountMetricDefinition) GetExperimentMetricDefinition() *ExperimentMetricDefinition { + return &ExperimentMetricDefinition{ + Type: e.Type, + } +} + +// EventRateMetricDefinition - The definition of an EventRate metric definition. Calculates the percentage of events satisfying +// a specified condition. +type EventRateMetricDefinition struct { + // REQUIRED; Event to observe as the rate denominator. + Event *ObservedEvent + + // REQUIRED; The event contributes to the rate numerator if it satisfies this condition. + RateCondition *string + + // CONSTANT; The type of metric. + // Field has constant value ExperimentMetricTypeEventRate, any specified value is ignored. + Type *ExperimentMetricType +} + +// GetExperimentMetricDefinition implements the ExperimentMetricDefinitionClassification interface for type EventRateMetricDefinition. +func (e *EventRateMetricDefinition) GetExperimentMetricDefinition() *ExperimentMetricDefinition { + return &ExperimentMetricDefinition{ + Type: e.Type, + } +} + +// ExperimentMetric - Defines experiment metric metadata and computation details. +type ExperimentMetric struct { + // REQUIRED; Categories associated with the experiment metric. Used for organizing and filtering metrics. + Categories []string + + // REQUIRED; The metric definition specifying how the metric value is calculated from event data. + Definition ExperimentMetricDefinitionClassification + + // REQUIRED; A detailed description of the experiment metric. + Description *string + + // REQUIRED; The desired direction for changes in the metric value. + DesiredDirection *DesiredDirection + + // REQUIRED; A user-friendly display name for the experiment metric shown in reports and dashboards. + DisplayName *string + + // REQUIRED; Determines whether it is included in experiment analysis. + Lifecycle *LifecycleStage + + // READ-ONLY; ETag of the experiment metric. + ETag *azcore.ETag + + // READ-ONLY; Identifier for this experiment metric. Must start with a lowercase letter and contain only lowercase letters, + // numbers, and underscores. + ID *string + + // READ-ONLY; The timestamp (UTC) of the last modification to the experiment metric resource. + LastModifiedAt *time.Time +} + +// ExperimentMetricDefinition - The metric definition, which determines how the metric value is calculated from event data. +type ExperimentMetricDefinition struct { + // REQUIRED; Discriminator property for ExperimentMetricDefinition. + Type *ExperimentMetricType +} + +// GetExperimentMetricDefinition implements the ExperimentMetricDefinitionClassification interface for type ExperimentMetricDefinition. +func (e *ExperimentMetricDefinition) GetExperimentMetricDefinition() *ExperimentMetricDefinition { + return e +} + +// ExperimentMetricValidationResult - The result of validating an experiment metric. +type ExperimentMetricValidationResult struct { + // REQUIRED; Indicates whether the experiment metric is valid. + IsValid *bool + + // READ-ONLY; Diagnostic details from the validation process. + Diagnostics []DiagnosticDetail +} + +// ObservedEvent - An event observed by a metric. +type ObservedEvent struct { + // REQUIRED; The name of the event. + EventName *string + + // [Optional] A condition to filter events. + Filter *string +} + +// PagedExperimentMetric - Paged collection of ExperimentMetric items +type PagedExperimentMetric struct { + // REQUIRED; The ExperimentMetric items on this page + Value []ExperimentMetric + + // The link to the next page of items + NextLink *string +} + +// PercentileMetricDefinition - The definition of a Percentile metric definition. Calculates a specified percentile of an +// event property. +type PercentileMetricDefinition struct { + // REQUIRED; The percentile to measure. + Percentile *float64 + + // CONSTANT; The type of metric. + // Field has constant value ExperimentMetricTypePercentile, any specified value is ignored. + Type *ExperimentMetricType + + // REQUIRED; The value to aggregate, including the event name and property to measure. + Value *AggregatedValue +} + +// GetExperimentMetricDefinition implements the ExperimentMetricDefinitionClassification interface for type PercentileMetricDefinition. +func (p *PercentileMetricDefinition) GetExperimentMetricDefinition() *ExperimentMetricDefinition { + return &ExperimentMetricDefinition{ + Type: p.Type, + } +} + +// SumMetricDefinition - The definition of a Sum metric definition. Calculates the sum of a specified event property. Experiment +// analysis accounts for unequal traffic allocation. +type SumMetricDefinition struct { + // CONSTANT; The type of metric. + // Field has constant value ExperimentMetricTypeSum, any specified value is ignored. + Type *ExperimentMetricType + + // REQUIRED; The value to aggregate. + Value *AggregatedValue +} + +// GetExperimentMetricDefinition implements the ExperimentMetricDefinitionClassification interface for type SumMetricDefinition. +func (s *SumMetricDefinition) GetExperimentMetricDefinition() *ExperimentMetricDefinition { + return &ExperimentMetricDefinition{ + Type: s.Type, + } +} + +// UserCountMetricDefinition - The definition of a UserCount metric definition. Counts unique users who encounter a specified +// event. +type UserCountMetricDefinition struct { + // REQUIRED; Event to observe. + Event *ObservedEvent + + // CONSTANT; The type of metric. + // Field has constant value ExperimentMetricTypeUserCount, any specified value is ignored. + Type *ExperimentMetricType +} + +// GetExperimentMetricDefinition implements the ExperimentMetricDefinitionClassification interface for type UserCountMetricDefinition. +func (u *UserCountMetricDefinition) GetExperimentMetricDefinition() *ExperimentMetricDefinition { + return &ExperimentMetricDefinition{ + Type: u.Type, + } +} + +// UserRateMetricDefinition - The definition of a UserRate metric definition. Calculates the percentage of users who encounter +// a start event and subsequently an end event. Users must encounter events in the specified order. +type UserRateMetricDefinition struct { + // REQUIRED; The end event to observe, which is a condition for the rate numerator. + EndEvent *ObservedEvent + + // REQUIRED; The start event to observe as the rate denominator. + StartEvent *ObservedEvent + + // CONSTANT; The type of metric. + // Field has constant value ExperimentMetricTypeUserRate, any specified value is ignored. + Type *ExperimentMetricType +} + +// GetExperimentMetricDefinition implements the ExperimentMetricDefinitionClassification interface for type UserRateMetricDefinition. +func (u *UserRateMetricDefinition) GetExperimentMetricDefinition() *ExperimentMetricDefinition { + return &ExperimentMetricDefinition{ + Type: u.Type, + } +} diff --git a/sdk/analytics/azonlineexperimentation/models_serde.go b/sdk/analytics/azonlineexperimentation/models_serde.go new file mode 100644 index 000000000000..599d05c62a29 --- /dev/null +++ b/sdk/analytics/azonlineexperimentation/models_serde.go @@ -0,0 +1,506 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package azonlineexperimentation + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "reflect" +) + +// MarshalJSON implements the json.Marshaller interface for type AggregatedValue. +func (a AggregatedValue) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "eventName", a.EventName) + populate(objectMap, "eventProperty", a.EventProperty) + populate(objectMap, "filter", a.Filter) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AggregatedValue. +func (a *AggregatedValue) 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 "eventName": + err = unpopulate(val, "EventName", &a.EventName) + delete(rawMsg, key) + case "eventProperty": + err = unpopulate(val, "EventProperty", &a.EventProperty) + delete(rawMsg, key) + case "filter": + err = unpopulate(val, "Filter", &a.Filter) + 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 AverageMetricDefinition. +func (a AverageMetricDefinition) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + objectMap["type"] = ExperimentMetricTypeAverage + populate(objectMap, "value", a.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AverageMetricDefinition. +func (a *AverageMetricDefinition) 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 "type": + err = unpopulate(val, "Type", &a.Type) + 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 DiagnosticDetail. +func (d DiagnosticDetail) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "code", d.Code) + populate(objectMap, "message", d.Message) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DiagnosticDetail. +func (d *DiagnosticDetail) 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 "code": + err = unpopulate(val, "Code", &d.Code) + delete(rawMsg, key) + case "message": + err = unpopulate(val, "Message", &d.Message) + 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 EventCountMetricDefinition. +func (e EventCountMetricDefinition) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "event", e.Event) + objectMap["type"] = ExperimentMetricTypeEventCount + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type EventCountMetricDefinition. +func (e *EventCountMetricDefinition) 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 "event": + err = unpopulate(val, "Event", &e.Event) + 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 EventRateMetricDefinition. +func (e EventRateMetricDefinition) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "event", e.Event) + populate(objectMap, "rateCondition", e.RateCondition) + objectMap["type"] = ExperimentMetricTypeEventRate + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type EventRateMetricDefinition. +func (e *EventRateMetricDefinition) 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 "event": + err = unpopulate(val, "Event", &e.Event) + delete(rawMsg, key) + case "rateCondition": + err = unpopulate(val, "RateCondition", &e.RateCondition) + 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 ExperimentMetric. +func (e ExperimentMetric) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "categories", e.Categories) + populate(objectMap, "definition", e.Definition) + populate(objectMap, "description", e.Description) + populate(objectMap, "desiredDirection", e.DesiredDirection) + populate(objectMap, "displayName", e.DisplayName) + populate(objectMap, "eTag", e.ETag) + populate(objectMap, "id", e.ID) + populateDateTimeRFC3339(objectMap, "lastModifiedAt", e.LastModifiedAt) + populate(objectMap, "lifecycle", e.Lifecycle) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ExperimentMetric. +func (e *ExperimentMetric) 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 "categories": + err = unpopulate(val, "Categories", &e.Categories) + delete(rawMsg, key) + case "definition": + e.Definition, err = unmarshalExperimentMetricDefinitionClassification(val) + delete(rawMsg, key) + case "description": + err = unpopulate(val, "Description", &e.Description) + delete(rawMsg, key) + case "desiredDirection": + err = unpopulate(val, "DesiredDirection", &e.DesiredDirection) + delete(rawMsg, key) + case "displayName": + err = unpopulate(val, "DisplayName", &e.DisplayName) + delete(rawMsg, key) + case "eTag": + err = unpopulate(val, "ETag", &e.ETag) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &e.ID) + delete(rawMsg, key) + case "lastModifiedAt": + err = unpopulateDateTimeRFC3339(val, "LastModifiedAt", &e.LastModifiedAt) + delete(rawMsg, key) + case "lifecycle": + err = unpopulate(val, "Lifecycle", &e.Lifecycle) + 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 ExperimentMetricDefinition. +func (e ExperimentMetricDefinition) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "type", e.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ExperimentMetricDefinition. +func (e *ExperimentMetricDefinition) 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 "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 ExperimentMetricValidationResult. +func (e ExperimentMetricValidationResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "diagnostics", e.Diagnostics) + populate(objectMap, "isValid", e.IsValid) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ExperimentMetricValidationResult. +func (e *ExperimentMetricValidationResult) 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 "diagnostics": + err = unpopulate(val, "Diagnostics", &e.Diagnostics) + delete(rawMsg, key) + case "isValid": + err = unpopulate(val, "IsValid", &e.IsValid) + 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 ObservedEvent. +func (o ObservedEvent) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "eventName", o.EventName) + populate(objectMap, "filter", o.Filter) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ObservedEvent. +func (o *ObservedEvent) 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 "eventName": + err = unpopulate(val, "EventName", &o.EventName) + delete(rawMsg, key) + case "filter": + err = unpopulate(val, "Filter", &o.Filter) + 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 PagedExperimentMetric. +func (p PagedExperimentMetric) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", p.NextLink) + populate(objectMap, "value", p.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PagedExperimentMetric. +func (p *PagedExperimentMetric) 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 "nextLink": + err = unpopulate(val, "NextLink", &p.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &p.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type PercentileMetricDefinition. +func (p PercentileMetricDefinition) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "percentile", p.Percentile) + objectMap["type"] = ExperimentMetricTypePercentile + populate(objectMap, "value", p.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PercentileMetricDefinition. +func (p *PercentileMetricDefinition) 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 "percentile": + err = unpopulate(val, "Percentile", &p.Percentile) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &p.Type) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &p.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SumMetricDefinition. +func (s SumMetricDefinition) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + objectMap["type"] = ExperimentMetricTypeSum + populate(objectMap, "value", s.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SumMetricDefinition. +func (s *SumMetricDefinition) 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 "type": + err = unpopulate(val, "Type", &s.Type) + 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 UserCountMetricDefinition. +func (u UserCountMetricDefinition) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "event", u.Event) + objectMap["type"] = ExperimentMetricTypeUserCount + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type UserCountMetricDefinition. +func (u *UserCountMetricDefinition) 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 "event": + err = unpopulate(val, "Event", &u.Event) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &u.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type UserRateMetricDefinition. +func (u UserRateMetricDefinition) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "endEvent", u.EndEvent) + populate(objectMap, "startEvent", u.StartEvent) + objectMap["type"] = ExperimentMetricTypeUserRate + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type UserRateMetricDefinition. +func (u *UserRateMetricDefinition) 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 "endEvent": + err = unpopulate(val, "EndEvent", &u.EndEvent) + delete(rawMsg, key) + case "startEvent": + err = unpopulate(val, "StartEvent", &u.StartEvent) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &u.Type) + 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/analytics/azonlineexperimentation/options.go b/sdk/analytics/azonlineexperimentation/options.go new file mode 100644 index 000000000000..bf860c42328d --- /dev/null +++ b/sdk/analytics/azonlineexperimentation/options.go @@ -0,0 +1,82 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package azonlineexperimentation + +import "time" + +// CreateOrUpdateMetricOptions contains the optional parameters for the Client.CreateOrUpdateMetric method. +type CreateOrUpdateMetricOptions struct { + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // The request should only proceed if an entity matches this string. + IfMatch *string + + // The request should only proceed if the entity was modified after this time. + IfModifiedSince *time.Time + + // The request should only proceed if no entity matches this string. + IfNoneMatch *string + + // The request should only proceed if the entity was not modified after this time. + IfUnmodifiedSince *time.Time +} + +// DeleteMetricOptions contains the optional parameters for the Client.DeleteMetric method. +type DeleteMetricOptions struct { + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // The request should only proceed if an entity matches this string. + IfMatch *string + + // The request should only proceed if the entity was modified after this time. + IfModifiedSince *time.Time + + // The request should only proceed if no entity matches this string. + IfNoneMatch *string + + // The request should only proceed if the entity was not modified after this time. + IfUnmodifiedSince *time.Time +} + +// GetMetricOptions contains the optional parameters for the Client.GetMetric method. +type GetMetricOptions struct { + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // The request should only proceed if an entity matches this string. + IfMatch *string + + // The request should only proceed if the entity was modified after this time. + IfModifiedSince *time.Time + + // The request should only proceed if no entity matches this string. + IfNoneMatch *string + + // The request should only proceed if the entity was not modified after this time. + IfUnmodifiedSince *time.Time +} + +// ListMetricsOptions contains the optional parameters for the Client.NewListMetricsPager method. +type ListMetricsOptions struct { + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // The maximum number of result items per page. + Maxpagesize *int32 + + // The number of result items to skip. + Skip *int32 + + // The number of result items to return. + Top *int32 +} + +// ValidateMetricOptions contains the optional parameters for the Client.ValidateMetric method. +type ValidateMetricOptions struct { + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string +} diff --git a/sdk/analytics/azonlineexperimentation/polymorphic_helpers.go b/sdk/analytics/azonlineexperimentation/polymorphic_helpers.go new file mode 100644 index 000000000000..dac0e6bad5e5 --- /dev/null +++ b/sdk/analytics/azonlineexperimentation/polymorphic_helpers.go @@ -0,0 +1,40 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package azonlineexperimentation + +import "encoding/json" + +func unmarshalExperimentMetricDefinitionClassification(rawMsg json.RawMessage) (ExperimentMetricDefinitionClassification, 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 ExperimentMetricDefinitionClassification + switch m["type"] { + case string(ExperimentMetricTypeEventCount): + b = &EventCountMetricDefinition{} + case string(ExperimentMetricTypeUserCount): + b = &UserCountMetricDefinition{} + case string(ExperimentMetricTypeEventRate): + b = &EventRateMetricDefinition{} + case string(ExperimentMetricTypeUserRate): + b = &UserRateMetricDefinition{} + case string(ExperimentMetricTypeSum): + b = &SumMetricDefinition{} + case string(ExperimentMetricTypeAverage): + b = &AverageMetricDefinition{} + case string(ExperimentMetricTypePercentile): + b = &PercentileMetricDefinition{} + default: + b = &ExperimentMetricDefinition{} + } + if err := json.Unmarshal(rawMsg, b); err != nil { + return nil, err + } + return b, nil +} diff --git a/sdk/analytics/azonlineexperimentation/responses.go b/sdk/analytics/azonlineexperimentation/responses.go new file mode 100644 index 000000000000..f34eaab3ad40 --- /dev/null +++ b/sdk/analytics/azonlineexperimentation/responses.go @@ -0,0 +1,53 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package azonlineexperimentation + +// CreateOrUpdateMetricResponse contains the response from method Client.CreateOrUpdateMetric. +type CreateOrUpdateMetricResponse struct { + // Defines experiment metric metadata and computation details. + ExperimentMetric + + // The entity tag for the response. + ETag *string + + // An opaque, globally-unique, client-generated string identifier for the request. + XMSClientRequestID *string +} + +// DeleteMetricResponse contains the response from method Client.DeleteMetric. +type DeleteMetricResponse struct { + // An opaque, globally-unique, client-generated string identifier for the request. + XMSClientRequestID *string +} + +// GetMetricResponse contains the response from method Client.GetMetric. +type GetMetricResponse struct { + // Defines experiment metric metadata and computation details. + ExperimentMetric + + // The entity tag for the response. + ETag *string + + // An opaque, globally-unique, client-generated string identifier for the request. + XMSClientRequestID *string +} + +// ListMetricsResponse contains the response from method Client.NewListMetricsPager. +type ListMetricsResponse struct { + // Paged collection of ExperimentMetric items + PagedExperimentMetric + + // An opaque, globally-unique, client-generated string identifier for the request. + XMSClientRequestID *string +} + +// ValidateMetricResponse contains the response from method Client.ValidateMetric. +type ValidateMetricResponse struct { + // The result of validating an experiment metric. + ExperimentMetricValidationResult + + // An opaque, globally-unique, client-generated string identifier for the request. + XMSClientRequestID *string +} diff --git a/sdk/analytics/azonlineexperimentation/time_rfc3339.go b/sdk/analytics/azonlineexperimentation/time_rfc3339.go new file mode 100644 index 000000000000..a3c99ae03343 --- /dev/null +++ b/sdk/analytics/azonlineexperimentation/time_rfc3339.go @@ -0,0 +1,109 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package azonlineexperimentation + +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 +} diff --git a/sdk/analytics/azonlineexperimentation/tsp-location.yaml b/sdk/analytics/azonlineexperimentation/tsp-location.yaml new file mode 100644 index 000000000000..ebab615093a5 --- /dev/null +++ b/sdk/analytics/azonlineexperimentation/tsp-location.yaml @@ -0,0 +1,4 @@ +directory: specification/onlineexperimentation/Azure.Analytics.OnlineExperimentation +commit: 1f578543d267d08febc1bebf4e33ffe14363ddfc +repo: Azure/azure-rest-api-specs +additionalDirectories: diff --git a/sdk/batch/azbatch/CHANGELOG.md b/sdk/batch/azbatch/CHANGELOG.md new file mode 100644 index 000000000000..6d24208ccaf2 --- /dev/null +++ b/sdk/batch/azbatch/CHANGELOG.md @@ -0,0 +1,8 @@ +# Release History + +## 0.1.0 (2025-04-27) +### Other Changes + +The package of `github.com/Azure/azure-sdk-for-go/sdk/batch/azbatch` 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/batch/azbatch/LICENSE.txt b/sdk/batch/azbatch/LICENSE.txt new file mode 100644 index 000000000000..dc0c2ffb3dc1 --- /dev/null +++ b/sdk/batch/azbatch/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/batch/azbatch/README.md b/sdk/batch/azbatch/README.md new file mode 100644 index 000000000000..f623d9701d1c --- /dev/null +++ b/sdk/batch/azbatch/README.md @@ -0,0 +1,90 @@ +# Azure Batch Module for Go + +The `azbatch` module provides operations for working with Azure Batch. + +[Source code](https://github.com/Azure/azure-sdk-for-go/tree/main/sdk/batch/azbatch) + +# 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 Batch module: + +```sh +go get github.com/Azure/azure-sdk-for-go/sdk/batch/azbatch +``` + +## Authorization + +When creating a client, you will need to provide a credential for authenticating with Azure Batch. 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 Batch 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 := azbatch.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 := azbatch.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.() +``` + +## 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 `Batch` 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/batch/azbatch/ci.yml b/sdk/batch/azbatch/ci.yml new file mode 100644 index 000000000000..15874a4787c7 --- /dev/null +++ b/sdk/batch/azbatch/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/batch/azbatch/ + +pr: + branches: + include: + - main + - feature/* + - hotfix/* + - release/* + paths: + include: + - sdk/batch/azbatch/ + +extends: + template: /eng/pipelines/templates/jobs/archetype-sdk-client.yml + parameters: + ServiceDirectory: 'batch/azbatch' diff --git a/sdk/batch/azbatch/client.go b/sdk/batch/azbatch/client.go new file mode 100644 index 000000000000..ba46e73384c0 --- /dev/null +++ b/sdk/batch/azbatch/client.go @@ -0,0 +1,7590 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package azbatch + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strconv" + "strings" + "time" +) + +// Client contains the methods for the group. +// Don't use this type directly, use a constructor function instead. +type Client struct { + internal *azcore.Client + endpoint string +} + +// CancelCertificateDeletion - Cancels a failed deletion of a Certificate from the specified Account. +// +// If you try to delete a Certificate that is being used by a Pool or Compute +// Node, the status of the Certificate changes to deleteFailed. If you decide that +// you want to continue using the Certificate, you can use this operation to set +// the status of the Certificate back to active. If you intend to delete the +// Certificate, you do not need to run this operation after the deletion failed. +// You must make sure that the Certificate is not being used by any resources, and +// then you can try again to delete the Certificate. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-07-01.20.0 +// - thumbprintAlgorithm - The algorithm used to derive the thumbprint parameter. This must be sha1. +// - thumbprint - The thumbprint of the Certificate being deleted. +// - options - CancelCertificateDeletionOptions contains the optional parameters for the Client.CancelCertificateDeletion method. +func (client *Client) CancelCertificateDeletion(ctx context.Context, thumbprintAlgorithm string, thumbprint string, options *CancelCertificateDeletionOptions) (CancelCertificateDeletionResponse, error) { + var err error + ctx, endSpan := runtime.StartSpan(ctx, "Client.CancelCertificateDeletion", client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.cancelCertificateDeletionCreateRequest(ctx, thumbprintAlgorithm, thumbprint, options) + if err != nil { + return CancelCertificateDeletionResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return CancelCertificateDeletionResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return CancelCertificateDeletionResponse{}, err + } + resp, err := client.cancelCertificateDeletionHandleResponse(httpResp) + return resp, err +} + +// cancelCertificateDeletionCreateRequest creates the CancelCertificateDeletion request. +func (client *Client) cancelCertificateDeletionCreateRequest(ctx context.Context, thumbprintAlgorithm string, thumbprint string, options *CancelCertificateDeletionOptions) (*policy.Request, error) { + host := "{endpoint}" + host = strings.ReplaceAll(host, "{endpoint}", client.endpoint) + urlPath := "/certificates(thumbprintAlgorithm={thumbprintAlgorithm},thumbprint={thumbprint})/canceldelete" + if thumbprintAlgorithm == "" { + return nil, errors.New("parameter thumbprintAlgorithm cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{thumbprintAlgorithm}", url.PathEscape(thumbprintAlgorithm)) + if thumbprint == "" { + return nil, errors.New("parameter thumbprint cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{thumbprint}", url.PathEscape(thumbprint)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2024-07-01.20.0") + if options != nil && options.Timeout != nil { + reqQP.Set("timeOut", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.Ocpdate != nil { + req.Raw().Header["ocp-date"] = []string{options.Ocpdate.Format(time.RFC1123)} + } + if options != nil && options.ReturnClientRequestID != nil { + req.Raw().Header["return-client-request-id"] = []string{strconv.FormatBool(*options.ReturnClientRequestID)} + } + return req, nil +} + +// cancelCertificateDeletionHandleResponse handles the CancelCertificateDeletion response. +func (client *Client) cancelCertificateDeletionHandleResponse(resp *http.Response) (CancelCertificateDeletionResponse, error) { + result := CancelCertificateDeletionResponse{} + if val := resp.Header.Get("client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("DataServiceId"); val != "" { + result.DataServiceID = &val + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = &val + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return CancelCertificateDeletionResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("request-id"); val != "" { + result.RequestID = &val + } + return result, nil +} + +// CreateCertificate - Creates a Certificate to the specified Account. +// +// Creates a Certificate to the specified Account. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-07-01.20.0 +// - certificate - The Certificate to be created. +// - options - CreateCertificateOptions contains the optional parameters for the Client.CreateCertificate method. +func (client *Client) CreateCertificate(ctx context.Context, certificate Certificate, options *CreateCertificateOptions) (CreateCertificateResponse, error) { + var err error + ctx, endSpan := runtime.StartSpan(ctx, "Client.CreateCertificate", client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createCertificateCreateRequest(ctx, certificate, options) + if err != nil { + return CreateCertificateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return CreateCertificateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return CreateCertificateResponse{}, err + } + resp, err := client.createCertificateHandleResponse(httpResp) + return resp, err +} + +// createCertificateCreateRequest creates the CreateCertificate request. +func (client *Client) createCertificateCreateRequest(ctx context.Context, certificate Certificate, options *CreateCertificateOptions) (*policy.Request, error) { + host := "{endpoint}" + host = strings.ReplaceAll(host, "{endpoint}", client.endpoint) + urlPath := "/certificates" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2024-07-01.20.0") + if options != nil && options.Timeout != nil { + reqQP.Set("timeOut", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.Ocpdate != nil { + req.Raw().Header["ocp-date"] = []string{options.Ocpdate.Format(time.RFC1123)} + } + if options != nil && options.ReturnClientRequestID != nil { + req.Raw().Header["return-client-request-id"] = []string{strconv.FormatBool(*options.ReturnClientRequestID)} + } + req.Raw().Header["Content-Type"] = []string{"application/json; odata=minimalmetadata"} + if err := runtime.MarshalAsJSON(req, certificate); err != nil { + return nil, err + } + return req, nil +} + +// createCertificateHandleResponse handles the CreateCertificate response. +func (client *Client) createCertificateHandleResponse(resp *http.Response) (CreateCertificateResponse, error) { + result := CreateCertificateResponse{} + if val := resp.Header.Get("client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("DataServiceId"); val != "" { + result.DataServiceID = &val + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = &val + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return CreateCertificateResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("request-id"); val != "" { + result.RequestID = &val + } + return result, nil +} + +// CreateJob - Creates a Job to the specified Account. +// +// The Batch service supports two ways to control the work done as part of a Job. +// In the first approach, the user specifies a Job Manager Task. The Batch service +// launches this Task when it is ready to start the Job. The Job Manager Task +// controls all other Tasks that run under this Job, by using the Task APIs. In +// the second approach, the user directly controls the execution of Tasks under an +// active Job, by using the Task APIs. Also note: when naming Jobs, avoid +// including sensitive information such as user names or secret project names. +// This information may appear in telemetry logs accessible to Microsoft Support +// engineers. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-07-01.20.0 +// - job - The Job to be created. +// - options - CreateJobOptions contains the optional parameters for the Client.CreateJob method. +func (client *Client) CreateJob(ctx context.Context, job CreateJobContent, options *CreateJobOptions) (CreateJobResponse, error) { + var err error + ctx, endSpan := runtime.StartSpan(ctx, "Client.CreateJob", client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createJobCreateRequest(ctx, job, options) + if err != nil { + return CreateJobResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return CreateJobResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return CreateJobResponse{}, err + } + resp, err := client.createJobHandleResponse(httpResp) + return resp, err +} + +// createJobCreateRequest creates the CreateJob request. +func (client *Client) createJobCreateRequest(ctx context.Context, job CreateJobContent, options *CreateJobOptions) (*policy.Request, error) { + host := "{endpoint}" + host = strings.ReplaceAll(host, "{endpoint}", client.endpoint) + urlPath := "/jobs" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2024-07-01.20.0") + if options != nil && options.Timeout != nil { + reqQP.Set("timeOut", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.Ocpdate != nil { + req.Raw().Header["ocp-date"] = []string{options.Ocpdate.Format(time.RFC1123)} + } + if options != nil && options.ReturnClientRequestID != nil { + req.Raw().Header["return-client-request-id"] = []string{strconv.FormatBool(*options.ReturnClientRequestID)} + } + req.Raw().Header["Content-Type"] = []string{"application/json; odata=minimalmetadata"} + if err := runtime.MarshalAsJSON(req, job); err != nil { + return nil, err + } + return req, nil +} + +// createJobHandleResponse handles the CreateJob response. +func (client *Client) createJobHandleResponse(resp *http.Response) (CreateJobResponse, error) { + result := CreateJobResponse{} + if val := resp.Header.Get("client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("DataServiceId"); val != "" { + result.DataServiceID = &val + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = &val + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return CreateJobResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("request-id"); val != "" { + result.RequestID = &val + } + return result, nil +} + +// CreateJobSchedule - Creates a Job Schedule to the specified Account. +// +// Creates a Job Schedule to the specified Account. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-07-01.20.0 +// - jobSchedule - The Job Schedule to be created. +// - options - CreateJobScheduleOptions contains the optional parameters for the Client.CreateJobSchedule method. +func (client *Client) CreateJobSchedule(ctx context.Context, jobSchedule CreateJobScheduleContent, options *CreateJobScheduleOptions) (CreateJobScheduleResponse, error) { + var err error + ctx, endSpan := runtime.StartSpan(ctx, "Client.CreateJobSchedule", client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createJobScheduleCreateRequest(ctx, jobSchedule, options) + if err != nil { + return CreateJobScheduleResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return CreateJobScheduleResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return CreateJobScheduleResponse{}, err + } + resp, err := client.createJobScheduleHandleResponse(httpResp) + return resp, err +} + +// createJobScheduleCreateRequest creates the CreateJobSchedule request. +func (client *Client) createJobScheduleCreateRequest(ctx context.Context, jobSchedule CreateJobScheduleContent, options *CreateJobScheduleOptions) (*policy.Request, error) { + host := "{endpoint}" + host = strings.ReplaceAll(host, "{endpoint}", client.endpoint) + urlPath := "/jobschedules" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2024-07-01.20.0") + if options != nil && options.Timeout != nil { + reqQP.Set("timeOut", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.Ocpdate != nil { + req.Raw().Header["ocp-date"] = []string{options.Ocpdate.Format(time.RFC1123)} + } + if options != nil && options.ReturnClientRequestID != nil { + req.Raw().Header["return-client-request-id"] = []string{strconv.FormatBool(*options.ReturnClientRequestID)} + } + req.Raw().Header["Content-Type"] = []string{"application/json; odata=minimalmetadata"} + if err := runtime.MarshalAsJSON(req, jobSchedule); err != nil { + return nil, err + } + return req, nil +} + +// createJobScheduleHandleResponse handles the CreateJobSchedule response. +func (client *Client) createJobScheduleHandleResponse(resp *http.Response) (CreateJobScheduleResponse, error) { + result := CreateJobScheduleResponse{} + if val := resp.Header.Get("client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("DataServiceId"); val != "" { + result.DataServiceID = &val + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = &val + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return CreateJobScheduleResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("request-id"); val != "" { + result.RequestID = &val + } + return result, nil +} + +// CreateNodeUser - Adds a user Account to the specified Compute Node. +// +// You can add a user Account to a Compute Node only when it is in the idle or +// running state. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-07-01.20.0 +// - poolID - The ID of the Pool that contains the Compute Node. +// - nodeID - The ID of the machine on which you want to create a user Account. +// - userParam - The options to use for creating the user. +// - options - CreateNodeUserOptions contains the optional parameters for the Client.CreateNodeUser method. +func (client *Client) CreateNodeUser(ctx context.Context, poolID string, nodeID string, userParam CreateNodeUserContent, options *CreateNodeUserOptions) (CreateNodeUserResponse, error) { + var err error + ctx, endSpan := runtime.StartSpan(ctx, "Client.CreateNodeUser", client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createNodeUserCreateRequest(ctx, poolID, nodeID, userParam, options) + if err != nil { + return CreateNodeUserResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return CreateNodeUserResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return CreateNodeUserResponse{}, err + } + resp, err := client.createNodeUserHandleResponse(httpResp) + return resp, err +} + +// createNodeUserCreateRequest creates the CreateNodeUser request. +func (client *Client) createNodeUserCreateRequest(ctx context.Context, poolID string, nodeID string, userParam CreateNodeUserContent, options *CreateNodeUserOptions) (*policy.Request, error) { + host := "{endpoint}" + host = strings.ReplaceAll(host, "{endpoint}", client.endpoint) + urlPath := "/pools/{poolId}/nodes/{nodeId}/users" + if poolID == "" { + return nil, errors.New("parameter poolID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{poolId}", url.PathEscape(poolID)) + if nodeID == "" { + return nil, errors.New("parameter nodeID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{nodeId}", url.PathEscape(nodeID)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2024-07-01.20.0") + if options != nil && options.Timeout != nil { + reqQP.Set("timeOut", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.Ocpdate != nil { + req.Raw().Header["ocp-date"] = []string{options.Ocpdate.Format(time.RFC1123)} + } + if options != nil && options.ReturnClientRequestID != nil { + req.Raw().Header["return-client-request-id"] = []string{strconv.FormatBool(*options.ReturnClientRequestID)} + } + req.Raw().Header["Content-Type"] = []string{"application/json; odata=minimalmetadata"} + if err := runtime.MarshalAsJSON(req, userParam); err != nil { + return nil, err + } + return req, nil +} + +// createNodeUserHandleResponse handles the CreateNodeUser response. +func (client *Client) createNodeUserHandleResponse(resp *http.Response) (CreateNodeUserResponse, error) { + result := CreateNodeUserResponse{} + if val := resp.Header.Get("client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("DataServiceId"); val != "" { + result.DataServiceID = &val + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = &val + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return CreateNodeUserResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("request-id"); val != "" { + result.RequestID = &val + } + return result, nil +} + +// CreatePool - Creates a Pool to the specified Account. +// +// When naming Pools, avoid including sensitive information such as user names or +// secret project names. This information may appear in telemetry logs accessible +// to Microsoft Support engineers. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-07-01.20.0 +// - pool - The Pool to be created. +// - options - CreatePoolOptions contains the optional parameters for the Client.CreatePool method. +func (client *Client) CreatePool(ctx context.Context, pool CreatePoolContent, options *CreatePoolOptions) (CreatePoolResponse, error) { + var err error + ctx, endSpan := runtime.StartSpan(ctx, "Client.CreatePool", client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createPoolCreateRequest(ctx, pool, options) + if err != nil { + return CreatePoolResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return CreatePoolResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return CreatePoolResponse{}, err + } + resp, err := client.createPoolHandleResponse(httpResp) + return resp, err +} + +// createPoolCreateRequest creates the CreatePool request. +func (client *Client) createPoolCreateRequest(ctx context.Context, pool CreatePoolContent, options *CreatePoolOptions) (*policy.Request, error) { + host := "{endpoint}" + host = strings.ReplaceAll(host, "{endpoint}", client.endpoint) + urlPath := "/pools" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2024-07-01.20.0") + if options != nil && options.Timeout != nil { + reqQP.Set("timeOut", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.Ocpdate != nil { + req.Raw().Header["ocp-date"] = []string{options.Ocpdate.Format(time.RFC1123)} + } + if options != nil && options.ReturnClientRequestID != nil { + req.Raw().Header["return-client-request-id"] = []string{strconv.FormatBool(*options.ReturnClientRequestID)} + } + req.Raw().Header["Content-Type"] = []string{"application/json; odata=minimalmetadata"} + if err := runtime.MarshalAsJSON(req, pool); err != nil { + return nil, err + } + return req, nil +} + +// createPoolHandleResponse handles the CreatePool response. +func (client *Client) createPoolHandleResponse(resp *http.Response) (CreatePoolResponse, error) { + result := CreatePoolResponse{} + if val := resp.Header.Get("client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("DataServiceId"); val != "" { + result.DataServiceID = &val + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = &val + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return CreatePoolResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("request-id"); val != "" { + result.RequestID = &val + } + return result, nil +} + +// CreateTask - Creates a Task to the specified Job. +// +// The maximum lifetime of a Task from addition to completion is 180 days. If a +// Task has not completed within 180 days of being added it will be terminated by +// the Batch service and left in whatever state it was in at that time. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-07-01.20.0 +// - jobID - The ID of the Job to which the Task is to be created. +// - task - The Task to be created. +// - options - CreateTaskOptions contains the optional parameters for the Client.CreateTask method. +func (client *Client) CreateTask(ctx context.Context, jobID string, task CreateTaskContent, options *CreateTaskOptions) (CreateTaskResponse, error) { + var err error + ctx, endSpan := runtime.StartSpan(ctx, "Client.CreateTask", client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createTaskCreateRequest(ctx, jobID, task, options) + if err != nil { + return CreateTaskResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return CreateTaskResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return CreateTaskResponse{}, err + } + resp, err := client.createTaskHandleResponse(httpResp) + return resp, err +} + +// createTaskCreateRequest creates the CreateTask request. +func (client *Client) createTaskCreateRequest(ctx context.Context, jobID string, task CreateTaskContent, options *CreateTaskOptions) (*policy.Request, error) { + host := "{endpoint}" + host = strings.ReplaceAll(host, "{endpoint}", client.endpoint) + urlPath := "/jobs/{jobId}/tasks" + if jobID == "" { + return nil, errors.New("parameter jobID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{jobId}", url.PathEscape(jobID)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2024-07-01.20.0") + if options != nil && options.Timeout != nil { + reqQP.Set("timeOut", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.Ocpdate != nil { + req.Raw().Header["ocp-date"] = []string{options.Ocpdate.Format(time.RFC1123)} + } + if options != nil && options.ReturnClientRequestID != nil { + req.Raw().Header["return-client-request-id"] = []string{strconv.FormatBool(*options.ReturnClientRequestID)} + } + req.Raw().Header["Content-Type"] = []string{"application/json; odata=minimalmetadata"} + if err := runtime.MarshalAsJSON(req, task); err != nil { + return nil, err + } + return req, nil +} + +// createTaskHandleResponse handles the CreateTask response. +func (client *Client) createTaskHandleResponse(resp *http.Response) (CreateTaskResponse, error) { + result := CreateTaskResponse{} + if val := resp.Header.Get("client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("DataServiceId"); val != "" { + result.DataServiceID = &val + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = &val + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return CreateTaskResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("request-id"); val != "" { + result.RequestID = &val + } + return result, nil +} + +// CreateTaskCollection - Adds a collection of Tasks to the specified Job. +// +// Note that each Task must have a unique ID. The Batch service may not return the +// results for each Task in the same order the Tasks were submitted in this +// request. If the server times out or the connection is closed during the +// request, the request may have been partially or fully processed, or not at all. +// In such cases, the user should re-issue the request. Note that it is up to the +// user to correctly handle failures when re-issuing a request. For example, you +// should use the same Task IDs during a retry so that if the prior operation +// succeeded, the retry will not create extra Tasks unexpectedly. If the response +// contains any Tasks which failed to add, a client can retry the request. In a +// retry, it is most efficient to resubmit only Tasks that failed to add, and to +// omit Tasks that were successfully added on the first attempt. The maximum +// lifetime of a Task from addition to completion is 180 days. If a Task has not +// completed within 180 days of being added it will be terminated by the Batch +// service and left in whatever state it was in at that time. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-07-01.20.0 +// - jobID - The ID of the Job to which the Task collection is to be added. +// - taskCollection - The Tasks to be added. +// - options - CreateTaskCollectionOptions contains the optional parameters for the Client.CreateTaskCollection method. +func (client *Client) CreateTaskCollection(ctx context.Context, jobID string, taskCollection TaskGroup, options *CreateTaskCollectionOptions) (CreateTaskCollectionResponse, error) { + var err error + ctx, endSpan := runtime.StartSpan(ctx, "Client.CreateTaskCollection", client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createTaskCollectionCreateRequest(ctx, jobID, taskCollection, options) + if err != nil { + return CreateTaskCollectionResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return CreateTaskCollectionResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return CreateTaskCollectionResponse{}, err + } + resp, err := client.createTaskCollectionHandleResponse(httpResp) + return resp, err +} + +// createTaskCollectionCreateRequest creates the CreateTaskCollection request. +func (client *Client) createTaskCollectionCreateRequest(ctx context.Context, jobID string, taskCollection TaskGroup, options *CreateTaskCollectionOptions) (*policy.Request, error) { + host := "{endpoint}" + host = strings.ReplaceAll(host, "{endpoint}", client.endpoint) + urlPath := "/jobs/{jobId}/addtaskcollection" + if jobID == "" { + return nil, errors.New("parameter jobID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{jobId}", url.PathEscape(jobID)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2024-07-01.20.0") + if options != nil && options.Timeout != nil { + reqQP.Set("timeOut", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.Ocpdate != nil { + req.Raw().Header["ocp-date"] = []string{options.Ocpdate.Format(time.RFC1123)} + } + if options != nil && options.ReturnClientRequestID != nil { + req.Raw().Header["return-client-request-id"] = []string{strconv.FormatBool(*options.ReturnClientRequestID)} + } + req.Raw().Header["Content-Type"] = []string{"application/json; odata=minimalmetadata"} + if err := runtime.MarshalAsJSON(req, taskCollection); err != nil { + return nil, err + } + return req, nil +} + +// createTaskCollectionHandleResponse handles the CreateTaskCollection response. +func (client *Client) createTaskCollectionHandleResponse(resp *http.Response) (CreateTaskCollectionResponse, error) { + result := CreateTaskCollectionResponse{} + if val := resp.Header.Get("client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = &val + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return CreateTaskCollectionResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("request-id"); val != "" { + result.RequestID = &val + } + if err := runtime.UnmarshalAsJSON(resp, &result.AddTaskCollectionResult); err != nil { + return CreateTaskCollectionResponse{}, err + } + return result, nil +} + +// DeallocateNode - Deallocates the specified Compute Node. +// +// You can deallocate a Compute Node only if it is in an idle or running state. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-07-01.20.0 +// - poolID - The ID of the Pool that contains the Compute Node. +// - nodeID - The ID of the Compute Node that you want to restart. +// - options - DeallocateNodeOptions contains the optional parameters for the Client.DeallocateNode method. +func (client *Client) DeallocateNode(ctx context.Context, poolID string, nodeID string, options *DeallocateNodeOptions) (DeallocateNodeResponse, error) { + var err error + ctx, endSpan := runtime.StartSpan(ctx, "Client.DeallocateNode", client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deallocateNodeCreateRequest(ctx, poolID, nodeID, options) + if err != nil { + return DeallocateNodeResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DeallocateNodeResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return DeallocateNodeResponse{}, err + } + resp, err := client.deallocateNodeHandleResponse(httpResp) + return resp, err +} + +// deallocateNodeCreateRequest creates the DeallocateNode request. +func (client *Client) deallocateNodeCreateRequest(ctx context.Context, poolID string, nodeID string, options *DeallocateNodeOptions) (*policy.Request, error) { + host := "{endpoint}" + host = strings.ReplaceAll(host, "{endpoint}", client.endpoint) + urlPath := "/pools/{poolId}/nodes/{nodeId}/deallocate" + if poolID == "" { + return nil, errors.New("parameter poolID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{poolId}", url.PathEscape(poolID)) + if nodeID == "" { + return nil, errors.New("parameter nodeID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{nodeId}", url.PathEscape(nodeID)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2024-07-01.20.0") + if options != nil && options.Timeout != nil { + reqQP.Set("timeOut", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.Ocpdate != nil { + req.Raw().Header["ocp-date"] = []string{options.Ocpdate.Format(time.RFC1123)} + } + if options != nil && options.ReturnClientRequestID != nil { + req.Raw().Header["return-client-request-id"] = []string{strconv.FormatBool(*options.ReturnClientRequestID)} + } + if options != nil && options.Parameters != nil { + req.Raw().Header["Content-Type"] = []string{"application/json; odata=minimalmetadata"} + if err := runtime.MarshalAsJSON(req, *options.Parameters); err != nil { + return nil, err + } + return req, nil + } + return req, nil +} + +// deallocateNodeHandleResponse handles the DeallocateNode response. +func (client *Client) deallocateNodeHandleResponse(resp *http.Response) (DeallocateNodeResponse, error) { + result := DeallocateNodeResponse{} + if val := resp.Header.Get("client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("DataServiceId"); val != "" { + result.DataServiceID = &val + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = &val + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return DeallocateNodeResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("request-id"); val != "" { + result.RequestID = &val + } + return result, nil +} + +// DeleteCertificate - Deletes a Certificate from the specified Account. +// +// You cannot delete a Certificate if a resource (Pool or Compute Node) is using +// it. Before you can delete a Certificate, you must therefore make sure that the +// Certificate is not associated with any existing Pools, the Certificate is not +// installed on any Nodes (even if you remove a Certificate from a Pool, it is not +// removed from existing Compute Nodes in that Pool until they restart), and no +// running Tasks depend on the Certificate. If you try to delete a Certificate +// that is in use, the deletion fails. The Certificate status changes to +// deleteFailed. You can use Cancel Delete Certificate to set the status back to +// active if you decide that you want to continue using the Certificate. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-07-01.20.0 +// - thumbprintAlgorithm - The algorithm used to derive the thumbprint parameter. This must be sha1. +// - thumbprint - The thumbprint of the Certificate to be deleted. +// - options - DeleteCertificateOptions contains the optional parameters for the Client.DeleteCertificate method. +func (client *Client) DeleteCertificate(ctx context.Context, thumbprintAlgorithm string, thumbprint string, options *DeleteCertificateOptions) (DeleteCertificateResponse, error) { + var err error + ctx, endSpan := runtime.StartSpan(ctx, "Client.DeleteCertificate", client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCertificateCreateRequest(ctx, thumbprintAlgorithm, thumbprint, options) + if err != nil { + return DeleteCertificateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DeleteCertificateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return DeleteCertificateResponse{}, err + } + resp, err := client.deleteCertificateHandleResponse(httpResp) + return resp, err +} + +// deleteCertificateCreateRequest creates the DeleteCertificate request. +func (client *Client) deleteCertificateCreateRequest(ctx context.Context, thumbprintAlgorithm string, thumbprint string, options *DeleteCertificateOptions) (*policy.Request, error) { + host := "{endpoint}" + host = strings.ReplaceAll(host, "{endpoint}", client.endpoint) + urlPath := "/certificates(thumbprintAlgorithm={thumbprintAlgorithm},thumbprint={thumbprint})" + if thumbprintAlgorithm == "" { + return nil, errors.New("parameter thumbprintAlgorithm cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{thumbprintAlgorithm}", url.PathEscape(thumbprintAlgorithm)) + if thumbprint == "" { + return nil, errors.New("parameter thumbprint cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{thumbprint}", url.PathEscape(thumbprint)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2024-07-01.20.0") + if options != nil && options.Timeout != nil { + reqQP.Set("timeOut", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.Ocpdate != nil { + req.Raw().Header["ocp-date"] = []string{options.Ocpdate.Format(time.RFC1123)} + } + if options != nil && options.ReturnClientRequestID != nil { + req.Raw().Header["return-client-request-id"] = []string{strconv.FormatBool(*options.ReturnClientRequestID)} + } + return req, nil +} + +// deleteCertificateHandleResponse handles the DeleteCertificate response. +func (client *Client) deleteCertificateHandleResponse(resp *http.Response) (DeleteCertificateResponse, error) { + result := DeleteCertificateResponse{} + if val := resp.Header.Get("client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = &val + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return DeleteCertificateResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("request-id"); val != "" { + result.RequestID = &val + } + return result, nil +} + +// DeleteJob - Deletes a Job. +// +// Deleting a Job also deletes all Tasks that are part of that Job, and all Job +// statistics. This also overrides the retention period for Task data; that is, if +// the Job contains Tasks which are still retained on Compute Nodes, the Batch +// services deletes those Tasks' working directories and all their contents. When +// a Delete Job request is received, the Batch service sets the Job to the +// deleting state. All update operations on a Job that is in deleting state will +// fail with status code 409 (Conflict), with additional information indicating +// that the Job is being deleted. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-07-01.20.0 +// - jobID - The ID of the Job to delete. +// - options - DeleteJobOptions contains the optional parameters for the Client.DeleteJob method. +func (client *Client) DeleteJob(ctx context.Context, jobID string, options *DeleteJobOptions) (DeleteJobResponse, error) { + var err error + ctx, endSpan := runtime.StartSpan(ctx, "Client.DeleteJob", client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteJobCreateRequest(ctx, jobID, options) + if err != nil { + return DeleteJobResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DeleteJobResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return DeleteJobResponse{}, err + } + resp, err := client.deleteJobHandleResponse(httpResp) + return resp, err +} + +// deleteJobCreateRequest creates the DeleteJob request. +func (client *Client) deleteJobCreateRequest(ctx context.Context, jobID string, options *DeleteJobOptions) (*policy.Request, error) { + host := "{endpoint}" + host = strings.ReplaceAll(host, "{endpoint}", client.endpoint) + urlPath := "/jobs/{jobId}" + if jobID == "" { + return nil, errors.New("parameter jobID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{jobId}", url.PathEscape(jobID)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2024-07-01.20.0") + if options != nil && options.Force != nil { + reqQP.Set("force", strconv.FormatBool(*options.Force)) + } + if options != nil && options.Timeout != nil { + reqQP.Set("timeOut", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.IfMatch != nil { + req.Raw().Header["If-Match"] = []string{*options.IfMatch} + } + if options != nil && options.IfModifiedSince != nil { + req.Raw().Header["If-Modified-Since"] = []string{options.IfModifiedSince.Format(time.RFC1123)} + } + if options != nil && options.IfNoneMatch != nil { + req.Raw().Header["If-None-Match"] = []string{*options.IfNoneMatch} + } + if options != nil && options.IfUnmodifiedSince != nil { + req.Raw().Header["If-Unmodified-Since"] = []string{options.IfUnmodifiedSince.Format(time.RFC1123)} + } + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.Ocpdate != nil { + req.Raw().Header["ocp-date"] = []string{options.Ocpdate.Format(time.RFC1123)} + } + if options != nil && options.ReturnClientRequestID != nil { + req.Raw().Header["return-client-request-id"] = []string{strconv.FormatBool(*options.ReturnClientRequestID)} + } + return req, nil +} + +// deleteJobHandleResponse handles the DeleteJob response. +func (client *Client) deleteJobHandleResponse(resp *http.Response) (DeleteJobResponse, error) { + result := DeleteJobResponse{} + if val := resp.Header.Get("client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("request-id"); val != "" { + result.RequestID = &val + } + return result, nil +} + +// DeleteJobSchedule - Deletes a Job Schedule from the specified Account. +// +// When you delete a Job Schedule, this also deletes all Jobs and Tasks under that +// schedule. When Tasks are deleted, all the files in their working directories on +// the Compute Nodes are also deleted (the retention period is ignored). The Job +// Schedule statistics are no longer accessible once the Job Schedule is deleted, +// though they are still counted towards Account lifetime statistics. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-07-01.20.0 +// - jobScheduleID - The ID of the Job Schedule to delete. +// - options - DeleteJobScheduleOptions contains the optional parameters for the Client.DeleteJobSchedule method. +func (client *Client) DeleteJobSchedule(ctx context.Context, jobScheduleID string, options *DeleteJobScheduleOptions) (DeleteJobScheduleResponse, error) { + var err error + ctx, endSpan := runtime.StartSpan(ctx, "Client.DeleteJobSchedule", client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteJobScheduleCreateRequest(ctx, jobScheduleID, options) + if err != nil { + return DeleteJobScheduleResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DeleteJobScheduleResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return DeleteJobScheduleResponse{}, err + } + resp, err := client.deleteJobScheduleHandleResponse(httpResp) + return resp, err +} + +// deleteJobScheduleCreateRequest creates the DeleteJobSchedule request. +func (client *Client) deleteJobScheduleCreateRequest(ctx context.Context, jobScheduleID string, options *DeleteJobScheduleOptions) (*policy.Request, error) { + host := "{endpoint}" + host = strings.ReplaceAll(host, "{endpoint}", client.endpoint) + urlPath := "/jobschedules/{jobScheduleId}" + if jobScheduleID == "" { + return nil, errors.New("parameter jobScheduleID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{jobScheduleId}", url.PathEscape(jobScheduleID)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2024-07-01.20.0") + if options != nil && options.Force != nil { + reqQP.Set("force", strconv.FormatBool(*options.Force)) + } + if options != nil && options.Timeout != nil { + reqQP.Set("timeOut", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.IfMatch != nil { + req.Raw().Header["If-Match"] = []string{*options.IfMatch} + } + if options != nil && options.IfModifiedSince != nil { + req.Raw().Header["If-Modified-Since"] = []string{options.IfModifiedSince.Format(time.RFC1123)} + } + if options != nil && options.IfNoneMatch != nil { + req.Raw().Header["If-None-Match"] = []string{*options.IfNoneMatch} + } + if options != nil && options.IfUnmodifiedSince != nil { + req.Raw().Header["If-Unmodified-Since"] = []string{options.IfUnmodifiedSince.Format(time.RFC1123)} + } + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.Ocpdate != nil { + req.Raw().Header["ocp-date"] = []string{options.Ocpdate.Format(time.RFC1123)} + } + if options != nil && options.ReturnClientRequestID != nil { + req.Raw().Header["return-client-request-id"] = []string{strconv.FormatBool(*options.ReturnClientRequestID)} + } + return req, nil +} + +// deleteJobScheduleHandleResponse handles the DeleteJobSchedule response. +func (client *Client) deleteJobScheduleHandleResponse(resp *http.Response) (DeleteJobScheduleResponse, error) { + result := DeleteJobScheduleResponse{} + if val := resp.Header.Get("client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("request-id"); val != "" { + result.RequestID = &val + } + return result, nil +} + +// DeleteNodeFile - Deletes the specified file from the Compute Node. +// +// Deletes the specified file from the Compute Node. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-07-01.20.0 +// - poolID - The ID of the Pool that contains the Compute Node. +// - nodeID - The ID of the Compute Node. +// - filePath - The path to the file or directory. +// - options - DeleteNodeFileOptions contains the optional parameters for the Client.DeleteNodeFile method. +func (client *Client) DeleteNodeFile(ctx context.Context, poolID string, nodeID string, filePath string, options *DeleteNodeFileOptions) (DeleteNodeFileResponse, error) { + var err error + ctx, endSpan := runtime.StartSpan(ctx, "Client.DeleteNodeFile", client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteNodeFileCreateRequest(ctx, poolID, nodeID, filePath, options) + if err != nil { + return DeleteNodeFileResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DeleteNodeFileResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return DeleteNodeFileResponse{}, err + } + resp, err := client.deleteNodeFileHandleResponse(httpResp) + return resp, err +} + +// deleteNodeFileCreateRequest creates the DeleteNodeFile request. +func (client *Client) deleteNodeFileCreateRequest(ctx context.Context, poolID string, nodeID string, filePath string, options *DeleteNodeFileOptions) (*policy.Request, error) { + host := "{endpoint}" + host = strings.ReplaceAll(host, "{endpoint}", client.endpoint) + urlPath := "/pools/{poolId}/nodes/{nodeId}/files/{filePath}" + if poolID == "" { + return nil, errors.New("parameter poolID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{poolId}", url.PathEscape(poolID)) + if nodeID == "" { + return nil, errors.New("parameter nodeID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{nodeId}", url.PathEscape(nodeID)) + if filePath == "" { + return nil, errors.New("parameter filePath cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{filePath}", url.PathEscape(filePath)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2024-07-01.20.0") + if options != nil && options.Recursive != nil { + reqQP.Set("recursive", strconv.FormatBool(*options.Recursive)) + } + if options != nil && options.Timeout != nil { + reqQP.Set("timeOut", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.Ocpdate != nil { + req.Raw().Header["ocp-date"] = []string{options.Ocpdate.Format(time.RFC1123)} + } + if options != nil && options.ReturnClientRequestID != nil { + req.Raw().Header["return-client-request-id"] = []string{strconv.FormatBool(*options.ReturnClientRequestID)} + } + return req, nil +} + +// deleteNodeFileHandleResponse handles the DeleteNodeFile response. +func (client *Client) deleteNodeFileHandleResponse(resp *http.Response) (DeleteNodeFileResponse, error) { + result := DeleteNodeFileResponse{} + if val := resp.Header.Get("client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("request-id"); val != "" { + result.RequestID = &val + } + return result, nil +} + +// DeleteNodeUser - Deletes a user Account from the specified Compute Node. +// +// You can delete a user Account to a Compute Node only when it is in the idle or +// running state. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-07-01.20.0 +// - poolID - The ID of the Pool that contains the Compute Node. +// - nodeID - The ID of the machine on which you want to delete a user Account. +// - userName - The name of the user Account to delete. +// - options - DeleteNodeUserOptions contains the optional parameters for the Client.DeleteNodeUser method. +func (client *Client) DeleteNodeUser(ctx context.Context, poolID string, nodeID string, userName string, options *DeleteNodeUserOptions) (DeleteNodeUserResponse, error) { + var err error + ctx, endSpan := runtime.StartSpan(ctx, "Client.DeleteNodeUser", client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteNodeUserCreateRequest(ctx, poolID, nodeID, userName, options) + if err != nil { + return DeleteNodeUserResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DeleteNodeUserResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return DeleteNodeUserResponse{}, err + } + resp, err := client.deleteNodeUserHandleResponse(httpResp) + return resp, err +} + +// deleteNodeUserCreateRequest creates the DeleteNodeUser request. +func (client *Client) deleteNodeUserCreateRequest(ctx context.Context, poolID string, nodeID string, userName string, options *DeleteNodeUserOptions) (*policy.Request, error) { + host := "{endpoint}" + host = strings.ReplaceAll(host, "{endpoint}", client.endpoint) + urlPath := "/pools/{poolId}/nodes/{nodeId}/users/{userName}" + if poolID == "" { + return nil, errors.New("parameter poolID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{poolId}", url.PathEscape(poolID)) + if nodeID == "" { + return nil, errors.New("parameter nodeID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{nodeId}", url.PathEscape(nodeID)) + if userName == "" { + return nil, errors.New("parameter userName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{userName}", url.PathEscape(userName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2024-07-01.20.0") + if options != nil && options.Timeout != nil { + reqQP.Set("timeOut", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.Ocpdate != nil { + req.Raw().Header["ocp-date"] = []string{options.Ocpdate.Format(time.RFC1123)} + } + if options != nil && options.ReturnClientRequestID != nil { + req.Raw().Header["return-client-request-id"] = []string{strconv.FormatBool(*options.ReturnClientRequestID)} + } + return req, nil +} + +// deleteNodeUserHandleResponse handles the DeleteNodeUser response. +func (client *Client) deleteNodeUserHandleResponse(resp *http.Response) (DeleteNodeUserResponse, error) { + result := DeleteNodeUserResponse{} + if val := resp.Header.Get("client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("request-id"); val != "" { + result.RequestID = &val + } + return result, nil +} + +// DeletePool - Deletes a Pool from the specified Account. +// +// When you request that a Pool be deleted, the following actions occur: the Pool +// state is set to deleting; any ongoing resize operation on the Pool are stopped; +// the Batch service starts resizing the Pool to zero Compute Nodes; any Tasks +// running on existing Compute Nodes are terminated and requeued (as if a resize +// Pool operation had been requested with the default requeue option); finally, +// the Pool is removed from the system. Because running Tasks are requeued, the +// user can rerun these Tasks by updating their Job to target a different Pool. +// The Tasks can then run on the new Pool. If you want to override the requeue +// behavior, then you should call resize Pool explicitly to shrink the Pool to +// zero size before deleting the Pool. If you call an Update, Patch or Delete API +// on a Pool in the deleting state, it will fail with HTTP status code 409 with +// error code PoolBeingDeleted. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-07-01.20.0 +// - poolID - The ID of the Pool to get. +// - options - DeletePoolOptions contains the optional parameters for the Client.DeletePool method. +func (client *Client) DeletePool(ctx context.Context, poolID string, options *DeletePoolOptions) (DeletePoolResponse, error) { + var err error + ctx, endSpan := runtime.StartSpan(ctx, "Client.DeletePool", client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deletePoolCreateRequest(ctx, poolID, options) + if err != nil { + return DeletePoolResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DeletePoolResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return DeletePoolResponse{}, err + } + resp, err := client.deletePoolHandleResponse(httpResp) + return resp, err +} + +// deletePoolCreateRequest creates the DeletePool request. +func (client *Client) deletePoolCreateRequest(ctx context.Context, poolID string, options *DeletePoolOptions) (*policy.Request, error) { + host := "{endpoint}" + host = strings.ReplaceAll(host, "{endpoint}", client.endpoint) + urlPath := "/pools/{poolId}" + if poolID == "" { + return nil, errors.New("parameter poolID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{poolId}", url.PathEscape(poolID)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2024-07-01.20.0") + if options != nil && options.Timeout != nil { + reqQP.Set("timeOut", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.IfMatch != nil { + req.Raw().Header["If-Match"] = []string{*options.IfMatch} + } + if options != nil && options.IfModifiedSince != nil { + req.Raw().Header["If-Modified-Since"] = []string{options.IfModifiedSince.Format(time.RFC1123)} + } + if options != nil && options.IfNoneMatch != nil { + req.Raw().Header["If-None-Match"] = []string{*options.IfNoneMatch} + } + if options != nil && options.IfUnmodifiedSince != nil { + req.Raw().Header["If-Unmodified-Since"] = []string{options.IfUnmodifiedSince.Format(time.RFC1123)} + } + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.Ocpdate != nil { + req.Raw().Header["ocp-date"] = []string{options.Ocpdate.Format(time.RFC1123)} + } + if options != nil && options.ReturnClientRequestID != nil { + req.Raw().Header["return-client-request-id"] = []string{strconv.FormatBool(*options.ReturnClientRequestID)} + } + return req, nil +} + +// deletePoolHandleResponse handles the DeletePool response. +func (client *Client) deletePoolHandleResponse(resp *http.Response) (DeletePoolResponse, error) { + result := DeletePoolResponse{} + if val := resp.Header.Get("client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("request-id"); val != "" { + result.RequestID = &val + } + return result, nil +} + +// DeleteTask - Deletes a Task from the specified Job. +// +// When a Task is deleted, all of the files in its directory on the Compute Node +// where it ran are also deleted (regardless of the retention time). For +// multi-instance Tasks, the delete Task operation applies synchronously to the +// primary task; subtasks and their files are then deleted asynchronously in the +// background. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-07-01.20.0 +// - jobID - The ID of the Job from which to delete the Task. +// - taskID - The ID of the Task to delete. +// - options - DeleteTaskOptions contains the optional parameters for the Client.DeleteTask method. +func (client *Client) DeleteTask(ctx context.Context, jobID string, taskID string, options *DeleteTaskOptions) (DeleteTaskResponse, error) { + var err error + ctx, endSpan := runtime.StartSpan(ctx, "Client.DeleteTask", client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteTaskCreateRequest(ctx, jobID, taskID, options) + if err != nil { + return DeleteTaskResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DeleteTaskResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return DeleteTaskResponse{}, err + } + resp, err := client.deleteTaskHandleResponse(httpResp) + return resp, err +} + +// deleteTaskCreateRequest creates the DeleteTask request. +func (client *Client) deleteTaskCreateRequest(ctx context.Context, jobID string, taskID string, options *DeleteTaskOptions) (*policy.Request, error) { + host := "{endpoint}" + host = strings.ReplaceAll(host, "{endpoint}", client.endpoint) + urlPath := "/jobs/{jobId}/tasks/{taskId}" + if jobID == "" { + return nil, errors.New("parameter jobID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{jobId}", url.PathEscape(jobID)) + if taskID == "" { + return nil, errors.New("parameter taskID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{taskId}", url.PathEscape(taskID)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2024-07-01.20.0") + if options != nil && options.Timeout != nil { + reqQP.Set("timeOut", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.IfMatch != nil { + req.Raw().Header["If-Match"] = []string{*options.IfMatch} + } + if options != nil && options.IfModifiedSince != nil { + req.Raw().Header["If-Modified-Since"] = []string{options.IfModifiedSince.Format(time.RFC1123)} + } + if options != nil && options.IfNoneMatch != nil { + req.Raw().Header["If-None-Match"] = []string{*options.IfNoneMatch} + } + if options != nil && options.IfUnmodifiedSince != nil { + req.Raw().Header["If-Unmodified-Since"] = []string{options.IfUnmodifiedSince.Format(time.RFC1123)} + } + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.Ocpdate != nil { + req.Raw().Header["ocp-date"] = []string{options.Ocpdate.Format(time.RFC1123)} + } + if options != nil && options.ReturnClientRequestID != nil { + req.Raw().Header["return-client-request-id"] = []string{strconv.FormatBool(*options.ReturnClientRequestID)} + } + return req, nil +} + +// deleteTaskHandleResponse handles the DeleteTask response. +func (client *Client) deleteTaskHandleResponse(resp *http.Response) (DeleteTaskResponse, error) { + result := DeleteTaskResponse{} + if val := resp.Header.Get("client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("request-id"); val != "" { + result.RequestID = &val + } + return result, nil +} + +// DeleteTaskFile - Deletes the specified Task file from the Compute Node where the Task ran. +// +// Deletes the specified Task file from the Compute Node where the Task ran. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-07-01.20.0 +// - jobID - The ID of the Job that contains the Task. +// - taskID - The ID of the Task whose file you want to retrieve. +// - filePath - The path to the Task file that you want to get the content of. +// - options - DeleteTaskFileOptions contains the optional parameters for the Client.DeleteTaskFile method. +func (client *Client) DeleteTaskFile(ctx context.Context, jobID string, taskID string, filePath string, options *DeleteTaskFileOptions) (DeleteTaskFileResponse, error) { + var err error + ctx, endSpan := runtime.StartSpan(ctx, "Client.DeleteTaskFile", client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteTaskFileCreateRequest(ctx, jobID, taskID, filePath, options) + if err != nil { + return DeleteTaskFileResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DeleteTaskFileResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return DeleteTaskFileResponse{}, err + } + resp, err := client.deleteTaskFileHandleResponse(httpResp) + return resp, err +} + +// deleteTaskFileCreateRequest creates the DeleteTaskFile request. +func (client *Client) deleteTaskFileCreateRequest(ctx context.Context, jobID string, taskID string, filePath string, options *DeleteTaskFileOptions) (*policy.Request, error) { + host := "{endpoint}" + host = strings.ReplaceAll(host, "{endpoint}", client.endpoint) + urlPath := "/jobs/{jobId}/tasks/{taskId}/files/{filePath}" + if jobID == "" { + return nil, errors.New("parameter jobID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{jobId}", url.PathEscape(jobID)) + if taskID == "" { + return nil, errors.New("parameter taskID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{taskId}", url.PathEscape(taskID)) + if filePath == "" { + return nil, errors.New("parameter filePath cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{filePath}", url.PathEscape(filePath)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2024-07-01.20.0") + if options != nil && options.Recursive != nil { + reqQP.Set("recursive", strconv.FormatBool(*options.Recursive)) + } + if options != nil && options.Timeout != nil { + reqQP.Set("timeOut", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.Ocpdate != nil { + req.Raw().Header["ocp-date"] = []string{options.Ocpdate.Format(time.RFC1123)} + } + if options != nil && options.ReturnClientRequestID != nil { + req.Raw().Header["return-client-request-id"] = []string{strconv.FormatBool(*options.ReturnClientRequestID)} + } + return req, nil +} + +// deleteTaskFileHandleResponse handles the DeleteTaskFile response. +func (client *Client) deleteTaskFileHandleResponse(resp *http.Response) (DeleteTaskFileResponse, error) { + result := DeleteTaskFileResponse{} + if val := resp.Header.Get("client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("request-id"); val != "" { + result.RequestID = &val + } + return result, nil +} + +// DisableJob - Disables the specified Job, preventing new Tasks from running. +// +// The Batch Service immediately moves the Job to the disabling state. Batch then +// uses the disableTasks parameter to determine what to do with the currently +// running Tasks of the Job. The Job remains in the disabling state until the +// disable operation is completed and all Tasks have been dealt with according to +// the disableTasks option; the Job then moves to the disabled state. No new Tasks +// are started under the Job until it moves back to active state. If you try to +// disable a Job that is in any state other than active, disabling, or disabled, +// the request fails with status code 409. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-07-01.20.0 +// - jobID - The ID of the Job to disable. +// - content - The options to use for disabling the Job. +// - options - DisableJobOptions contains the optional parameters for the Client.DisableJob method. +func (client *Client) DisableJob(ctx context.Context, jobID string, content DisableJobContent, options *DisableJobOptions) (DisableJobResponse, error) { + var err error + ctx, endSpan := runtime.StartSpan(ctx, "Client.DisableJob", client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.disableJobCreateRequest(ctx, jobID, content, options) + if err != nil { + return DisableJobResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DisableJobResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return DisableJobResponse{}, err + } + resp, err := client.disableJobHandleResponse(httpResp) + return resp, err +} + +// disableJobCreateRequest creates the DisableJob request. +func (client *Client) disableJobCreateRequest(ctx context.Context, jobID string, content DisableJobContent, options *DisableJobOptions) (*policy.Request, error) { + host := "{endpoint}" + host = strings.ReplaceAll(host, "{endpoint}", client.endpoint) + urlPath := "/jobs/{jobId}/disable" + if jobID == "" { + return nil, errors.New("parameter jobID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{jobId}", url.PathEscape(jobID)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2024-07-01.20.0") + if options != nil && options.Timeout != nil { + reqQP.Set("timeOut", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.IfMatch != nil { + req.Raw().Header["If-Match"] = []string{*options.IfMatch} + } + if options != nil && options.IfModifiedSince != nil { + req.Raw().Header["If-Modified-Since"] = []string{options.IfModifiedSince.Format(time.RFC1123)} + } + if options != nil && options.IfNoneMatch != nil { + req.Raw().Header["If-None-Match"] = []string{*options.IfNoneMatch} + } + if options != nil && options.IfUnmodifiedSince != nil { + req.Raw().Header["If-Unmodified-Since"] = []string{options.IfUnmodifiedSince.Format(time.RFC1123)} + } + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.Ocpdate != nil { + req.Raw().Header["ocp-date"] = []string{options.Ocpdate.Format(time.RFC1123)} + } + if options != nil && options.ReturnClientRequestID != nil { + req.Raw().Header["return-client-request-id"] = []string{strconv.FormatBool(*options.ReturnClientRequestID)} + } + req.Raw().Header["Content-Type"] = []string{"application/json; odata=minimalmetadata"} + if err := runtime.MarshalAsJSON(req, content); err != nil { + return nil, err + } + return req, nil +} + +// disableJobHandleResponse handles the DisableJob response. +func (client *Client) disableJobHandleResponse(resp *http.Response) (DisableJobResponse, error) { + result := DisableJobResponse{} + if val := resp.Header.Get("client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("DataServiceId"); val != "" { + result.DataServiceID = &val + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = &val + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return DisableJobResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("request-id"); val != "" { + result.RequestID = &val + } + return result, nil +} + +// DisableJobSchedule - Disables a Job Schedule. +// +// No new Jobs will be created until the Job Schedule is enabled again. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-07-01.20.0 +// - jobScheduleID - The ID of the Job Schedule to disable. +// - options - DisableJobScheduleOptions contains the optional parameters for the Client.DisableJobSchedule method. +func (client *Client) DisableJobSchedule(ctx context.Context, jobScheduleID string, options *DisableJobScheduleOptions) (DisableJobScheduleResponse, error) { + var err error + ctx, endSpan := runtime.StartSpan(ctx, "Client.DisableJobSchedule", client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.disableJobScheduleCreateRequest(ctx, jobScheduleID, options) + if err != nil { + return DisableJobScheduleResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DisableJobScheduleResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return DisableJobScheduleResponse{}, err + } + resp, err := client.disableJobScheduleHandleResponse(httpResp) + return resp, err +} + +// disableJobScheduleCreateRequest creates the DisableJobSchedule request. +func (client *Client) disableJobScheduleCreateRequest(ctx context.Context, jobScheduleID string, options *DisableJobScheduleOptions) (*policy.Request, error) { + host := "{endpoint}" + host = strings.ReplaceAll(host, "{endpoint}", client.endpoint) + urlPath := "/jobschedules/{jobScheduleId}/disable" + if jobScheduleID == "" { + return nil, errors.New("parameter jobScheduleID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{jobScheduleId}", url.PathEscape(jobScheduleID)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2024-07-01.20.0") + if options != nil && options.Timeout != nil { + reqQP.Set("timeOut", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.IfMatch != nil { + req.Raw().Header["If-Match"] = []string{*options.IfMatch} + } + if options != nil && options.IfModifiedSince != nil { + req.Raw().Header["If-Modified-Since"] = []string{options.IfModifiedSince.Format(time.RFC1123)} + } + if options != nil && options.IfNoneMatch != nil { + req.Raw().Header["If-None-Match"] = []string{*options.IfNoneMatch} + } + if options != nil && options.IfUnmodifiedSince != nil { + req.Raw().Header["If-Unmodified-Since"] = []string{options.IfUnmodifiedSince.Format(time.RFC1123)} + } + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.Ocpdate != nil { + req.Raw().Header["ocp-date"] = []string{options.Ocpdate.Format(time.RFC1123)} + } + if options != nil && options.ReturnClientRequestID != nil { + req.Raw().Header["return-client-request-id"] = []string{strconv.FormatBool(*options.ReturnClientRequestID)} + } + return req, nil +} + +// disableJobScheduleHandleResponse handles the DisableJobSchedule response. +func (client *Client) disableJobScheduleHandleResponse(resp *http.Response) (DisableJobScheduleResponse, error) { + result := DisableJobScheduleResponse{} + if val := resp.Header.Get("client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("DataServiceId"); val != "" { + result.DataServiceID = &val + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = &val + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return DisableJobScheduleResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("request-id"); val != "" { + result.RequestID = &val + } + return result, nil +} + +// DisableNodeScheduling - Disables Task scheduling on the specified Compute Node. +// +// You can disable Task scheduling on a Compute Node only if its current +// scheduling state is enabled. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-07-01.20.0 +// - poolID - The ID of the Pool that contains the Compute Node. +// - nodeID - The ID of the Compute Node on which you want to disable Task scheduling. +// - options - DisableNodeSchedulingOptions contains the optional parameters for the Client.DisableNodeScheduling method. +func (client *Client) DisableNodeScheduling(ctx context.Context, poolID string, nodeID string, options *DisableNodeSchedulingOptions) (DisableNodeSchedulingResponse, error) { + var err error + ctx, endSpan := runtime.StartSpan(ctx, "Client.DisableNodeScheduling", client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.disableNodeSchedulingCreateRequest(ctx, poolID, nodeID, options) + if err != nil { + return DisableNodeSchedulingResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DisableNodeSchedulingResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return DisableNodeSchedulingResponse{}, err + } + resp, err := client.disableNodeSchedulingHandleResponse(httpResp) + return resp, err +} + +// disableNodeSchedulingCreateRequest creates the DisableNodeScheduling request. +func (client *Client) disableNodeSchedulingCreateRequest(ctx context.Context, poolID string, nodeID string, options *DisableNodeSchedulingOptions) (*policy.Request, error) { + host := "{endpoint}" + host = strings.ReplaceAll(host, "{endpoint}", client.endpoint) + urlPath := "/pools/{poolId}/nodes/{nodeId}/disablescheduling" + if poolID == "" { + return nil, errors.New("parameter poolID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{poolId}", url.PathEscape(poolID)) + if nodeID == "" { + return nil, errors.New("parameter nodeID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{nodeId}", url.PathEscape(nodeID)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2024-07-01.20.0") + if options != nil && options.Timeout != nil { + reqQP.Set("timeOut", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.Ocpdate != nil { + req.Raw().Header["ocp-date"] = []string{options.Ocpdate.Format(time.RFC1123)} + } + if options != nil && options.ReturnClientRequestID != nil { + req.Raw().Header["return-client-request-id"] = []string{strconv.FormatBool(*options.ReturnClientRequestID)} + } + if options != nil && options.Parameters != nil { + req.Raw().Header["Content-Type"] = []string{"application/json; odata=minimalmetadata"} + if err := runtime.MarshalAsJSON(req, *options.Parameters); err != nil { + return nil, err + } + return req, nil + } + return req, nil +} + +// disableNodeSchedulingHandleResponse handles the DisableNodeScheduling response. +func (client *Client) disableNodeSchedulingHandleResponse(resp *http.Response) (DisableNodeSchedulingResponse, error) { + result := DisableNodeSchedulingResponse{} + if val := resp.Header.Get("client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("DataServiceId"); val != "" { + result.DataServiceID = &val + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = &val + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return DisableNodeSchedulingResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("request-id"); val != "" { + result.RequestID = &val + } + return result, nil +} + +// DisablePoolAutoScale - Disables automatic scaling for a Pool. +// +// Disables automatic scaling for a Pool. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-07-01.20.0 +// - poolID - The ID of the Pool on which to disable automatic scaling. +// - options - DisablePoolAutoScaleOptions contains the optional parameters for the Client.DisablePoolAutoScale method. +func (client *Client) DisablePoolAutoScale(ctx context.Context, poolID string, options *DisablePoolAutoScaleOptions) (DisablePoolAutoScaleResponse, error) { + var err error + ctx, endSpan := runtime.StartSpan(ctx, "Client.DisablePoolAutoScale", client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.disablePoolAutoScaleCreateRequest(ctx, poolID, options) + if err != nil { + return DisablePoolAutoScaleResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DisablePoolAutoScaleResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return DisablePoolAutoScaleResponse{}, err + } + resp, err := client.disablePoolAutoScaleHandleResponse(httpResp) + return resp, err +} + +// disablePoolAutoScaleCreateRequest creates the DisablePoolAutoScale request. +func (client *Client) disablePoolAutoScaleCreateRequest(ctx context.Context, poolID string, options *DisablePoolAutoScaleOptions) (*policy.Request, error) { + host := "{endpoint}" + host = strings.ReplaceAll(host, "{endpoint}", client.endpoint) + urlPath := "/pools/{poolId}/disableautoscale" + if poolID == "" { + return nil, errors.New("parameter poolID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{poolId}", url.PathEscape(poolID)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2024-07-01.20.0") + if options != nil && options.Timeout != nil { + reqQP.Set("timeOut", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.Ocpdate != nil { + req.Raw().Header["ocp-date"] = []string{options.Ocpdate.Format(time.RFC1123)} + } + if options != nil && options.ReturnClientRequestID != nil { + req.Raw().Header["return-client-request-id"] = []string{strconv.FormatBool(*options.ReturnClientRequestID)} + } + return req, nil +} + +// disablePoolAutoScaleHandleResponse handles the DisablePoolAutoScale response. +func (client *Client) disablePoolAutoScaleHandleResponse(resp *http.Response) (DisablePoolAutoScaleResponse, error) { + result := DisablePoolAutoScaleResponse{} + if val := resp.Header.Get("client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("DataServiceId"); val != "" { + result.DataServiceID = &val + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = &val + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return DisablePoolAutoScaleResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("request-id"); val != "" { + result.RequestID = &val + } + return result, nil +} + +// EnableJob - Enables the specified Job, allowing new Tasks to run. +// +// When you call this API, the Batch service sets a disabled Job to the enabling +// state. After the this operation is completed, the Job moves to the active +// state, and scheduling of new Tasks under the Job resumes. The Batch service +// does not allow a Task to remain in the active state for more than 180 days. +// Therefore, if you enable a Job containing active Tasks which were added more +// than 180 days ago, those Tasks will not run. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-07-01.20.0 +// - jobID - The ID of the Job to enable. +// - options - EnableJobOptions contains the optional parameters for the Client.EnableJob method. +func (client *Client) EnableJob(ctx context.Context, jobID string, options *EnableJobOptions) (EnableJobResponse, error) { + var err error + ctx, endSpan := runtime.StartSpan(ctx, "Client.EnableJob", client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.enableJobCreateRequest(ctx, jobID, options) + if err != nil { + return EnableJobResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return EnableJobResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return EnableJobResponse{}, err + } + resp, err := client.enableJobHandleResponse(httpResp) + return resp, err +} + +// enableJobCreateRequest creates the EnableJob request. +func (client *Client) enableJobCreateRequest(ctx context.Context, jobID string, options *EnableJobOptions) (*policy.Request, error) { + host := "{endpoint}" + host = strings.ReplaceAll(host, "{endpoint}", client.endpoint) + urlPath := "/jobs/{jobId}/enable" + if jobID == "" { + return nil, errors.New("parameter jobID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{jobId}", url.PathEscape(jobID)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2024-07-01.20.0") + if options != nil && options.Timeout != nil { + reqQP.Set("timeOut", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.IfMatch != nil { + req.Raw().Header["If-Match"] = []string{*options.IfMatch} + } + if options != nil && options.IfModifiedSince != nil { + req.Raw().Header["If-Modified-Since"] = []string{options.IfModifiedSince.Format(time.RFC1123)} + } + if options != nil && options.IfNoneMatch != nil { + req.Raw().Header["If-None-Match"] = []string{*options.IfNoneMatch} + } + if options != nil && options.IfUnmodifiedSince != nil { + req.Raw().Header["If-Unmodified-Since"] = []string{options.IfUnmodifiedSince.Format(time.RFC1123)} + } + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.Ocpdate != nil { + req.Raw().Header["ocp-date"] = []string{options.Ocpdate.Format(time.RFC1123)} + } + if options != nil && options.ReturnClientRequestID != nil { + req.Raw().Header["return-client-request-id"] = []string{strconv.FormatBool(*options.ReturnClientRequestID)} + } + return req, nil +} + +// enableJobHandleResponse handles the EnableJob response. +func (client *Client) enableJobHandleResponse(resp *http.Response) (EnableJobResponse, error) { + result := EnableJobResponse{} + if val := resp.Header.Get("client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("DataServiceId"); val != "" { + result.DataServiceID = &val + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = &val + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return EnableJobResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("request-id"); val != "" { + result.RequestID = &val + } + return result, nil +} + +// EnableJobSchedule - Enables a Job Schedule. +// +// Enables a Job Schedule. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-07-01.20.0 +// - jobScheduleID - The ID of the Job Schedule to enable. +// - options - EnableJobScheduleOptions contains the optional parameters for the Client.EnableJobSchedule method. +func (client *Client) EnableJobSchedule(ctx context.Context, jobScheduleID string, options *EnableJobScheduleOptions) (EnableJobScheduleResponse, error) { + var err error + ctx, endSpan := runtime.StartSpan(ctx, "Client.EnableJobSchedule", client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.enableJobScheduleCreateRequest(ctx, jobScheduleID, options) + if err != nil { + return EnableJobScheduleResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return EnableJobScheduleResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return EnableJobScheduleResponse{}, err + } + resp, err := client.enableJobScheduleHandleResponse(httpResp) + return resp, err +} + +// enableJobScheduleCreateRequest creates the EnableJobSchedule request. +func (client *Client) enableJobScheduleCreateRequest(ctx context.Context, jobScheduleID string, options *EnableJobScheduleOptions) (*policy.Request, error) { + host := "{endpoint}" + host = strings.ReplaceAll(host, "{endpoint}", client.endpoint) + urlPath := "/jobschedules/{jobScheduleId}/enable" + if jobScheduleID == "" { + return nil, errors.New("parameter jobScheduleID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{jobScheduleId}", url.PathEscape(jobScheduleID)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2024-07-01.20.0") + if options != nil && options.Timeout != nil { + reqQP.Set("timeOut", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.IfMatch != nil { + req.Raw().Header["If-Match"] = []string{*options.IfMatch} + } + if options != nil && options.IfModifiedSince != nil { + req.Raw().Header["If-Modified-Since"] = []string{options.IfModifiedSince.Format(time.RFC1123)} + } + if options != nil && options.IfNoneMatch != nil { + req.Raw().Header["If-None-Match"] = []string{*options.IfNoneMatch} + } + if options != nil && options.IfUnmodifiedSince != nil { + req.Raw().Header["If-Unmodified-Since"] = []string{options.IfUnmodifiedSince.Format(time.RFC1123)} + } + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.Ocpdate != nil { + req.Raw().Header["ocp-date"] = []string{options.Ocpdate.Format(time.RFC1123)} + } + if options != nil && options.ReturnClientRequestID != nil { + req.Raw().Header["return-client-request-id"] = []string{strconv.FormatBool(*options.ReturnClientRequestID)} + } + return req, nil +} + +// enableJobScheduleHandleResponse handles the EnableJobSchedule response. +func (client *Client) enableJobScheduleHandleResponse(resp *http.Response) (EnableJobScheduleResponse, error) { + result := EnableJobScheduleResponse{} + if val := resp.Header.Get("client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("DataServiceId"); val != "" { + result.DataServiceID = &val + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = &val + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return EnableJobScheduleResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("request-id"); val != "" { + result.RequestID = &val + } + return result, nil +} + +// EnableNodeScheduling - Enables Task scheduling on the specified Compute Node. +// +// You can enable Task scheduling on a Compute Node only if its current scheduling +// state is disabled +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-07-01.20.0 +// - poolID - The ID of the Pool that contains the Compute Node. +// - nodeID - The ID of the Compute Node on which you want to enable Task scheduling. +// - options - EnableNodeSchedulingOptions contains the optional parameters for the Client.EnableNodeScheduling method. +func (client *Client) EnableNodeScheduling(ctx context.Context, poolID string, nodeID string, options *EnableNodeSchedulingOptions) (EnableNodeSchedulingResponse, error) { + var err error + ctx, endSpan := runtime.StartSpan(ctx, "Client.EnableNodeScheduling", client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.enableNodeSchedulingCreateRequest(ctx, poolID, nodeID, options) + if err != nil { + return EnableNodeSchedulingResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return EnableNodeSchedulingResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return EnableNodeSchedulingResponse{}, err + } + resp, err := client.enableNodeSchedulingHandleResponse(httpResp) + return resp, err +} + +// enableNodeSchedulingCreateRequest creates the EnableNodeScheduling request. +func (client *Client) enableNodeSchedulingCreateRequest(ctx context.Context, poolID string, nodeID string, options *EnableNodeSchedulingOptions) (*policy.Request, error) { + host := "{endpoint}" + host = strings.ReplaceAll(host, "{endpoint}", client.endpoint) + urlPath := "/pools/{poolId}/nodes/{nodeId}/enablescheduling" + if poolID == "" { + return nil, errors.New("parameter poolID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{poolId}", url.PathEscape(poolID)) + if nodeID == "" { + return nil, errors.New("parameter nodeID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{nodeId}", url.PathEscape(nodeID)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2024-07-01.20.0") + if options != nil && options.Timeout != nil { + reqQP.Set("timeOut", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.Ocpdate != nil { + req.Raw().Header["ocp-date"] = []string{options.Ocpdate.Format(time.RFC1123)} + } + if options != nil && options.ReturnClientRequestID != nil { + req.Raw().Header["return-client-request-id"] = []string{strconv.FormatBool(*options.ReturnClientRequestID)} + } + return req, nil +} + +// enableNodeSchedulingHandleResponse handles the EnableNodeScheduling response. +func (client *Client) enableNodeSchedulingHandleResponse(resp *http.Response) (EnableNodeSchedulingResponse, error) { + result := EnableNodeSchedulingResponse{} + if val := resp.Header.Get("client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("DataServiceId"); val != "" { + result.DataServiceID = &val + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = &val + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return EnableNodeSchedulingResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("request-id"); val != "" { + result.RequestID = &val + } + return result, nil +} + +// EnablePoolAutoScale - Enables automatic scaling for a Pool. +// +// You cannot enable automatic scaling on a Pool if a resize operation is in +// progress on the Pool. If automatic scaling of the Pool is currently disabled, +// you must specify a valid autoscale formula as part of the request. If automatic +// scaling of the Pool is already enabled, you may specify a new autoscale formula +// and/or a new evaluation interval. You cannot call this API for the same Pool +// more than once every 30 seconds. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-07-01.20.0 +// - poolID - The ID of the Pool to get. +// - content - The options to use for enabling automatic scaling. +// - options - EnablePoolAutoScaleOptions contains the optional parameters for the Client.EnablePoolAutoScale method. +func (client *Client) EnablePoolAutoScale(ctx context.Context, poolID string, content EnablePoolAutoScaleContent, options *EnablePoolAutoScaleOptions) (EnablePoolAutoScaleResponse, error) { + var err error + ctx, endSpan := runtime.StartSpan(ctx, "Client.EnablePoolAutoScale", client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.enablePoolAutoScaleCreateRequest(ctx, poolID, content, options) + if err != nil { + return EnablePoolAutoScaleResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return EnablePoolAutoScaleResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return EnablePoolAutoScaleResponse{}, err + } + resp, err := client.enablePoolAutoScaleHandleResponse(httpResp) + return resp, err +} + +// enablePoolAutoScaleCreateRequest creates the EnablePoolAutoScale request. +func (client *Client) enablePoolAutoScaleCreateRequest(ctx context.Context, poolID string, content EnablePoolAutoScaleContent, options *EnablePoolAutoScaleOptions) (*policy.Request, error) { + host := "{endpoint}" + host = strings.ReplaceAll(host, "{endpoint}", client.endpoint) + urlPath := "/pools/{poolId}/enableautoscale" + if poolID == "" { + return nil, errors.New("parameter poolID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{poolId}", url.PathEscape(poolID)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2024-07-01.20.0") + if options != nil && options.Timeout != nil { + reqQP.Set("timeOut", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.IfMatch != nil { + req.Raw().Header["If-Match"] = []string{*options.IfMatch} + } + if options != nil && options.IfModifiedSince != nil { + req.Raw().Header["If-Modified-Since"] = []string{options.IfModifiedSince.Format(time.RFC1123)} + } + if options != nil && options.IfNoneMatch != nil { + req.Raw().Header["If-None-Match"] = []string{*options.IfNoneMatch} + } + if options != nil && options.IfUnmodifiedSince != nil { + req.Raw().Header["If-Unmodified-Since"] = []string{options.IfUnmodifiedSince.Format(time.RFC1123)} + } + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.Ocpdate != nil { + req.Raw().Header["ocp-date"] = []string{options.Ocpdate.Format(time.RFC1123)} + } + if options != nil && options.ReturnClientRequestID != nil { + req.Raw().Header["return-client-request-id"] = []string{strconv.FormatBool(*options.ReturnClientRequestID)} + } + req.Raw().Header["Content-Type"] = []string{"application/json; odata=minimalmetadata"} + if err := runtime.MarshalAsJSON(req, content); err != nil { + return nil, err + } + return req, nil +} + +// enablePoolAutoScaleHandleResponse handles the EnablePoolAutoScale response. +func (client *Client) enablePoolAutoScaleHandleResponse(resp *http.Response) (EnablePoolAutoScaleResponse, error) { + result := EnablePoolAutoScaleResponse{} + if val := resp.Header.Get("client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("DataServiceId"); val != "" { + result.DataServiceID = &val + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = &val + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return EnablePoolAutoScaleResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("request-id"); val != "" { + result.RequestID = &val + } + return result, nil +} + +// EvaluatePoolAutoScale - Gets the result of evaluating an automatic scaling formula on the Pool. +// +// This API is primarily for validating an autoscale formula, as it simply returns +// the result without applying the formula to the Pool. The Pool must have auto +// scaling enabled in order to evaluate a formula. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-07-01.20.0 +// - poolID - The ID of the Pool on which to evaluate the automatic scaling formula. +// - content - The options to use for evaluating the automatic scaling formula. +// - options - EvaluatePoolAutoScaleOptions contains the optional parameters for the Client.EvaluatePoolAutoScale method. +func (client *Client) EvaluatePoolAutoScale(ctx context.Context, poolID string, content EvaluatePoolAutoScaleContent, options *EvaluatePoolAutoScaleOptions) (EvaluatePoolAutoScaleResponse, error) { + var err error + ctx, endSpan := runtime.StartSpan(ctx, "Client.EvaluatePoolAutoScale", client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.evaluatePoolAutoScaleCreateRequest(ctx, poolID, content, options) + if err != nil { + return EvaluatePoolAutoScaleResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return EvaluatePoolAutoScaleResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return EvaluatePoolAutoScaleResponse{}, err + } + resp, err := client.evaluatePoolAutoScaleHandleResponse(httpResp) + return resp, err +} + +// evaluatePoolAutoScaleCreateRequest creates the EvaluatePoolAutoScale request. +func (client *Client) evaluatePoolAutoScaleCreateRequest(ctx context.Context, poolID string, content EvaluatePoolAutoScaleContent, options *EvaluatePoolAutoScaleOptions) (*policy.Request, error) { + host := "{endpoint}" + host = strings.ReplaceAll(host, "{endpoint}", client.endpoint) + urlPath := "/pools/{poolId}/evaluateautoscale" + if poolID == "" { + return nil, errors.New("parameter poolID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{poolId}", url.PathEscape(poolID)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2024-07-01.20.0") + if options != nil && options.Timeout != nil { + reqQP.Set("timeOut", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.Ocpdate != nil { + req.Raw().Header["ocp-date"] = []string{options.Ocpdate.Format(time.RFC1123)} + } + if options != nil && options.ReturnClientRequestID != nil { + req.Raw().Header["return-client-request-id"] = []string{strconv.FormatBool(*options.ReturnClientRequestID)} + } + req.Raw().Header["Content-Type"] = []string{"application/json; odata=minimalmetadata"} + if err := runtime.MarshalAsJSON(req, content); err != nil { + return nil, err + } + return req, nil +} + +// evaluatePoolAutoScaleHandleResponse handles the EvaluatePoolAutoScale response. +func (client *Client) evaluatePoolAutoScaleHandleResponse(resp *http.Response) (EvaluatePoolAutoScaleResponse, error) { + result := EvaluatePoolAutoScaleResponse{} + if val := resp.Header.Get("client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("DataServiceId"); val != "" { + result.DataServiceID = &val + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = &val + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return EvaluatePoolAutoScaleResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("request-id"); val != "" { + result.RequestID = &val + } + if err := runtime.UnmarshalAsJSON(resp, &result.AutoScaleRun); err != nil { + return EvaluatePoolAutoScaleResponse{}, err + } + return result, nil +} + +// GetApplication - Gets information about the specified Application. +// +// This operation returns only Applications and versions that are available for +// use on Compute Nodes; that is, that can be used in an Package reference. For +// administrator information about Applications and versions that are not yet +// available to Compute Nodes, use the Azure portal or the Azure Resource Manager +// API. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-07-01.20.0 +// - applicationID - The ID of the Application +// - options - GetApplicationOptions contains the optional parameters for the Client.GetApplication method. +func (client *Client) GetApplication(ctx context.Context, applicationID string, options *GetApplicationOptions) (GetApplicationResponse, error) { + var err error + ctx, endSpan := runtime.StartSpan(ctx, "Client.GetApplication", client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getApplicationCreateRequest(ctx, applicationID, options) + if err != nil { + return GetApplicationResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return GetApplicationResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return GetApplicationResponse{}, err + } + resp, err := client.getApplicationHandleResponse(httpResp) + return resp, err +} + +// getApplicationCreateRequest creates the GetApplication request. +func (client *Client) getApplicationCreateRequest(ctx context.Context, applicationID string, options *GetApplicationOptions) (*policy.Request, error) { + host := "{endpoint}" + host = strings.ReplaceAll(host, "{endpoint}", client.endpoint) + urlPath := "/applications/{applicationId}" + if applicationID == "" { + return nil, errors.New("parameter applicationID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{applicationId}", url.PathEscape(applicationID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2024-07-01.20.0") + if options != nil && options.Timeout != nil { + reqQP.Set("timeOut", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.Ocpdate != nil { + req.Raw().Header["ocp-date"] = []string{options.Ocpdate.Format(time.RFC1123)} + } + if options != nil && options.ReturnClientRequestID != nil { + req.Raw().Header["return-client-request-id"] = []string{strconv.FormatBool(*options.ReturnClientRequestID)} + } + return req, nil +} + +// getApplicationHandleResponse handles the GetApplication response. +func (client *Client) getApplicationHandleResponse(resp *http.Response) (GetApplicationResponse, error) { + result := GetApplicationResponse{} + if val := resp.Header.Get("client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = &val + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return GetApplicationResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("request-id"); val != "" { + result.RequestID = &val + } + if err := runtime.UnmarshalAsJSON(resp, &result.Application); err != nil { + return GetApplicationResponse{}, err + } + return result, nil +} + +// GetCertificate - Gets information about the specified Certificate. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-07-01.20.0 +// - thumbprintAlgorithm - The algorithm used to derive the thumbprint parameter. This must be sha1. +// - thumbprint - The thumbprint of the Certificate to get. +// - options - GetCertificateOptions contains the optional parameters for the Client.GetCertificate method. +func (client *Client) GetCertificate(ctx context.Context, thumbprintAlgorithm string, thumbprint string, options *GetCertificateOptions) (GetCertificateResponse, error) { + var err error + ctx, endSpan := runtime.StartSpan(ctx, "Client.GetCertificate", client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCertificateCreateRequest(ctx, thumbprintAlgorithm, thumbprint, options) + if err != nil { + return GetCertificateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return GetCertificateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return GetCertificateResponse{}, err + } + resp, err := client.getCertificateHandleResponse(httpResp) + return resp, err +} + +// getCertificateCreateRequest creates the GetCertificate request. +func (client *Client) getCertificateCreateRequest(ctx context.Context, thumbprintAlgorithm string, thumbprint string, options *GetCertificateOptions) (*policy.Request, error) { + host := "{endpoint}" + host = strings.ReplaceAll(host, "{endpoint}", client.endpoint) + urlPath := "/certificates(thumbprintAlgorithm={thumbprintAlgorithm},thumbprint={thumbprint})" + if thumbprintAlgorithm == "" { + return nil, errors.New("parameter thumbprintAlgorithm cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{thumbprintAlgorithm}", url.PathEscape(thumbprintAlgorithm)) + if thumbprint == "" { + return nil, errors.New("parameter thumbprint cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{thumbprint}", url.PathEscape(thumbprint)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.SelectParam != nil { + reqQP.Set("$select", strings.Join(options.SelectParam, ",")) + } + reqQP.Set("api-version", "2024-07-01.20.0") + if options != nil && options.Timeout != nil { + reqQP.Set("timeOut", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.Ocpdate != nil { + req.Raw().Header["ocp-date"] = []string{options.Ocpdate.Format(time.RFC1123)} + } + if options != nil && options.ReturnClientRequestID != nil { + req.Raw().Header["return-client-request-id"] = []string{strconv.FormatBool(*options.ReturnClientRequestID)} + } + return req, nil +} + +// getCertificateHandleResponse handles the GetCertificate response. +func (client *Client) getCertificateHandleResponse(resp *http.Response) (GetCertificateResponse, error) { + result := GetCertificateResponse{} + if val := resp.Header.Get("client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = &val + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return GetCertificateResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("request-id"); val != "" { + result.RequestID = &val + } + if err := runtime.UnmarshalAsJSON(resp, &result.Certificate); err != nil { + return GetCertificateResponse{}, err + } + return result, nil +} + +// GetJob - Gets information about the specified Job. +// +// Gets information about the specified Job. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-07-01.20.0 +// - jobID - The ID of the Job. +// - options - GetJobOptions contains the optional parameters for the Client.GetJob method. +func (client *Client) GetJob(ctx context.Context, jobID string, options *GetJobOptions) (GetJobResponse, error) { + var err error + ctx, endSpan := runtime.StartSpan(ctx, "Client.GetJob", client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getJobCreateRequest(ctx, jobID, options) + if err != nil { + return GetJobResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return GetJobResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return GetJobResponse{}, err + } + resp, err := client.getJobHandleResponse(httpResp) + return resp, err +} + +// getJobCreateRequest creates the GetJob request. +func (client *Client) getJobCreateRequest(ctx context.Context, jobID string, options *GetJobOptions) (*policy.Request, error) { + host := "{endpoint}" + host = strings.ReplaceAll(host, "{endpoint}", client.endpoint) + urlPath := "/jobs/{jobId}" + if jobID == "" { + return nil, errors.New("parameter jobID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{jobId}", url.PathEscape(jobID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Expand != nil { + reqQP.Set("$expand", strings.Join(options.Expand, ",")) + } + if options != nil && options.SelectParam != nil { + reqQP.Set("$select", strings.Join(options.SelectParam, ",")) + } + reqQP.Set("api-version", "2024-07-01.20.0") + if options != nil && options.Timeout != nil { + reqQP.Set("timeOut", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.IfMatch != nil { + req.Raw().Header["If-Match"] = []string{*options.IfMatch} + } + if options != nil && options.IfModifiedSince != nil { + req.Raw().Header["If-Modified-Since"] = []string{options.IfModifiedSince.Format(time.RFC1123)} + } + if options != nil && options.IfNoneMatch != nil { + req.Raw().Header["If-None-Match"] = []string{*options.IfNoneMatch} + } + if options != nil && options.IfUnmodifiedSince != nil { + req.Raw().Header["If-Unmodified-Since"] = []string{options.IfUnmodifiedSince.Format(time.RFC1123)} + } + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.Ocpdate != nil { + req.Raw().Header["ocp-date"] = []string{options.Ocpdate.Format(time.RFC1123)} + } + if options != nil && options.ReturnClientRequestID != nil { + req.Raw().Header["return-client-request-id"] = []string{strconv.FormatBool(*options.ReturnClientRequestID)} + } + return req, nil +} + +// getJobHandleResponse handles the GetJob response. +func (client *Client) getJobHandleResponse(resp *http.Response) (GetJobResponse, error) { + result := GetJobResponse{} + if val := resp.Header.Get("client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = &val + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return GetJobResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("request-id"); val != "" { + result.RequestID = &val + } + if err := runtime.UnmarshalAsJSON(resp, &result.Job); err != nil { + return GetJobResponse{}, err + } + return result, nil +} + +// GetJobSchedule - Gets information about the specified Job Schedule. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-07-01.20.0 +// - jobScheduleID - The ID of the Job Schedule to get. +// - options - GetJobScheduleOptions contains the optional parameters for the Client.GetJobSchedule method. +func (client *Client) GetJobSchedule(ctx context.Context, jobScheduleID string, options *GetJobScheduleOptions) (GetJobScheduleResponse, error) { + var err error + ctx, endSpan := runtime.StartSpan(ctx, "Client.GetJobSchedule", client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getJobScheduleCreateRequest(ctx, jobScheduleID, options) + if err != nil { + return GetJobScheduleResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return GetJobScheduleResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return GetJobScheduleResponse{}, err + } + resp, err := client.getJobScheduleHandleResponse(httpResp) + return resp, err +} + +// getJobScheduleCreateRequest creates the GetJobSchedule request. +func (client *Client) getJobScheduleCreateRequest(ctx context.Context, jobScheduleID string, options *GetJobScheduleOptions) (*policy.Request, error) { + host := "{endpoint}" + host = strings.ReplaceAll(host, "{endpoint}", client.endpoint) + urlPath := "/jobschedules/{jobScheduleId}" + if jobScheduleID == "" { + return nil, errors.New("parameter jobScheduleID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{jobScheduleId}", url.PathEscape(jobScheduleID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Expand != nil { + reqQP.Set("$expand", strings.Join(options.Expand, ",")) + } + if options != nil && options.SelectParam != nil { + reqQP.Set("$select", strings.Join(options.SelectParam, ",")) + } + reqQP.Set("api-version", "2024-07-01.20.0") + if options != nil && options.Timeout != nil { + reqQP.Set("timeOut", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.IfMatch != nil { + req.Raw().Header["If-Match"] = []string{*options.IfMatch} + } + if options != nil && options.IfModifiedSince != nil { + req.Raw().Header["If-Modified-Since"] = []string{options.IfModifiedSince.Format(time.RFC1123)} + } + if options != nil && options.IfNoneMatch != nil { + req.Raw().Header["If-None-Match"] = []string{*options.IfNoneMatch} + } + if options != nil && options.IfUnmodifiedSince != nil { + req.Raw().Header["If-Unmodified-Since"] = []string{options.IfUnmodifiedSince.Format(time.RFC1123)} + } + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.Ocpdate != nil { + req.Raw().Header["ocp-date"] = []string{options.Ocpdate.Format(time.RFC1123)} + } + if options != nil && options.ReturnClientRequestID != nil { + req.Raw().Header["return-client-request-id"] = []string{strconv.FormatBool(*options.ReturnClientRequestID)} + } + return req, nil +} + +// getJobScheduleHandleResponse handles the GetJobSchedule response. +func (client *Client) getJobScheduleHandleResponse(resp *http.Response) (GetJobScheduleResponse, error) { + result := GetJobScheduleResponse{} + if val := resp.Header.Get("client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = &val + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return GetJobScheduleResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("request-id"); val != "" { + result.RequestID = &val + } + if err := runtime.UnmarshalAsJSON(resp, &result.JobSchedule); err != nil { + return GetJobScheduleResponse{}, err + } + return result, nil +} + +// GetJobTaskCounts - Gets the Task counts for the specified Job. +// +// Task counts provide a count of the Tasks by active, running or completed Task +// state, and a count of Tasks which succeeded or failed. Tasks in the preparing +// state are counted as running. Note that the numbers returned may not always be +// up to date. If you need exact task counts, use a list query. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-07-01.20.0 +// - jobID - The ID of the Job. +// - options - GetJobTaskCountsOptions contains the optional parameters for the Client.GetJobTaskCounts method. +func (client *Client) GetJobTaskCounts(ctx context.Context, jobID string, options *GetJobTaskCountsOptions) (GetJobTaskCountsResponse, error) { + var err error + ctx, endSpan := runtime.StartSpan(ctx, "Client.GetJobTaskCounts", client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getJobTaskCountsCreateRequest(ctx, jobID, options) + if err != nil { + return GetJobTaskCountsResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return GetJobTaskCountsResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return GetJobTaskCountsResponse{}, err + } + resp, err := client.getJobTaskCountsHandleResponse(httpResp) + return resp, err +} + +// getJobTaskCountsCreateRequest creates the GetJobTaskCounts request. +func (client *Client) getJobTaskCountsCreateRequest(ctx context.Context, jobID string, options *GetJobTaskCountsOptions) (*policy.Request, error) { + host := "{endpoint}" + host = strings.ReplaceAll(host, "{endpoint}", client.endpoint) + urlPath := "/jobs/{jobId}/taskcounts" + if jobID == "" { + return nil, errors.New("parameter jobID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{jobId}", url.PathEscape(jobID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2024-07-01.20.0") + if options != nil && options.Timeout != nil { + reqQP.Set("timeOut", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.Ocpdate != nil { + req.Raw().Header["ocp-date"] = []string{options.Ocpdate.Format(time.RFC1123)} + } + if options != nil && options.ReturnClientRequestID != nil { + req.Raw().Header["return-client-request-id"] = []string{strconv.FormatBool(*options.ReturnClientRequestID)} + } + return req, nil +} + +// getJobTaskCountsHandleResponse handles the GetJobTaskCounts response. +func (client *Client) getJobTaskCountsHandleResponse(resp *http.Response) (GetJobTaskCountsResponse, error) { + result := GetJobTaskCountsResponse{} + if val := resp.Header.Get("client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = &val + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return GetJobTaskCountsResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("request-id"); val != "" { + result.RequestID = &val + } + if err := runtime.UnmarshalAsJSON(resp, &result.TaskCountsResult); err != nil { + return GetJobTaskCountsResponse{}, err + } + return result, nil +} + +// GetNode - Gets information about the specified Compute Node. +// +// Gets information about the specified Compute Node. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-07-01.20.0 +// - poolID - The ID of the Pool that contains the Compute Node. +// - nodeID - The ID of the Compute Node that you want to get information about. +// - options - GetNodeOptions contains the optional parameters for the Client.GetNode method. +func (client *Client) GetNode(ctx context.Context, poolID string, nodeID string, options *GetNodeOptions) (GetNodeResponse, error) { + var err error + ctx, endSpan := runtime.StartSpan(ctx, "Client.GetNode", client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getNodeCreateRequest(ctx, poolID, nodeID, options) + if err != nil { + return GetNodeResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return GetNodeResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return GetNodeResponse{}, err + } + resp, err := client.getNodeHandleResponse(httpResp) + return resp, err +} + +// getNodeCreateRequest creates the GetNode request. +func (client *Client) getNodeCreateRequest(ctx context.Context, poolID string, nodeID string, options *GetNodeOptions) (*policy.Request, error) { + host := "{endpoint}" + host = strings.ReplaceAll(host, "{endpoint}", client.endpoint) + urlPath := "/pools/{poolId}/nodes/{nodeId}" + if poolID == "" { + return nil, errors.New("parameter poolID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{poolId}", url.PathEscape(poolID)) + if nodeID == "" { + return nil, errors.New("parameter nodeID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{nodeId}", url.PathEscape(nodeID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.SelectParam != nil { + reqQP.Set("$select", strings.Join(options.SelectParam, ",")) + } + reqQP.Set("api-version", "2024-07-01.20.0") + if options != nil && options.Timeout != nil { + reqQP.Set("timeOut", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.Ocpdate != nil { + req.Raw().Header["ocp-date"] = []string{options.Ocpdate.Format(time.RFC1123)} + } + if options != nil && options.ReturnClientRequestID != nil { + req.Raw().Header["return-client-request-id"] = []string{strconv.FormatBool(*options.ReturnClientRequestID)} + } + return req, nil +} + +// getNodeHandleResponse handles the GetNode response. +func (client *Client) getNodeHandleResponse(resp *http.Response) (GetNodeResponse, error) { + result := GetNodeResponse{} + if val := resp.Header.Get("client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = &val + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return GetNodeResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("request-id"); val != "" { + result.RequestID = &val + } + if err := runtime.UnmarshalAsJSON(resp, &result.Node); err != nil { + return GetNodeResponse{}, err + } + return result, nil +} + +// GetNodeExtension - Gets information about the specified Compute Node Extension. +// +// Gets information about the specified Compute Node Extension. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-07-01.20.0 +// - poolID - The ID of the Pool that contains the Compute Node. +// - nodeID - The ID of the Compute Node that contains the extensions. +// - extensionName - The name of the Compute Node Extension that you want to get information about. +// - options - GetNodeExtensionOptions contains the optional parameters for the Client.GetNodeExtension method. +func (client *Client) GetNodeExtension(ctx context.Context, poolID string, nodeID string, extensionName string, options *GetNodeExtensionOptions) (GetNodeExtensionResponse, error) { + var err error + ctx, endSpan := runtime.StartSpan(ctx, "Client.GetNodeExtension", client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getNodeExtensionCreateRequest(ctx, poolID, nodeID, extensionName, options) + if err != nil { + return GetNodeExtensionResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return GetNodeExtensionResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return GetNodeExtensionResponse{}, err + } + resp, err := client.getNodeExtensionHandleResponse(httpResp) + return resp, err +} + +// getNodeExtensionCreateRequest creates the GetNodeExtension request. +func (client *Client) getNodeExtensionCreateRequest(ctx context.Context, poolID string, nodeID string, extensionName string, options *GetNodeExtensionOptions) (*policy.Request, error) { + host := "{endpoint}" + host = strings.ReplaceAll(host, "{endpoint}", client.endpoint) + urlPath := "/pools/{poolId}/nodes/{nodeId}/extensions/{extensionName}" + if poolID == "" { + return nil, errors.New("parameter poolID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{poolId}", url.PathEscape(poolID)) + if nodeID == "" { + return nil, errors.New("parameter nodeID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{nodeId}", url.PathEscape(nodeID)) + if extensionName == "" { + return nil, errors.New("parameter extensionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{extensionName}", url.PathEscape(extensionName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.SelectParam != nil { + reqQP.Set("$select", strings.Join(options.SelectParam, ",")) + } + reqQP.Set("api-version", "2024-07-01.20.0") + if options != nil && options.Timeout != nil { + reqQP.Set("timeOut", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.Ocpdate != nil { + req.Raw().Header["ocp-date"] = []string{options.Ocpdate.Format(time.RFC1123)} + } + if options != nil && options.ReturnClientRequestID != nil { + req.Raw().Header["return-client-request-id"] = []string{strconv.FormatBool(*options.ReturnClientRequestID)} + } + return req, nil +} + +// getNodeExtensionHandleResponse handles the GetNodeExtension response. +func (client *Client) getNodeExtensionHandleResponse(resp *http.Response) (GetNodeExtensionResponse, error) { + result := GetNodeExtensionResponse{} + if val := resp.Header.Get("client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = &val + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return GetNodeExtensionResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("request-id"); val != "" { + result.RequestID = &val + } + if err := runtime.UnmarshalAsJSON(resp, &result.NodeVMExtension); err != nil { + return GetNodeExtensionResponse{}, err + } + return result, nil +} + +// GetNodeFile - Returns the content of the specified Compute Node file. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-07-01.20.0 +// - poolID - The ID of the Pool that contains the Compute Node. +// - nodeID - The ID of the Compute Node. +// - filePath - The path to the file or directory. +// - options - GetNodeFileOptions contains the optional parameters for the Client.GetNodeFile method. +func (client *Client) GetNodeFile(ctx context.Context, poolID string, nodeID string, filePath string, options *GetNodeFileOptions) (GetNodeFileResponse, error) { + var err error + ctx, endSpan := runtime.StartSpan(ctx, "Client.GetNodeFile", client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getNodeFileCreateRequest(ctx, poolID, nodeID, filePath, options) + if err != nil { + return GetNodeFileResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return GetNodeFileResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return GetNodeFileResponse{}, err + } + resp, err := client.getNodeFileHandleResponse(httpResp) + return resp, err +} + +// getNodeFileCreateRequest creates the GetNodeFile request. +func (client *Client) getNodeFileCreateRequest(ctx context.Context, poolID string, nodeID string, filePath string, options *GetNodeFileOptions) (*policy.Request, error) { + host := "{endpoint}" + host = strings.ReplaceAll(host, "{endpoint}", client.endpoint) + urlPath := "/pools/{poolId}/nodes/{nodeId}/files/{filePath}" + if poolID == "" { + return nil, errors.New("parameter poolID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{poolId}", url.PathEscape(poolID)) + if nodeID == "" { + return nil, errors.New("parameter nodeID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{nodeId}", url.PathEscape(nodeID)) + if filePath == "" { + return nil, errors.New("parameter filePath cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{filePath}", url.PathEscape(filePath)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2024-07-01.20.0") + if options != nil && options.Timeout != nil { + reqQP.Set("timeOut", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = reqQP.Encode() + runtime.SkipBodyDownload(req) + req.Raw().Header["Accept"] = []string{"application/octet-stream"} + if options != nil && options.IfModifiedSince != nil { + req.Raw().Header["If-Modified-Since"] = []string{options.IfModifiedSince.Format(time.RFC1123)} + } + if options != nil && options.IfUnmodifiedSince != nil { + req.Raw().Header["If-Unmodified-Since"] = []string{options.IfUnmodifiedSince.Format(time.RFC1123)} + } + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.Ocpdate != nil { + req.Raw().Header["ocp-date"] = []string{options.Ocpdate.Format(time.RFC1123)} + } + if options != nil && options.OcpRange != nil { + req.Raw().Header["ocp-range"] = []string{*options.OcpRange} + } + if options != nil && options.ReturnClientRequestID != nil { + req.Raw().Header["return-client-request-id"] = []string{strconv.FormatBool(*options.ReturnClientRequestID)} + } + return req, nil +} + +// getNodeFileHandleResponse handles the GetNodeFile response. +func (client *Client) getNodeFileHandleResponse(resp *http.Response) (GetNodeFileResponse, error) { + result := GetNodeFileResponse{Body: resp.Body} + if val := resp.Header.Get("client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("Content-Length"); val != "" { + contentLength, err := strconv.ParseInt(val, 10, 64) + if err != nil { + return GetNodeFileResponse{}, err + } + result.ContentLength = &contentLength + } + if val := resp.Header.Get("content-type"); val != "" { + result.ContentType = &val + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = &val + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return GetNodeFileResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("ocp-batch-file-isdirectory"); val != "" { + ocpBatchFileIsdirectory, err := strconv.ParseBool(val) + if err != nil { + return GetNodeFileResponse{}, err + } + result.OcpBatchFileIsdirectory = &ocpBatchFileIsdirectory + } + if val := resp.Header.Get("ocp-batch-file-mode"); val != "" { + result.OcpBatchFileMode = &val + } + if val := resp.Header.Get("ocp-batch-file-url"); val != "" { + result.OcpBatchFileURL = &val + } + if val := resp.Header.Get("ocp-creation-time"); val != "" { + ocpCreationTime, err := time.Parse(time.RFC1123, val) + if err != nil { + return GetNodeFileResponse{}, err + } + result.OcpCreationTime = &ocpCreationTime + } + if val := resp.Header.Get("request-id"); val != "" { + result.RequestID = &val + } + return result, nil +} + +// GetNodeFileProperties - Gets the properties of the specified Compute Node file. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-07-01.20.0 +// - poolID - The ID of the Pool that contains the Compute Node. +// - nodeID - The ID of the Compute Node. +// - filePath - The path to the file or directory. +// - options - GetNodeFilePropertiesOptions contains the optional parameters for the Client.GetNodeFileProperties method. +func (client *Client) GetNodeFileProperties(ctx context.Context, poolID string, nodeID string, filePath string, options *GetNodeFilePropertiesOptions) (GetNodeFilePropertiesResponse, error) { + var err error + ctx, endSpan := runtime.StartSpan(ctx, "Client.GetNodeFileProperties", client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getNodeFilePropertiesCreateRequest(ctx, poolID, nodeID, filePath, options) + if err != nil { + return GetNodeFilePropertiesResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return GetNodeFilePropertiesResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return GetNodeFilePropertiesResponse{}, err + } + resp, err := client.getNodeFilePropertiesHandleResponse(httpResp) + return resp, err +} + +// getNodeFilePropertiesCreateRequest creates the GetNodeFileProperties request. +func (client *Client) getNodeFilePropertiesCreateRequest(ctx context.Context, poolID string, nodeID string, filePath string, options *GetNodeFilePropertiesOptions) (*policy.Request, error) { + host := "{endpoint}" + host = strings.ReplaceAll(host, "{endpoint}", client.endpoint) + urlPath := "/pools/{poolId}/nodes/{nodeId}/files/{filePath}" + if poolID == "" { + return nil, errors.New("parameter poolID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{poolId}", url.PathEscape(poolID)) + if nodeID == "" { + return nil, errors.New("parameter nodeID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{nodeId}", url.PathEscape(nodeID)) + if filePath == "" { + return nil, errors.New("parameter filePath cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{filePath}", url.PathEscape(filePath)) + req, err := runtime.NewRequest(ctx, http.MethodHead, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2024-07-01.20.0") + if options != nil && options.Timeout != nil { + reqQP.Set("timeOut", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.IfModifiedSince != nil { + req.Raw().Header["If-Modified-Since"] = []string{options.IfModifiedSince.Format(time.RFC1123)} + } + if options != nil && options.IfUnmodifiedSince != nil { + req.Raw().Header["If-Unmodified-Since"] = []string{options.IfUnmodifiedSince.Format(time.RFC1123)} + } + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.Ocpdate != nil { + req.Raw().Header["ocp-date"] = []string{options.Ocpdate.Format(time.RFC1123)} + } + if options != nil && options.ReturnClientRequestID != nil { + req.Raw().Header["return-client-request-id"] = []string{strconv.FormatBool(*options.ReturnClientRequestID)} + } + return req, nil +} + +// getNodeFilePropertiesHandleResponse handles the GetNodeFileProperties response. +func (client *Client) getNodeFilePropertiesHandleResponse(resp *http.Response) (GetNodeFilePropertiesResponse, error) { + result := GetNodeFilePropertiesResponse{} + if val := resp.Header.Get("client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("Content-Length"); val != "" { + contentLength, err := strconv.ParseInt(val, 10, 64) + if err != nil { + return GetNodeFilePropertiesResponse{}, err + } + result.ContentLength = &contentLength + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = &val + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return GetNodeFilePropertiesResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("ocp-batch-file-isdirectory"); val != "" { + ocpBatchFileIsdirectory, err := strconv.ParseBool(val) + if err != nil { + return GetNodeFilePropertiesResponse{}, err + } + result.OcpBatchFileIsdirectory = &ocpBatchFileIsdirectory + } + if val := resp.Header.Get("ocp-batch-file-mode"); val != "" { + result.OcpBatchFileMode = &val + } + if val := resp.Header.Get("ocp-batch-file-url"); val != "" { + result.OcpBatchFileURL = &val + } + if val := resp.Header.Get("ocp-creation-time"); val != "" { + ocpCreationTime, err := time.Parse(time.RFC1123, val) + if err != nil { + return GetNodeFilePropertiesResponse{}, err + } + result.OcpCreationTime = &ocpCreationTime + } + if val := resp.Header.Get("request-id"); val != "" { + result.RequestID = &val + } + return result, nil +} + +// GetNodeRemoteLoginSettings - Gets the settings required for remote login to a Compute Node. +// +// Before you can remotely login to a Compute Node using the remote login settings, +// you must create a user Account on the Compute Node. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-07-01.20.0 +// - poolID - The ID of the Pool that contains the Compute Node. +// - nodeID - The ID of the Compute Node for which to obtain the remote login settings. +// - options - GetNodeRemoteLoginSettingsOptions contains the optional parameters for the Client.GetNodeRemoteLoginSettings +// method. +func (client *Client) GetNodeRemoteLoginSettings(ctx context.Context, poolID string, nodeID string, options *GetNodeRemoteLoginSettingsOptions) (GetNodeRemoteLoginSettingsResponse, error) { + var err error + ctx, endSpan := runtime.StartSpan(ctx, "Client.GetNodeRemoteLoginSettings", client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getNodeRemoteLoginSettingsCreateRequest(ctx, poolID, nodeID, options) + if err != nil { + return GetNodeRemoteLoginSettingsResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return GetNodeRemoteLoginSettingsResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return GetNodeRemoteLoginSettingsResponse{}, err + } + resp, err := client.getNodeRemoteLoginSettingsHandleResponse(httpResp) + return resp, err +} + +// getNodeRemoteLoginSettingsCreateRequest creates the GetNodeRemoteLoginSettings request. +func (client *Client) getNodeRemoteLoginSettingsCreateRequest(ctx context.Context, poolID string, nodeID string, options *GetNodeRemoteLoginSettingsOptions) (*policy.Request, error) { + host := "{endpoint}" + host = strings.ReplaceAll(host, "{endpoint}", client.endpoint) + urlPath := "/pools/{poolId}/nodes/{nodeId}/remoteloginsettings" + if poolID == "" { + return nil, errors.New("parameter poolID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{poolId}", url.PathEscape(poolID)) + if nodeID == "" { + return nil, errors.New("parameter nodeID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{nodeId}", url.PathEscape(nodeID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2024-07-01.20.0") + if options != nil && options.Timeout != nil { + reqQP.Set("timeOut", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.Ocpdate != nil { + req.Raw().Header["ocp-date"] = []string{options.Ocpdate.Format(time.RFC1123)} + } + if options != nil && options.ReturnClientRequestID != nil { + req.Raw().Header["return-client-request-id"] = []string{strconv.FormatBool(*options.ReturnClientRequestID)} + } + return req, nil +} + +// getNodeRemoteLoginSettingsHandleResponse handles the GetNodeRemoteLoginSettings response. +func (client *Client) getNodeRemoteLoginSettingsHandleResponse(resp *http.Response) (GetNodeRemoteLoginSettingsResponse, error) { + result := GetNodeRemoteLoginSettingsResponse{} + if val := resp.Header.Get("client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = &val + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return GetNodeRemoteLoginSettingsResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("request-id"); val != "" { + result.RequestID = &val + } + if err := runtime.UnmarshalAsJSON(resp, &result.NodeRemoteLoginSettings); err != nil { + return GetNodeRemoteLoginSettingsResponse{}, err + } + return result, nil +} + +// GetPool - Gets information about the specified Pool. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-07-01.20.0 +// - poolID - The ID of the Pool to get. +// - options - GetPoolOptions contains the optional parameters for the Client.GetPool method. +func (client *Client) GetPool(ctx context.Context, poolID string, options *GetPoolOptions) (GetPoolResponse, error) { + var err error + ctx, endSpan := runtime.StartSpan(ctx, "Client.GetPool", client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getPoolCreateRequest(ctx, poolID, options) + if err != nil { + return GetPoolResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return GetPoolResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return GetPoolResponse{}, err + } + resp, err := client.getPoolHandleResponse(httpResp) + return resp, err +} + +// getPoolCreateRequest creates the GetPool request. +func (client *Client) getPoolCreateRequest(ctx context.Context, poolID string, options *GetPoolOptions) (*policy.Request, error) { + host := "{endpoint}" + host = strings.ReplaceAll(host, "{endpoint}", client.endpoint) + urlPath := "/pools/{poolId}" + if poolID == "" { + return nil, errors.New("parameter poolID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{poolId}", url.PathEscape(poolID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Expand != nil { + reqQP.Set("$expand", strings.Join(options.Expand, ",")) + } + if options != nil && options.SelectParam != nil { + reqQP.Set("$select", strings.Join(options.SelectParam, ",")) + } + reqQP.Set("api-version", "2024-07-01.20.0") + if options != nil && options.Timeout != nil { + reqQP.Set("timeOut", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.IfMatch != nil { + req.Raw().Header["If-Match"] = []string{*options.IfMatch} + } + if options != nil && options.IfModifiedSince != nil { + req.Raw().Header["If-Modified-Since"] = []string{options.IfModifiedSince.Format(time.RFC1123)} + } + if options != nil && options.IfNoneMatch != nil { + req.Raw().Header["If-None-Match"] = []string{*options.IfNoneMatch} + } + if options != nil && options.IfUnmodifiedSince != nil { + req.Raw().Header["If-Unmodified-Since"] = []string{options.IfUnmodifiedSince.Format(time.RFC1123)} + } + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.Ocpdate != nil { + req.Raw().Header["ocp-date"] = []string{options.Ocpdate.Format(time.RFC1123)} + } + if options != nil && options.ReturnClientRequestID != nil { + req.Raw().Header["return-client-request-id"] = []string{strconv.FormatBool(*options.ReturnClientRequestID)} + } + return req, nil +} + +// getPoolHandleResponse handles the GetPool response. +func (client *Client) getPoolHandleResponse(resp *http.Response) (GetPoolResponse, error) { + result := GetPoolResponse{} + if val := resp.Header.Get("client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = &val + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return GetPoolResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("request-id"); val != "" { + result.RequestID = &val + } + if err := runtime.UnmarshalAsJSON(resp, &result.Pool); err != nil { + return GetPoolResponse{}, err + } + return result, nil +} + +// GetTask - Gets information about the specified Task. +// +// For multi-instance Tasks, information such as affinityId, executionInfo and +// nodeInfo refer to the primary Task. Use the list subtasks API to retrieve +// information about subtasks. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-07-01.20.0 +// - jobID - The ID of the Job that contains the Task. +// - taskID - The ID of the Task to get information about. +// - options - GetTaskOptions contains the optional parameters for the Client.GetTask method. +func (client *Client) GetTask(ctx context.Context, jobID string, taskID string, options *GetTaskOptions) (GetTaskResponse, error) { + var err error + ctx, endSpan := runtime.StartSpan(ctx, "Client.GetTask", client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getTaskCreateRequest(ctx, jobID, taskID, options) + if err != nil { + return GetTaskResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return GetTaskResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return GetTaskResponse{}, err + } + resp, err := client.getTaskHandleResponse(httpResp) + return resp, err +} + +// getTaskCreateRequest creates the GetTask request. +func (client *Client) getTaskCreateRequest(ctx context.Context, jobID string, taskID string, options *GetTaskOptions) (*policy.Request, error) { + host := "{endpoint}" + host = strings.ReplaceAll(host, "{endpoint}", client.endpoint) + urlPath := "/jobs/{jobId}/tasks/{taskId}" + if jobID == "" { + return nil, errors.New("parameter jobID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{jobId}", url.PathEscape(jobID)) + if taskID == "" { + return nil, errors.New("parameter taskID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{taskId}", url.PathEscape(taskID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Expand != nil { + reqQP.Set("$expand", strings.Join(options.Expand, ",")) + } + if options != nil && options.SelectParam != nil { + reqQP.Set("$select", strings.Join(options.SelectParam, ",")) + } + reqQP.Set("api-version", "2024-07-01.20.0") + if options != nil && options.Timeout != nil { + reqQP.Set("timeOut", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.IfMatch != nil { + req.Raw().Header["If-Match"] = []string{*options.IfMatch} + } + if options != nil && options.IfModifiedSince != nil { + req.Raw().Header["If-Modified-Since"] = []string{options.IfModifiedSince.Format(time.RFC1123)} + } + if options != nil && options.IfNoneMatch != nil { + req.Raw().Header["If-None-Match"] = []string{*options.IfNoneMatch} + } + if options != nil && options.IfUnmodifiedSince != nil { + req.Raw().Header["If-Unmodified-Since"] = []string{options.IfUnmodifiedSince.Format(time.RFC1123)} + } + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.Ocpdate != nil { + req.Raw().Header["ocp-date"] = []string{options.Ocpdate.Format(time.RFC1123)} + } + if options != nil && options.ReturnClientRequestID != nil { + req.Raw().Header["return-client-request-id"] = []string{strconv.FormatBool(*options.ReturnClientRequestID)} + } + return req, nil +} + +// getTaskHandleResponse handles the GetTask response. +func (client *Client) getTaskHandleResponse(resp *http.Response) (GetTaskResponse, error) { + result := GetTaskResponse{} + if val := resp.Header.Get("client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("DataServiceId"); val != "" { + result.DataServiceID = &val + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = &val + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return GetTaskResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("request-id"); val != "" { + result.RequestID = &val + } + if err := runtime.UnmarshalAsJSON(resp, &result.Task); err != nil { + return GetTaskResponse{}, err + } + return result, nil +} + +// GetTaskFile - Returns the content of the specified Task file. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-07-01.20.0 +// - jobID - The ID of the Job that contains the Task. +// - taskID - The ID of the Task whose file you want to retrieve. +// - filePath - The path to the Task file that you want to get the content of. +// - options - GetTaskFileOptions contains the optional parameters for the Client.GetTaskFile method. +func (client *Client) GetTaskFile(ctx context.Context, jobID string, taskID string, filePath string, options *GetTaskFileOptions) (GetTaskFileResponse, error) { + var err error + ctx, endSpan := runtime.StartSpan(ctx, "Client.GetTaskFile", client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getTaskFileCreateRequest(ctx, jobID, taskID, filePath, options) + if err != nil { + return GetTaskFileResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return GetTaskFileResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return GetTaskFileResponse{}, err + } + resp, err := client.getTaskFileHandleResponse(httpResp) + return resp, err +} + +// getTaskFileCreateRequest creates the GetTaskFile request. +func (client *Client) getTaskFileCreateRequest(ctx context.Context, jobID string, taskID string, filePath string, options *GetTaskFileOptions) (*policy.Request, error) { + host := "{endpoint}" + host = strings.ReplaceAll(host, "{endpoint}", client.endpoint) + urlPath := "/jobs/{jobId}/tasks/{taskId}/files/{filePath}" + if jobID == "" { + return nil, errors.New("parameter jobID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{jobId}", url.PathEscape(jobID)) + if taskID == "" { + return nil, errors.New("parameter taskID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{taskId}", url.PathEscape(taskID)) + if filePath == "" { + return nil, errors.New("parameter filePath cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{filePath}", url.PathEscape(filePath)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2024-07-01.20.0") + if options != nil && options.Timeout != nil { + reqQP.Set("timeOut", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = reqQP.Encode() + runtime.SkipBodyDownload(req) + req.Raw().Header["Accept"] = []string{"application/octet-stream"} + if options != nil && options.IfModifiedSince != nil { + req.Raw().Header["If-Modified-Since"] = []string{options.IfModifiedSince.Format(time.RFC1123)} + } + if options != nil && options.IfUnmodifiedSince != nil { + req.Raw().Header["If-Unmodified-Since"] = []string{options.IfUnmodifiedSince.Format(time.RFC1123)} + } + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.Ocpdate != nil { + req.Raw().Header["ocp-date"] = []string{options.Ocpdate.Format(time.RFC1123)} + } + if options != nil && options.OcpRange != nil { + req.Raw().Header["ocp-range"] = []string{*options.OcpRange} + } + if options != nil && options.ReturnClientRequestID != nil { + req.Raw().Header["return-client-request-id"] = []string{strconv.FormatBool(*options.ReturnClientRequestID)} + } + return req, nil +} + +// getTaskFileHandleResponse handles the GetTaskFile response. +func (client *Client) getTaskFileHandleResponse(resp *http.Response) (GetTaskFileResponse, error) { + result := GetTaskFileResponse{Body: resp.Body} + if val := resp.Header.Get("client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("Content-Length"); val != "" { + contentLength, err := strconv.ParseInt(val, 10, 64) + if err != nil { + return GetTaskFileResponse{}, err + } + result.ContentLength = &contentLength + } + if val := resp.Header.Get("content-type"); val != "" { + result.ContentType = &val + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = &val + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return GetTaskFileResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("ocp-batch-file-isdirectory"); val != "" { + ocpBatchFileIsdirectory, err := strconv.ParseBool(val) + if err != nil { + return GetTaskFileResponse{}, err + } + result.OcpBatchFileIsdirectory = &ocpBatchFileIsdirectory + } + if val := resp.Header.Get("ocp-batch-file-mode"); val != "" { + result.OcpBatchFileMode = &val + } + if val := resp.Header.Get("ocp-batch-file-url"); val != "" { + result.OcpBatchFileURL = &val + } + if val := resp.Header.Get("ocp-creation-time"); val != "" { + ocpCreationTime, err := time.Parse(time.RFC1123, val) + if err != nil { + return GetTaskFileResponse{}, err + } + result.OcpCreationTime = &ocpCreationTime + } + if val := resp.Header.Get("request-id"); val != "" { + result.RequestID = &val + } + return result, nil +} + +// GetTaskFileProperties - Gets the properties of the specified Task file. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-07-01.20.0 +// - jobID - The ID of the Job that contains the Task. +// - taskID - The ID of the Task whose file you want to retrieve. +// - filePath - The path to the Task file that you want to get the content of. +// - options - GetTaskFilePropertiesOptions contains the optional parameters for the Client.GetTaskFileProperties method. +func (client *Client) GetTaskFileProperties(ctx context.Context, jobID string, taskID string, filePath string, options *GetTaskFilePropertiesOptions) (GetTaskFilePropertiesResponse, error) { + var err error + ctx, endSpan := runtime.StartSpan(ctx, "Client.GetTaskFileProperties", client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getTaskFilePropertiesCreateRequest(ctx, jobID, taskID, filePath, options) + if err != nil { + return GetTaskFilePropertiesResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return GetTaskFilePropertiesResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return GetTaskFilePropertiesResponse{}, err + } + resp, err := client.getTaskFilePropertiesHandleResponse(httpResp) + return resp, err +} + +// getTaskFilePropertiesCreateRequest creates the GetTaskFileProperties request. +func (client *Client) getTaskFilePropertiesCreateRequest(ctx context.Context, jobID string, taskID string, filePath string, options *GetTaskFilePropertiesOptions) (*policy.Request, error) { + host := "{endpoint}" + host = strings.ReplaceAll(host, "{endpoint}", client.endpoint) + urlPath := "/jobs/{jobId}/tasks/{taskId}/files/{filePath}" + if jobID == "" { + return nil, errors.New("parameter jobID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{jobId}", url.PathEscape(jobID)) + if taskID == "" { + return nil, errors.New("parameter taskID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{taskId}", url.PathEscape(taskID)) + if filePath == "" { + return nil, errors.New("parameter filePath cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{filePath}", url.PathEscape(filePath)) + req, err := runtime.NewRequest(ctx, http.MethodHead, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2024-07-01.20.0") + if options != nil && options.Timeout != nil { + reqQP.Set("timeOut", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.IfModifiedSince != nil { + req.Raw().Header["If-Modified-Since"] = []string{options.IfModifiedSince.Format(time.RFC1123)} + } + if options != nil && options.IfUnmodifiedSince != nil { + req.Raw().Header["If-Unmodified-Since"] = []string{options.IfUnmodifiedSince.Format(time.RFC1123)} + } + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.Ocpdate != nil { + req.Raw().Header["ocp-date"] = []string{options.Ocpdate.Format(time.RFC1123)} + } + if options != nil && options.ReturnClientRequestID != nil { + req.Raw().Header["return-client-request-id"] = []string{strconv.FormatBool(*options.ReturnClientRequestID)} + } + return req, nil +} + +// getTaskFilePropertiesHandleResponse handles the GetTaskFileProperties response. +func (client *Client) getTaskFilePropertiesHandleResponse(resp *http.Response) (GetTaskFilePropertiesResponse, error) { + result := GetTaskFilePropertiesResponse{} + if val := resp.Header.Get("client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("Content-Length"); val != "" { + contentLength, err := strconv.ParseInt(val, 10, 64) + if err != nil { + return GetTaskFilePropertiesResponse{}, err + } + result.ContentLength = &contentLength + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = &val + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return GetTaskFilePropertiesResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("ocp-batch-file-isdirectory"); val != "" { + ocpBatchFileIsdirectory, err := strconv.ParseBool(val) + if err != nil { + return GetTaskFilePropertiesResponse{}, err + } + result.OcpBatchFileIsdirectory = &ocpBatchFileIsdirectory + } + if val := resp.Header.Get("ocp-batch-file-mode"); val != "" { + result.OcpBatchFileMode = &val + } + if val := resp.Header.Get("ocp-batch-file-url"); val != "" { + result.OcpBatchFileURL = &val + } + if val := resp.Header.Get("ocp-creation-time"); val != "" { + ocpCreationTime, err := time.Parse(time.RFC1123, val) + if err != nil { + return GetTaskFilePropertiesResponse{}, err + } + result.OcpCreationTime = &ocpCreationTime + } + if val := resp.Header.Get("request-id"); val != "" { + result.RequestID = &val + } + return result, nil +} + +// JobScheduleExists - Checks the specified Job Schedule exists. +// +// Checks the specified Job Schedule exists. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-07-01.20.0 +// - jobScheduleID - The ID of the Job Schedule which you want to check. +// - options - JobScheduleExistsOptions contains the optional parameters for the Client.JobScheduleExists method. +func (client *Client) JobScheduleExists(ctx context.Context, jobScheduleID string, options *JobScheduleExistsOptions) (JobScheduleExistsResponse, error) { + var err error + ctx, endSpan := runtime.StartSpan(ctx, "Client.JobScheduleExists", client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.jobScheduleExistsCreateRequest(ctx, jobScheduleID, options) + if err != nil { + return JobScheduleExistsResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return JobScheduleExistsResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusNotFound) { + err = runtime.NewResponseError(httpResp) + return JobScheduleExistsResponse{}, err + } + resp, err := client.jobScheduleExistsHandleResponse(httpResp) + return resp, err +} + +// jobScheduleExistsCreateRequest creates the JobScheduleExists request. +func (client *Client) jobScheduleExistsCreateRequest(ctx context.Context, jobScheduleID string, options *JobScheduleExistsOptions) (*policy.Request, error) { + host := "{endpoint}" + host = strings.ReplaceAll(host, "{endpoint}", client.endpoint) + urlPath := "/jobschedules/{jobScheduleId}" + if jobScheduleID == "" { + return nil, errors.New("parameter jobScheduleID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{jobScheduleId}", url.PathEscape(jobScheduleID)) + req, err := runtime.NewRequest(ctx, http.MethodHead, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2024-07-01.20.0") + if options != nil && options.Timeout != nil { + reqQP.Set("timeOut", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.IfMatch != nil { + req.Raw().Header["If-Match"] = []string{*options.IfMatch} + } + if options != nil && options.IfModifiedSince != nil { + req.Raw().Header["If-Modified-Since"] = []string{options.IfModifiedSince.Format(time.RFC1123)} + } + if options != nil && options.IfNoneMatch != nil { + req.Raw().Header["If-None-Match"] = []string{*options.IfNoneMatch} + } + if options != nil && options.IfUnmodifiedSince != nil { + req.Raw().Header["If-Unmodified-Since"] = []string{options.IfUnmodifiedSince.Format(time.RFC1123)} + } + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.Ocpdate != nil { + req.Raw().Header["ocp-date"] = []string{options.Ocpdate.Format(time.RFC1123)} + } + if options != nil && options.ReturnClientRequestID != nil { + req.Raw().Header["return-client-request-id"] = []string{strconv.FormatBool(*options.ReturnClientRequestID)} + } + return req, nil +} + +// jobScheduleExistsHandleResponse handles the JobScheduleExists response. +func (client *Client) jobScheduleExistsHandleResponse(resp *http.Response) (JobScheduleExistsResponse, error) { + result := JobScheduleExistsResponse{} + if val := resp.Header.Get("client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = &val + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return JobScheduleExistsResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("request-id"); val != "" { + result.RequestID = &val + } + return result, nil +} + +// NewListApplicationsPager - Lists all of the applications available in the specified Account. +// +// This operation returns only Applications and versions that are available for +// use on Compute Nodes; that is, that can be used in an Package reference. For +// administrator information about applications and versions that are not yet +// available to Compute Nodes, use the Azure portal or the Azure Resource Manager +// API. +// +// Generated from API version 2024-07-01.20.0 +// - options - ListApplicationsOptions contains the optional parameters for the Client.NewListApplicationsPager method. +func (client *Client) NewListApplicationsPager(options *ListApplicationsOptions) *runtime.Pager[ListApplicationsResponse] { + return runtime.NewPager(runtime.PagingHandler[ListApplicationsResponse]{ + More: func(page ListApplicationsResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ListApplicationsResponse) (ListApplicationsResponse, error) { + 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.listApplicationsCreateRequest(ctx, options) + }, nil) + if err != nil { + return ListApplicationsResponse{}, err + } + return client.listApplicationsHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listApplicationsCreateRequest creates the ListApplications request. +func (client *Client) listApplicationsCreateRequest(ctx context.Context, options *ListApplicationsOptions) (*policy.Request, error) { + host := "{endpoint}" + host = strings.ReplaceAll(host, "{endpoint}", client.endpoint) + urlPath := "/applications" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2024-07-01.20.0") + if options != nil && options.MaxResults != nil { + reqQP.Set("maxresults", strconv.FormatInt(int64(*options.MaxResults), 10)) + } + if options != nil && options.Timeout != nil { + reqQP.Set("timeOut", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.Ocpdate != nil { + req.Raw().Header["ocp-date"] = []string{options.Ocpdate.Format(time.RFC1123)} + } + if options != nil && options.ReturnClientRequestID != nil { + req.Raw().Header["return-client-request-id"] = []string{strconv.FormatBool(*options.ReturnClientRequestID)} + } + return req, nil +} + +// listApplicationsHandleResponse handles the ListApplications response. +func (client *Client) listApplicationsHandleResponse(resp *http.Response) (ListApplicationsResponse, error) { + result := ListApplicationsResponse{} + if val := resp.Header.Get("client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = &val + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return ListApplicationsResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("request-id"); val != "" { + result.RequestID = &val + } + if err := runtime.UnmarshalAsJSON(resp, &result.ApplicationListResult); err != nil { + return ListApplicationsResponse{}, err + } + return result, nil +} + +// NewListCertificatesPager - Lists all of the Certificates that have been added to the specified Account. +// +// Lists all of the Certificates that have been added to the specified Account. +// +// Generated from API version 2024-07-01.20.0 +// - options - ListCertificatesOptions contains the optional parameters for the Client.NewListCertificatesPager method. +func (client *Client) NewListCertificatesPager(options *ListCertificatesOptions) *runtime.Pager[ListCertificatesResponse] { + return runtime.NewPager(runtime.PagingHandler[ListCertificatesResponse]{ + More: func(page ListCertificatesResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ListCertificatesResponse) (ListCertificatesResponse, error) { + 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.listCertificatesCreateRequest(ctx, options) + }, nil) + if err != nil { + return ListCertificatesResponse{}, err + } + return client.listCertificatesHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCertificatesCreateRequest creates the ListCertificates request. +func (client *Client) listCertificatesCreateRequest(ctx context.Context, options *ListCertificatesOptions) (*policy.Request, error) { + host := "{endpoint}" + host = strings.ReplaceAll(host, "{endpoint}", client.endpoint) + urlPath := "/certificates" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Filter != nil { + reqQP.Set("$filter", *options.Filter) + } + if options != nil && options.SelectParam != nil { + reqQP.Set("$select", strings.Join(options.SelectParam, ",")) + } + reqQP.Set("api-version", "2024-07-01.20.0") + if options != nil && options.MaxResults != nil { + reqQP.Set("maxresults", strconv.FormatInt(int64(*options.MaxResults), 10)) + } + if options != nil && options.Timeout != nil { + reqQP.Set("timeOut", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.Ocpdate != nil { + req.Raw().Header["ocp-date"] = []string{options.Ocpdate.Format(time.RFC1123)} + } + if options != nil && options.ReturnClientRequestID != nil { + req.Raw().Header["return-client-request-id"] = []string{strconv.FormatBool(*options.ReturnClientRequestID)} + } + return req, nil +} + +// listCertificatesHandleResponse handles the ListCertificates response. +func (client *Client) listCertificatesHandleResponse(resp *http.Response) (ListCertificatesResponse, error) { + result := ListCertificatesResponse{} + if val := resp.Header.Get("client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = &val + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return ListCertificatesResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("request-id"); val != "" { + result.RequestID = &val + } + if err := runtime.UnmarshalAsJSON(resp, &result.CertificateListResult); err != nil { + return ListCertificatesResponse{}, err + } + return result, nil +} + +// NewListJobPreparationAndReleaseTaskStatusPager - Lists the execution status of the Job Preparation and Job Release Task +// for the +// specified Job across the Compute Nodes where the Job has run. +// +// This API returns the Job Preparation and Job Release Task status on all Compute +// Nodes that have run the Job Preparation or Job Release Task. This includes +// Compute Nodes which have since been removed from the Pool. If this API is +// invoked on a Job which has no Job Preparation or Job Release Task, the Batch +// service returns HTTP status code 409 (Conflict) with an error code of +// JobPreparationTaskNotSpecified. +// +// Generated from API version 2024-07-01.20.0 +// - jobID - The ID of the Job. +// - options - ListJobPreparationAndReleaseTaskStatusOptions contains the optional parameters for the Client.NewListJobPreparationAndReleaseTaskStatusPager +// method. +func (client *Client) NewListJobPreparationAndReleaseTaskStatusPager(jobID string, options *ListJobPreparationAndReleaseTaskStatusOptions) *runtime.Pager[ListJobPreparationAndReleaseTaskStatusResponse] { + return runtime.NewPager(runtime.PagingHandler[ListJobPreparationAndReleaseTaskStatusResponse]{ + More: func(page ListJobPreparationAndReleaseTaskStatusResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ListJobPreparationAndReleaseTaskStatusResponse) (ListJobPreparationAndReleaseTaskStatusResponse, error) { + 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.listJobPreparationAndReleaseTaskStatusCreateRequest(ctx, jobID, options) + }, nil) + if err != nil { + return ListJobPreparationAndReleaseTaskStatusResponse{}, err + } + return client.listJobPreparationAndReleaseTaskStatusHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listJobPreparationAndReleaseTaskStatusCreateRequest creates the ListJobPreparationAndReleaseTaskStatus request. +func (client *Client) listJobPreparationAndReleaseTaskStatusCreateRequest(ctx context.Context, jobID string, options *ListJobPreparationAndReleaseTaskStatusOptions) (*policy.Request, error) { + host := "{endpoint}" + host = strings.ReplaceAll(host, "{endpoint}", client.endpoint) + urlPath := "/jobs/{jobId}/jobpreparationandreleasetaskstatus" + if jobID == "" { + return nil, errors.New("parameter jobID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{jobId}", url.PathEscape(jobID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Filter != nil { + reqQP.Set("$filter", *options.Filter) + } + if options != nil && options.SelectParam != nil { + reqQP.Set("$select", strings.Join(options.SelectParam, ",")) + } + reqQP.Set("api-version", "2024-07-01.20.0") + if options != nil && options.MaxResults != nil { + reqQP.Set("maxresults", strconv.FormatInt(int64(*options.MaxResults), 10)) + } + if options != nil && options.Timeout != nil { + reqQP.Set("timeOut", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.Ocpdate != nil { + req.Raw().Header["ocp-date"] = []string{options.Ocpdate.Format(time.RFC1123)} + } + if options != nil && options.ReturnClientRequestID != nil { + req.Raw().Header["return-client-request-id"] = []string{strconv.FormatBool(*options.ReturnClientRequestID)} + } + return req, nil +} + +// listJobPreparationAndReleaseTaskStatusHandleResponse handles the ListJobPreparationAndReleaseTaskStatus response. +func (client *Client) listJobPreparationAndReleaseTaskStatusHandleResponse(resp *http.Response) (ListJobPreparationAndReleaseTaskStatusResponse, error) { + result := ListJobPreparationAndReleaseTaskStatusResponse{} + if val := resp.Header.Get("client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = &val + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return ListJobPreparationAndReleaseTaskStatusResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("request-id"); val != "" { + result.RequestID = &val + } + if err := runtime.UnmarshalAsJSON(resp, &result.JobPreparationAndReleaseTaskStatusListResult); err != nil { + return ListJobPreparationAndReleaseTaskStatusResponse{}, err + } + return result, nil +} + +// NewListJobSchedulesPager - Lists all of the Job Schedules in the specified Account. +// +// Lists all of the Job Schedules in the specified Account. +// +// Generated from API version 2024-07-01.20.0 +// - options - ListJobSchedulesOptions contains the optional parameters for the Client.NewListJobSchedulesPager method. +func (client *Client) NewListJobSchedulesPager(options *ListJobSchedulesOptions) *runtime.Pager[ListJobSchedulesResponse] { + return runtime.NewPager(runtime.PagingHandler[ListJobSchedulesResponse]{ + More: func(page ListJobSchedulesResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ListJobSchedulesResponse) (ListJobSchedulesResponse, error) { + 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.listJobSchedulesCreateRequest(ctx, options) + }, nil) + if err != nil { + return ListJobSchedulesResponse{}, err + } + return client.listJobSchedulesHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listJobSchedulesCreateRequest creates the ListJobSchedules request. +func (client *Client) listJobSchedulesCreateRequest(ctx context.Context, options *ListJobSchedulesOptions) (*policy.Request, error) { + host := "{endpoint}" + host = strings.ReplaceAll(host, "{endpoint}", client.endpoint) + urlPath := "/jobschedules" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Expand != nil { + reqQP.Set("$expand", strings.Join(options.Expand, ",")) + } + if options != nil && options.Filter != nil { + reqQP.Set("$filter", *options.Filter) + } + if options != nil && options.SelectParam != nil { + reqQP.Set("$select", strings.Join(options.SelectParam, ",")) + } + reqQP.Set("api-version", "2024-07-01.20.0") + if options != nil && options.MaxResults != nil { + reqQP.Set("maxresults", strconv.FormatInt(int64(*options.MaxResults), 10)) + } + if options != nil && options.Timeout != nil { + reqQP.Set("timeOut", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.Ocpdate != nil { + req.Raw().Header["ocp-date"] = []string{options.Ocpdate.Format(time.RFC1123)} + } + if options != nil && options.ReturnClientRequestID != nil { + req.Raw().Header["return-client-request-id"] = []string{strconv.FormatBool(*options.ReturnClientRequestID)} + } + return req, nil +} + +// listJobSchedulesHandleResponse handles the ListJobSchedules response. +func (client *Client) listJobSchedulesHandleResponse(resp *http.Response) (ListJobSchedulesResponse, error) { + result := ListJobSchedulesResponse{} + if val := resp.Header.Get("client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = &val + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return ListJobSchedulesResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("request-id"); val != "" { + result.RequestID = &val + } + if err := runtime.UnmarshalAsJSON(resp, &result.JobScheduleListResult); err != nil { + return ListJobSchedulesResponse{}, err + } + return result, nil +} + +// NewListJobsPager - Lists all of the Jobs in the specified Account. +// +// Lists all of the Jobs in the specified Account. +// +// Generated from API version 2024-07-01.20.0 +// - options - ListJobsOptions contains the optional parameters for the Client.NewListJobsPager method. +func (client *Client) NewListJobsPager(options *ListJobsOptions) *runtime.Pager[ListJobsResponse] { + return runtime.NewPager(runtime.PagingHandler[ListJobsResponse]{ + More: func(page ListJobsResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ListJobsResponse) (ListJobsResponse, error) { + 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.listJobsCreateRequest(ctx, options) + }, nil) + if err != nil { + return ListJobsResponse{}, err + } + return client.listJobsHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listJobsCreateRequest creates the ListJobs request. +func (client *Client) listJobsCreateRequest(ctx context.Context, options *ListJobsOptions) (*policy.Request, error) { + host := "{endpoint}" + host = strings.ReplaceAll(host, "{endpoint}", client.endpoint) + urlPath := "/jobs" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Expand != nil { + reqQP.Set("$expand", strings.Join(options.Expand, ",")) + } + if options != nil && options.Filter != nil { + reqQP.Set("$filter", *options.Filter) + } + if options != nil && options.SelectParam != nil { + reqQP.Set("$select", strings.Join(options.SelectParam, ",")) + } + reqQP.Set("api-version", "2024-07-01.20.0") + if options != nil && options.MaxResults != nil { + reqQP.Set("maxresults", strconv.FormatInt(int64(*options.MaxResults), 10)) + } + if options != nil && options.Timeout != nil { + reqQP.Set("timeOut", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.Ocpdate != nil { + req.Raw().Header["ocp-date"] = []string{options.Ocpdate.Format(time.RFC1123)} + } + if options != nil && options.ReturnClientRequestID != nil { + req.Raw().Header["return-client-request-id"] = []string{strconv.FormatBool(*options.ReturnClientRequestID)} + } + return req, nil +} + +// listJobsHandleResponse handles the ListJobs response. +func (client *Client) listJobsHandleResponse(resp *http.Response) (ListJobsResponse, error) { + result := ListJobsResponse{} + if val := resp.Header.Get("client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = &val + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return ListJobsResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("request-id"); val != "" { + result.RequestID = &val + } + if err := runtime.UnmarshalAsJSON(resp, &result.JobListResult); err != nil { + return ListJobsResponse{}, err + } + return result, nil +} + +// NewListJobsFromSchedulePager - Lists the Jobs that have been created under the specified Job Schedule. +// +// Lists the Jobs that have been created under the specified Job Schedule. +// +// Generated from API version 2024-07-01.20.0 +// - jobScheduleID - The ID of the Job Schedule from which you want to get a list of Jobs. +// - options - ListJobsFromScheduleOptions contains the optional parameters for the Client.NewListJobsFromSchedulePager method. +func (client *Client) NewListJobsFromSchedulePager(jobScheduleID string, options *ListJobsFromScheduleOptions) *runtime.Pager[ListJobsFromScheduleResponse] { + return runtime.NewPager(runtime.PagingHandler[ListJobsFromScheduleResponse]{ + More: func(page ListJobsFromScheduleResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ListJobsFromScheduleResponse) (ListJobsFromScheduleResponse, error) { + 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.listJobsFromScheduleCreateRequest(ctx, jobScheduleID, options) + }, nil) + if err != nil { + return ListJobsFromScheduleResponse{}, err + } + return client.listJobsFromScheduleHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listJobsFromScheduleCreateRequest creates the ListJobsFromSchedule request. +func (client *Client) listJobsFromScheduleCreateRequest(ctx context.Context, jobScheduleID string, options *ListJobsFromScheduleOptions) (*policy.Request, error) { + host := "{endpoint}" + host = strings.ReplaceAll(host, "{endpoint}", client.endpoint) + urlPath := "/jobschedules/{jobScheduleId}/jobs" + if jobScheduleID == "" { + return nil, errors.New("parameter jobScheduleID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{jobScheduleId}", url.PathEscape(jobScheduleID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Expand != nil { + reqQP.Set("$expand", strings.Join(options.Expand, ",")) + } + if options != nil && options.Filter != nil { + reqQP.Set("$filter", *options.Filter) + } + if options != nil && options.SelectParam != nil { + reqQP.Set("$select", strings.Join(options.SelectParam, ",")) + } + reqQP.Set("api-version", "2024-07-01.20.0") + if options != nil && options.MaxResults != nil { + reqQP.Set("maxresults", strconv.FormatInt(int64(*options.MaxResults), 10)) + } + if options != nil && options.Timeout != nil { + reqQP.Set("timeOut", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.Ocpdate != nil { + req.Raw().Header["ocp-date"] = []string{options.Ocpdate.Format(time.RFC1123)} + } + if options != nil && options.ReturnClientRequestID != nil { + req.Raw().Header["return-client-request-id"] = []string{strconv.FormatBool(*options.ReturnClientRequestID)} + } + return req, nil +} + +// listJobsFromScheduleHandleResponse handles the ListJobsFromSchedule response. +func (client *Client) listJobsFromScheduleHandleResponse(resp *http.Response) (ListJobsFromScheduleResponse, error) { + result := ListJobsFromScheduleResponse{} + if val := resp.Header.Get("client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = &val + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return ListJobsFromScheduleResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("request-id"); val != "" { + result.RequestID = &val + } + if err := runtime.UnmarshalAsJSON(resp, &result.JobListResult); err != nil { + return ListJobsFromScheduleResponse{}, err + } + return result, nil +} + +// NewListNodeExtensionsPager - Lists the Compute Nodes Extensions in the specified Pool. +// +// Lists the Compute Nodes Extensions in the specified Pool. +// +// Generated from API version 2024-07-01.20.0 +// - poolID - The ID of the Pool that contains Compute Node. +// - nodeID - The ID of the Compute Node that you want to list extensions. +// - options - ListNodeExtensionsOptions contains the optional parameters for the Client.NewListNodeExtensionsPager method. +func (client *Client) NewListNodeExtensionsPager(poolID string, nodeID string, options *ListNodeExtensionsOptions) *runtime.Pager[ListNodeExtensionsResponse] { + return runtime.NewPager(runtime.PagingHandler[ListNodeExtensionsResponse]{ + More: func(page ListNodeExtensionsResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ListNodeExtensionsResponse) (ListNodeExtensionsResponse, error) { + 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.listNodeExtensionsCreateRequest(ctx, poolID, nodeID, options) + }, nil) + if err != nil { + return ListNodeExtensionsResponse{}, err + } + return client.listNodeExtensionsHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listNodeExtensionsCreateRequest creates the ListNodeExtensions request. +func (client *Client) listNodeExtensionsCreateRequest(ctx context.Context, poolID string, nodeID string, options *ListNodeExtensionsOptions) (*policy.Request, error) { + host := "{endpoint}" + host = strings.ReplaceAll(host, "{endpoint}", client.endpoint) + urlPath := "/pools/{poolId}/nodes/{nodeId}/extensions" + if poolID == "" { + return nil, errors.New("parameter poolID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{poolId}", url.PathEscape(poolID)) + if nodeID == "" { + return nil, errors.New("parameter nodeID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{nodeId}", url.PathEscape(nodeID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.SelectParam != nil { + reqQP.Set("$select", strings.Join(options.SelectParam, ",")) + } + reqQP.Set("api-version", "2024-07-01.20.0") + if options != nil && options.MaxResults != nil { + reqQP.Set("maxresults", strconv.FormatInt(int64(*options.MaxResults), 10)) + } + if options != nil && options.Timeout != nil { + reqQP.Set("timeOut", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.Ocpdate != nil { + req.Raw().Header["ocp-date"] = []string{options.Ocpdate.Format(time.RFC1123)} + } + if options != nil && options.ReturnClientRequestID != nil { + req.Raw().Header["return-client-request-id"] = []string{strconv.FormatBool(*options.ReturnClientRequestID)} + } + return req, nil +} + +// listNodeExtensionsHandleResponse handles the ListNodeExtensions response. +func (client *Client) listNodeExtensionsHandleResponse(resp *http.Response) (ListNodeExtensionsResponse, error) { + result := ListNodeExtensionsResponse{} + if val := resp.Header.Get("client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = &val + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return ListNodeExtensionsResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("request-id"); val != "" { + result.RequestID = &val + } + if err := runtime.UnmarshalAsJSON(resp, &result.NodeVMExtensionListResult); err != nil { + return ListNodeExtensionsResponse{}, err + } + return result, nil +} + +// NewListNodeFilesPager - Lists all of the files in Task directories on the specified Compute Node. +// +// Lists all of the files in Task directories on the specified Compute Node. +// +// Generated from API version 2024-07-01.20.0 +// - poolID - The ID of the Pool that contains the Compute Node. +// - nodeID - The ID of the Compute Node whose files you want to list. +// - options - ListNodeFilesOptions contains the optional parameters for the Client.NewListNodeFilesPager method. +func (client *Client) NewListNodeFilesPager(poolID string, nodeID string, options *ListNodeFilesOptions) *runtime.Pager[ListNodeFilesResponse] { + return runtime.NewPager(runtime.PagingHandler[ListNodeFilesResponse]{ + More: func(page ListNodeFilesResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ListNodeFilesResponse) (ListNodeFilesResponse, error) { + 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.listNodeFilesCreateRequest(ctx, poolID, nodeID, options) + }, nil) + if err != nil { + return ListNodeFilesResponse{}, err + } + return client.listNodeFilesHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listNodeFilesCreateRequest creates the ListNodeFiles request. +func (client *Client) listNodeFilesCreateRequest(ctx context.Context, poolID string, nodeID string, options *ListNodeFilesOptions) (*policy.Request, error) { + host := "{endpoint}" + host = strings.ReplaceAll(host, "{endpoint}", client.endpoint) + urlPath := "/pools/{poolId}/nodes/{nodeId}/files" + if poolID == "" { + return nil, errors.New("parameter poolID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{poolId}", url.PathEscape(poolID)) + if nodeID == "" { + return nil, errors.New("parameter nodeID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{nodeId}", url.PathEscape(nodeID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Filter != nil { + reqQP.Set("$filter", *options.Filter) + } + reqQP.Set("api-version", "2024-07-01.20.0") + if options != nil && options.MaxResults != nil { + reqQP.Set("maxresults", strconv.FormatInt(int64(*options.MaxResults), 10)) + } + if options != nil && options.Recursive != nil { + reqQP.Set("recursive", strconv.FormatBool(*options.Recursive)) + } + if options != nil && options.Timeout != nil { + reqQP.Set("timeOut", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.Ocpdate != nil { + req.Raw().Header["ocp-date"] = []string{options.Ocpdate.Format(time.RFC1123)} + } + if options != nil && options.ReturnClientRequestID != nil { + req.Raw().Header["return-client-request-id"] = []string{strconv.FormatBool(*options.ReturnClientRequestID)} + } + return req, nil +} + +// listNodeFilesHandleResponse handles the ListNodeFiles response. +func (client *Client) listNodeFilesHandleResponse(resp *http.Response) (ListNodeFilesResponse, error) { + result := ListNodeFilesResponse{} + if val := resp.Header.Get("client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = &val + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return ListNodeFilesResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("request-id"); val != "" { + result.RequestID = &val + } + if err := runtime.UnmarshalAsJSON(resp, &result.NodeFileListResult); err != nil { + return ListNodeFilesResponse{}, err + } + return result, nil +} + +// NewListNodesPager - Lists the Compute Nodes in the specified Pool. +// +// Lists the Compute Nodes in the specified Pool. +// +// Generated from API version 2024-07-01.20.0 +// - poolID - The ID of the Pool from which you want to list Compute Nodes. +// - options - ListNodesOptions contains the optional parameters for the Client.NewListNodesPager method. +func (client *Client) NewListNodesPager(poolID string, options *ListNodesOptions) *runtime.Pager[ListNodesResponse] { + return runtime.NewPager(runtime.PagingHandler[ListNodesResponse]{ + More: func(page ListNodesResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ListNodesResponse) (ListNodesResponse, error) { + 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.listNodesCreateRequest(ctx, poolID, options) + }, nil) + if err != nil { + return ListNodesResponse{}, err + } + return client.listNodesHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listNodesCreateRequest creates the ListNodes request. +func (client *Client) listNodesCreateRequest(ctx context.Context, poolID string, options *ListNodesOptions) (*policy.Request, error) { + host := "{endpoint}" + host = strings.ReplaceAll(host, "{endpoint}", client.endpoint) + urlPath := "/pools/{poolId}/nodes" + if poolID == "" { + return nil, errors.New("parameter poolID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{poolId}", url.PathEscape(poolID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Filter != nil { + reqQP.Set("$filter", *options.Filter) + } + if options != nil && options.SelectParam != nil { + reqQP.Set("$select", strings.Join(options.SelectParam, ",")) + } + reqQP.Set("api-version", "2024-07-01.20.0") + if options != nil && options.MaxResults != nil { + reqQP.Set("maxresults", strconv.FormatInt(int64(*options.MaxResults), 10)) + } + if options != nil && options.Timeout != nil { + reqQP.Set("timeOut", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.Ocpdate != nil { + req.Raw().Header["ocp-date"] = []string{options.Ocpdate.Format(time.RFC1123)} + } + if options != nil && options.ReturnClientRequestID != nil { + req.Raw().Header["return-client-request-id"] = []string{strconv.FormatBool(*options.ReturnClientRequestID)} + } + return req, nil +} + +// listNodesHandleResponse handles the ListNodes response. +func (client *Client) listNodesHandleResponse(resp *http.Response) (ListNodesResponse, error) { + result := ListNodesResponse{} + if val := resp.Header.Get("client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = &val + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return ListNodesResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("request-id"); val != "" { + result.RequestID = &val + } + if err := runtime.UnmarshalAsJSON(resp, &result.NodeListResult); err != nil { + return ListNodesResponse{}, err + } + return result, nil +} + +// NewListPoolNodeCountsPager - Gets the number of Compute Nodes in each state, grouped by Pool. Note that the +// numbers returned may not always be up to date. If you need exact node counts, +// use a list query. +// +// Generated from API version 2024-07-01.20.0 +// - options - ListPoolNodeCountsOptions contains the optional parameters for the Client.NewListPoolNodeCountsPager method. +func (client *Client) NewListPoolNodeCountsPager(options *ListPoolNodeCountsOptions) *runtime.Pager[ListPoolNodeCountsResponse] { + return runtime.NewPager(runtime.PagingHandler[ListPoolNodeCountsResponse]{ + More: func(page ListPoolNodeCountsResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ListPoolNodeCountsResponse) (ListPoolNodeCountsResponse, error) { + 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.listPoolNodeCountsCreateRequest(ctx, options) + }, nil) + if err != nil { + return ListPoolNodeCountsResponse{}, err + } + return client.listPoolNodeCountsHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listPoolNodeCountsCreateRequest creates the ListPoolNodeCounts request. +func (client *Client) listPoolNodeCountsCreateRequest(ctx context.Context, options *ListPoolNodeCountsOptions) (*policy.Request, error) { + host := "{endpoint}" + host = strings.ReplaceAll(host, "{endpoint}", client.endpoint) + urlPath := "/nodecounts" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Filter != nil { + reqQP.Set("$filter", *options.Filter) + } + reqQP.Set("api-version", "2024-07-01.20.0") + if options != nil && options.MaxResults != nil { + reqQP.Set("maxresults", strconv.FormatInt(int64(*options.MaxResults), 10)) + } + if options != nil && options.Timeout != nil { + reqQP.Set("timeOut", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.Ocpdate != nil { + req.Raw().Header["ocp-date"] = []string{options.Ocpdate.Format(time.RFC1123)} + } + if options != nil && options.ReturnClientRequestID != nil { + req.Raw().Header["return-client-request-id"] = []string{strconv.FormatBool(*options.ReturnClientRequestID)} + } + return req, nil +} + +// listPoolNodeCountsHandleResponse handles the ListPoolNodeCounts response. +func (client *Client) listPoolNodeCountsHandleResponse(resp *http.Response) (ListPoolNodeCountsResponse, error) { + result := ListPoolNodeCountsResponse{} + if val := resp.Header.Get("client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = &val + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return ListPoolNodeCountsResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("request-id"); val != "" { + result.RequestID = &val + } + if err := runtime.UnmarshalAsJSON(resp, &result.ListPoolNodeCountsResult); err != nil { + return ListPoolNodeCountsResponse{}, err + } + return result, nil +} + +// NewListPoolsPager - Lists all of the Pools which be mounted. +// +// Lists all of the Pools which be mounted. +// +// Generated from API version 2024-07-01.20.0 +// - options - ListPoolsOptions contains the optional parameters for the Client.NewListPoolsPager method. +func (client *Client) NewListPoolsPager(options *ListPoolsOptions) *runtime.Pager[ListPoolsResponse] { + return runtime.NewPager(runtime.PagingHandler[ListPoolsResponse]{ + More: func(page ListPoolsResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ListPoolsResponse) (ListPoolsResponse, error) { + 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.listPoolsCreateRequest(ctx, options) + }, nil) + if err != nil { + return ListPoolsResponse{}, err + } + return client.listPoolsHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listPoolsCreateRequest creates the ListPools request. +func (client *Client) listPoolsCreateRequest(ctx context.Context, options *ListPoolsOptions) (*policy.Request, error) { + host := "{endpoint}" + host = strings.ReplaceAll(host, "{endpoint}", client.endpoint) + urlPath := "/pools" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Expand != nil { + reqQP.Set("$expand", strings.Join(options.Expand, ",")) + } + if options != nil && options.Filter != nil { + reqQP.Set("$filter", *options.Filter) + } + if options != nil && options.SelectParam != nil { + reqQP.Set("$select", strings.Join(options.SelectParam, ",")) + } + reqQP.Set("api-version", "2024-07-01.20.0") + if options != nil && options.MaxResults != nil { + reqQP.Set("maxresults", strconv.FormatInt(int64(*options.MaxResults), 10)) + } + if options != nil && options.Timeout != nil { + reqQP.Set("timeOut", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.Ocpdate != nil { + req.Raw().Header["ocp-date"] = []string{options.Ocpdate.Format(time.RFC1123)} + } + if options != nil && options.ReturnClientRequestID != nil { + req.Raw().Header["return-client-request-id"] = []string{strconv.FormatBool(*options.ReturnClientRequestID)} + } + return req, nil +} + +// listPoolsHandleResponse handles the ListPools response. +func (client *Client) listPoolsHandleResponse(resp *http.Response) (ListPoolsResponse, error) { + result := ListPoolsResponse{} + if val := resp.Header.Get("client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = &val + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return ListPoolsResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("request-id"); val != "" { + result.RequestID = &val + } + if err := runtime.UnmarshalAsJSON(resp, &result.PoolListResult); err != nil { + return ListPoolsResponse{}, err + } + return result, nil +} + +// NewListSubTasksPager - Lists all of the subtasks that are associated with the specified multi-instance +// Task. +// +// If the Task is not a multi-instance Task then this returns an empty collection. +// +// Generated from API version 2024-07-01.20.0 +// - jobID - The ID of the Job. +// - taskID - The ID of the Task. +// - options - ListSubTasksOptions contains the optional parameters for the Client.NewListSubTasksPager method. +func (client *Client) NewListSubTasksPager(jobID string, taskID string, options *ListSubTasksOptions) *runtime.Pager[ListSubTasksResponse] { + return runtime.NewPager(runtime.PagingHandler[ListSubTasksResponse]{ + More: func(page ListSubTasksResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ListSubTasksResponse) (ListSubTasksResponse, error) { + 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.listSubTasksCreateRequest(ctx, jobID, taskID, options) + }, nil) + if err != nil { + return ListSubTasksResponse{}, err + } + return client.listSubTasksHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listSubTasksCreateRequest creates the ListSubTasks request. +func (client *Client) listSubTasksCreateRequest(ctx context.Context, jobID string, taskID string, options *ListSubTasksOptions) (*policy.Request, error) { + host := "{endpoint}" + host = strings.ReplaceAll(host, "{endpoint}", client.endpoint) + urlPath := "/jobs/{jobId}/tasks/{taskId}/subtasksinfo" + if jobID == "" { + return nil, errors.New("parameter jobID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{jobId}", url.PathEscape(jobID)) + if taskID == "" { + return nil, errors.New("parameter taskID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{taskId}", url.PathEscape(taskID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.SelectParam != nil { + reqQP.Set("$select", strings.Join(options.SelectParam, ",")) + } + reqQP.Set("api-version", "2024-07-01.20.0") + if options != nil && options.Timeout != nil { + reqQP.Set("timeOut", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.Ocpdate != nil { + req.Raw().Header["ocp-date"] = []string{options.Ocpdate.Format(time.RFC1123)} + } + if options != nil && options.ReturnClientRequestID != nil { + req.Raw().Header["return-client-request-id"] = []string{strconv.FormatBool(*options.ReturnClientRequestID)} + } + return req, nil +} + +// listSubTasksHandleResponse handles the ListSubTasks response. +func (client *Client) listSubTasksHandleResponse(resp *http.Response) (ListSubTasksResponse, error) { + result := ListSubTasksResponse{} + if val := resp.Header.Get("client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = &val + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return ListSubTasksResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("request-id"); val != "" { + result.RequestID = &val + } + if err := runtime.UnmarshalAsJSON(resp, &result.TaskListSubtasksResult); err != nil { + return ListSubTasksResponse{}, err + } + return result, nil +} + +// NewListSupportedImagesPager - Lists all Virtual Machine Images supported by the Azure Batch service. +// +// Lists all Virtual Machine Images supported by the Azure Batch service. +// +// Generated from API version 2024-07-01.20.0 +// - options - ListSupportedImagesOptions contains the optional parameters for the Client.NewListSupportedImagesPager method. +func (client *Client) NewListSupportedImagesPager(options *ListSupportedImagesOptions) *runtime.Pager[ListSupportedImagesResponse] { + return runtime.NewPager(runtime.PagingHandler[ListSupportedImagesResponse]{ + More: func(page ListSupportedImagesResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ListSupportedImagesResponse) (ListSupportedImagesResponse, error) { + 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.listSupportedImagesCreateRequest(ctx, options) + }, nil) + if err != nil { + return ListSupportedImagesResponse{}, err + } + return client.listSupportedImagesHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listSupportedImagesCreateRequest creates the ListSupportedImages request. +func (client *Client) listSupportedImagesCreateRequest(ctx context.Context, options *ListSupportedImagesOptions) (*policy.Request, error) { + host := "{endpoint}" + host = strings.ReplaceAll(host, "{endpoint}", client.endpoint) + urlPath := "/supportedimages" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Filter != nil { + reqQP.Set("$filter", *options.Filter) + } + reqQP.Set("api-version", "2024-07-01.20.0") + if options != nil && options.MaxResults != nil { + reqQP.Set("maxresults", strconv.FormatInt(int64(*options.MaxResults), 10)) + } + if options != nil && options.Timeout != nil { + reqQP.Set("timeOut", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.Ocpdate != nil { + req.Raw().Header["ocp-date"] = []string{options.Ocpdate.Format(time.RFC1123)} + } + if options != nil && options.ReturnClientRequestID != nil { + req.Raw().Header["return-client-request-id"] = []string{strconv.FormatBool(*options.ReturnClientRequestID)} + } + return req, nil +} + +// listSupportedImagesHandleResponse handles the ListSupportedImages response. +func (client *Client) listSupportedImagesHandleResponse(resp *http.Response) (ListSupportedImagesResponse, error) { + result := ListSupportedImagesResponse{} + if val := resp.Header.Get("client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = &val + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return ListSupportedImagesResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("request-id"); val != "" { + result.RequestID = &val + } + if err := runtime.UnmarshalAsJSON(resp, &result.AccountListSupportedImagesResult); err != nil { + return ListSupportedImagesResponse{}, err + } + return result, nil +} + +// NewListTaskFilesPager - Lists the files in a Task's directory on its Compute Node. +// +// Lists the files in a Task's directory on its Compute Node. +// +// Generated from API version 2024-07-01.20.0 +// - jobID - The ID of the Job that contains the Task. +// - taskID - The ID of the Task whose files you want to list. +// - options - ListTaskFilesOptions contains the optional parameters for the Client.NewListTaskFilesPager method. +func (client *Client) NewListTaskFilesPager(jobID string, taskID string, options *ListTaskFilesOptions) *runtime.Pager[ListTaskFilesResponse] { + return runtime.NewPager(runtime.PagingHandler[ListTaskFilesResponse]{ + More: func(page ListTaskFilesResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ListTaskFilesResponse) (ListTaskFilesResponse, error) { + 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.listTaskFilesCreateRequest(ctx, jobID, taskID, options) + }, nil) + if err != nil { + return ListTaskFilesResponse{}, err + } + return client.listTaskFilesHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listTaskFilesCreateRequest creates the ListTaskFiles request. +func (client *Client) listTaskFilesCreateRequest(ctx context.Context, jobID string, taskID string, options *ListTaskFilesOptions) (*policy.Request, error) { + host := "{endpoint}" + host = strings.ReplaceAll(host, "{endpoint}", client.endpoint) + urlPath := "/jobs/{jobId}/tasks/{taskId}/files" + if jobID == "" { + return nil, errors.New("parameter jobID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{jobId}", url.PathEscape(jobID)) + if taskID == "" { + return nil, errors.New("parameter taskID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{taskId}", url.PathEscape(taskID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Filter != nil { + reqQP.Set("$filter", *options.Filter) + } + reqQP.Set("api-version", "2024-07-01.20.0") + if options != nil && options.MaxResults != nil { + reqQP.Set("maxresults", strconv.FormatInt(int64(*options.MaxResults), 10)) + } + if options != nil && options.Recursive != nil { + reqQP.Set("recursive", strconv.FormatBool(*options.Recursive)) + } + if options != nil && options.Timeout != nil { + reqQP.Set("timeOut", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.Ocpdate != nil { + req.Raw().Header["ocp-date"] = []string{options.Ocpdate.Format(time.RFC1123)} + } + if options != nil && options.ReturnClientRequestID != nil { + req.Raw().Header["return-client-request-id"] = []string{strconv.FormatBool(*options.ReturnClientRequestID)} + } + return req, nil +} + +// listTaskFilesHandleResponse handles the ListTaskFiles response. +func (client *Client) listTaskFilesHandleResponse(resp *http.Response) (ListTaskFilesResponse, error) { + result := ListTaskFilesResponse{} + if val := resp.Header.Get("client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = &val + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return ListTaskFilesResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("request-id"); val != "" { + result.RequestID = &val + } + if err := runtime.UnmarshalAsJSON(resp, &result.NodeFileListResult); err != nil { + return ListTaskFilesResponse{}, err + } + return result, nil +} + +// NewListTasksPager - Lists all of the Tasks that are associated with the specified Job. +// +// For multi-instance Tasks, information such as affinityId, executionInfo and +// nodeInfo refer to the primary Task. Use the list subtasks API to retrieve +// information about subtasks. +// +// Generated from API version 2024-07-01.20.0 +// - jobID - The ID of the Job. +// - options - ListTasksOptions contains the optional parameters for the Client.NewListTasksPager method. +func (client *Client) NewListTasksPager(jobID string, options *ListTasksOptions) *runtime.Pager[ListTasksResponse] { + return runtime.NewPager(runtime.PagingHandler[ListTasksResponse]{ + More: func(page ListTasksResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ListTasksResponse) (ListTasksResponse, error) { + 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.listTasksCreateRequest(ctx, jobID, options) + }, nil) + if err != nil { + return ListTasksResponse{}, err + } + return client.listTasksHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listTasksCreateRequest creates the ListTasks request. +func (client *Client) listTasksCreateRequest(ctx context.Context, jobID string, options *ListTasksOptions) (*policy.Request, error) { + host := "{endpoint}" + host = strings.ReplaceAll(host, "{endpoint}", client.endpoint) + urlPath := "/jobs/{jobId}/tasks" + if jobID == "" { + return nil, errors.New("parameter jobID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{jobId}", url.PathEscape(jobID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Expand != nil { + reqQP.Set("$expand", strings.Join(options.Expand, ",")) + } + if options != nil && options.Filter != nil { + reqQP.Set("$filter", *options.Filter) + } + if options != nil && options.SelectParam != nil { + reqQP.Set("$select", strings.Join(options.SelectParam, ",")) + } + reqQP.Set("api-version", "2024-07-01.20.0") + if options != nil && options.MaxResults != nil { + reqQP.Set("maxresults", strconv.FormatInt(int64(*options.MaxResults), 10)) + } + if options != nil && options.Timeout != nil { + reqQP.Set("timeOut", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.Ocpdate != nil { + req.Raw().Header["ocp-date"] = []string{options.Ocpdate.Format(time.RFC1123)} + } + if options != nil && options.ReturnClientRequestID != nil { + req.Raw().Header["return-client-request-id"] = []string{strconv.FormatBool(*options.ReturnClientRequestID)} + } + return req, nil +} + +// listTasksHandleResponse handles the ListTasks response. +func (client *Client) listTasksHandleResponse(resp *http.Response) (ListTasksResponse, error) { + result := ListTasksResponse{} + if val := resp.Header.Get("client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = &val + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return ListTasksResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("request-id"); val != "" { + result.RequestID = &val + } + if err := runtime.UnmarshalAsJSON(resp, &result.TaskListResult); err != nil { + return ListTasksResponse{}, err + } + return result, nil +} + +// PoolExists - Gets basic properties of a Pool. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-07-01.20.0 +// - poolID - The ID of the Pool to get. +// - options - PoolExistsOptions contains the optional parameters for the Client.PoolExists method. +func (client *Client) PoolExists(ctx context.Context, poolID string, options *PoolExistsOptions) (PoolExistsResponse, error) { + var err error + ctx, endSpan := runtime.StartSpan(ctx, "Client.PoolExists", client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.poolExistsCreateRequest(ctx, poolID, options) + if err != nil { + return PoolExistsResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return PoolExistsResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusNotFound) { + err = runtime.NewResponseError(httpResp) + return PoolExistsResponse{}, err + } + resp, err := client.poolExistsHandleResponse(httpResp) + return resp, err +} + +// poolExistsCreateRequest creates the PoolExists request. +func (client *Client) poolExistsCreateRequest(ctx context.Context, poolID string, options *PoolExistsOptions) (*policy.Request, error) { + host := "{endpoint}" + host = strings.ReplaceAll(host, "{endpoint}", client.endpoint) + urlPath := "/pools/{poolId}" + if poolID == "" { + return nil, errors.New("parameter poolID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{poolId}", url.PathEscape(poolID)) + req, err := runtime.NewRequest(ctx, http.MethodHead, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2024-07-01.20.0") + if options != nil && options.Timeout != nil { + reqQP.Set("timeOut", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.IfMatch != nil { + req.Raw().Header["If-Match"] = []string{*options.IfMatch} + } + if options != nil && options.IfModifiedSince != nil { + req.Raw().Header["If-Modified-Since"] = []string{options.IfModifiedSince.Format(time.RFC1123)} + } + if options != nil && options.IfNoneMatch != nil { + req.Raw().Header["If-None-Match"] = []string{*options.IfNoneMatch} + } + if options != nil && options.IfUnmodifiedSince != nil { + req.Raw().Header["If-Unmodified-Since"] = []string{options.IfUnmodifiedSince.Format(time.RFC1123)} + } + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.Ocpdate != nil { + req.Raw().Header["ocp-date"] = []string{options.Ocpdate.Format(time.RFC1123)} + } + if options != nil && options.ReturnClientRequestID != nil { + req.Raw().Header["return-client-request-id"] = []string{strconv.FormatBool(*options.ReturnClientRequestID)} + } + return req, nil +} + +// poolExistsHandleResponse handles the PoolExists response. +func (client *Client) poolExistsHandleResponse(resp *http.Response) (PoolExistsResponse, error) { + result := PoolExistsResponse{} + if val := resp.Header.Get("client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = &val + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return PoolExistsResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("request-id"); val != "" { + result.RequestID = &val + } + return result, nil +} + +// ReactivateTask - Reactivates a Task, allowing it to run again even if its retry count has been +// exhausted. +// +// Reactivation makes a Task eligible to be retried again up to its maximum retry +// count. The Task's state is changed to active. As the Task is no longer in the +// completed state, any previous exit code or failure information is no longer +// available after reactivation. Each time a Task is reactivated, its retry count +// is reset to 0. Reactivation will fail for Tasks that are not completed or that +// previously completed successfully (with an exit code of 0). Additionally, it +// will fail if the Job has completed (or is terminating or deleting). +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-07-01.20.0 +// - jobID - The ID of the Job containing the Task. +// - taskID - The ID of the Task to reactivate. +// - options - ReactivateTaskOptions contains the optional parameters for the Client.ReactivateTask method. +func (client *Client) ReactivateTask(ctx context.Context, jobID string, taskID string, options *ReactivateTaskOptions) (ReactivateTaskResponse, error) { + var err error + ctx, endSpan := runtime.StartSpan(ctx, "Client.ReactivateTask", client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.reactivateTaskCreateRequest(ctx, jobID, taskID, options) + if err != nil { + return ReactivateTaskResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ReactivateTaskResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ReactivateTaskResponse{}, err + } + resp, err := client.reactivateTaskHandleResponse(httpResp) + return resp, err +} + +// reactivateTaskCreateRequest creates the ReactivateTask request. +func (client *Client) reactivateTaskCreateRequest(ctx context.Context, jobID string, taskID string, options *ReactivateTaskOptions) (*policy.Request, error) { + host := "{endpoint}" + host = strings.ReplaceAll(host, "{endpoint}", client.endpoint) + urlPath := "/jobs/{jobId}/tasks/{taskId}/reactivate" + if jobID == "" { + return nil, errors.New("parameter jobID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{jobId}", url.PathEscape(jobID)) + if taskID == "" { + return nil, errors.New("parameter taskID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{taskId}", url.PathEscape(taskID)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2024-07-01.20.0") + if options != nil && options.Timeout != nil { + reqQP.Set("timeOut", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.IfMatch != nil { + req.Raw().Header["If-Match"] = []string{*options.IfMatch} + } + if options != nil && options.IfModifiedSince != nil { + req.Raw().Header["If-Modified-Since"] = []string{options.IfModifiedSince.Format(time.RFC1123)} + } + if options != nil && options.IfNoneMatch != nil { + req.Raw().Header["If-None-Match"] = []string{*options.IfNoneMatch} + } + if options != nil && options.IfUnmodifiedSince != nil { + req.Raw().Header["If-Unmodified-Since"] = []string{options.IfUnmodifiedSince.Format(time.RFC1123)} + } + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.Ocpdate != nil { + req.Raw().Header["ocp-date"] = []string{options.Ocpdate.Format(time.RFC1123)} + } + if options != nil && options.ReturnClientRequestID != nil { + req.Raw().Header["return-client-request-id"] = []string{strconv.FormatBool(*options.ReturnClientRequestID)} + } + return req, nil +} + +// reactivateTaskHandleResponse handles the ReactivateTask response. +func (client *Client) reactivateTaskHandleResponse(resp *http.Response) (ReactivateTaskResponse, error) { + result := ReactivateTaskResponse{} + if val := resp.Header.Get("client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("DataServiceId"); val != "" { + result.DataServiceID = &val + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = &val + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return ReactivateTaskResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("request-id"); val != "" { + result.RequestID = &val + } + return result, nil +} + +// RebootNode - Restarts the specified Compute Node. +// +// You can restart a Compute Node only if it is in an idle or running state. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-07-01.20.0 +// - poolID - The ID of the Pool that contains the Compute Node. +// - nodeID - The ID of the Compute Node that you want to restart. +// - options - RebootNodeOptions contains the optional parameters for the Client.RebootNode method. +func (client *Client) RebootNode(ctx context.Context, poolID string, nodeID string, options *RebootNodeOptions) (RebootNodeResponse, error) { + var err error + ctx, endSpan := runtime.StartSpan(ctx, "Client.RebootNode", client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.rebootNodeCreateRequest(ctx, poolID, nodeID, options) + if err != nil { + return RebootNodeResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return RebootNodeResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return RebootNodeResponse{}, err + } + resp, err := client.rebootNodeHandleResponse(httpResp) + return resp, err +} + +// rebootNodeCreateRequest creates the RebootNode request. +func (client *Client) rebootNodeCreateRequest(ctx context.Context, poolID string, nodeID string, options *RebootNodeOptions) (*policy.Request, error) { + host := "{endpoint}" + host = strings.ReplaceAll(host, "{endpoint}", client.endpoint) + urlPath := "/pools/{poolId}/nodes/{nodeId}/reboot" + if poolID == "" { + return nil, errors.New("parameter poolID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{poolId}", url.PathEscape(poolID)) + if nodeID == "" { + return nil, errors.New("parameter nodeID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{nodeId}", url.PathEscape(nodeID)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2024-07-01.20.0") + if options != nil && options.Timeout != nil { + reqQP.Set("timeOut", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.Ocpdate != nil { + req.Raw().Header["ocp-date"] = []string{options.Ocpdate.Format(time.RFC1123)} + } + if options != nil && options.ReturnClientRequestID != nil { + req.Raw().Header["return-client-request-id"] = []string{strconv.FormatBool(*options.ReturnClientRequestID)} + } + if options != nil && options.Parameters != nil { + req.Raw().Header["Content-Type"] = []string{"application/json; odata=minimalmetadata"} + if err := runtime.MarshalAsJSON(req, *options.Parameters); err != nil { + return nil, err + } + return req, nil + } + return req, nil +} + +// rebootNodeHandleResponse handles the RebootNode response. +func (client *Client) rebootNodeHandleResponse(resp *http.Response) (RebootNodeResponse, error) { + result := RebootNodeResponse{} + if val := resp.Header.Get("client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("DataServiceId"); val != "" { + result.DataServiceID = &val + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = &val + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return RebootNodeResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("request-id"); val != "" { + result.RequestID = &val + } + return result, nil +} + +// ReimageNode - Reinstalls the operating system on the specified Compute Node. +// +// You can reinstall the operating system on a Compute Node only if it is in an +// idle or running state. This API can be invoked only on Pools created with the +// cloud service configuration property. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-07-01.20.0 +// - poolID - The ID of the Pool that contains the Compute Node. +// - nodeID - The ID of the Compute Node that you want to restart. +// - options - ReimageNodeOptions contains the optional parameters for the Client.ReimageNode method. +func (client *Client) ReimageNode(ctx context.Context, poolID string, nodeID string, options *ReimageNodeOptions) (ReimageNodeResponse, error) { + var err error + ctx, endSpan := runtime.StartSpan(ctx, "Client.ReimageNode", client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.reimageNodeCreateRequest(ctx, poolID, nodeID, options) + if err != nil { + return ReimageNodeResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ReimageNodeResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return ReimageNodeResponse{}, err + } + resp, err := client.reimageNodeHandleResponse(httpResp) + return resp, err +} + +// reimageNodeCreateRequest creates the ReimageNode request. +func (client *Client) reimageNodeCreateRequest(ctx context.Context, poolID string, nodeID string, options *ReimageNodeOptions) (*policy.Request, error) { + host := "{endpoint}" + host = strings.ReplaceAll(host, "{endpoint}", client.endpoint) + urlPath := "/pools/{poolId}/nodes/{nodeId}/reimage" + if poolID == "" { + return nil, errors.New("parameter poolID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{poolId}", url.PathEscape(poolID)) + if nodeID == "" { + return nil, errors.New("parameter nodeID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{nodeId}", url.PathEscape(nodeID)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2024-07-01.20.0") + if options != nil && options.Timeout != nil { + reqQP.Set("timeOut", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.Ocpdate != nil { + req.Raw().Header["ocp-date"] = []string{options.Ocpdate.Format(time.RFC1123)} + } + if options != nil && options.ReturnClientRequestID != nil { + req.Raw().Header["return-client-request-id"] = []string{strconv.FormatBool(*options.ReturnClientRequestID)} + } + if options != nil && options.Parameters != nil { + req.Raw().Header["Content-Type"] = []string{"application/json; odata=minimalmetadata"} + if err := runtime.MarshalAsJSON(req, *options.Parameters); err != nil { + return nil, err + } + return req, nil + } + return req, nil +} + +// reimageNodeHandleResponse handles the ReimageNode response. +func (client *Client) reimageNodeHandleResponse(resp *http.Response) (ReimageNodeResponse, error) { + result := ReimageNodeResponse{} + if val := resp.Header.Get("client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("DataServiceId"); val != "" { + result.DataServiceID = &val + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = &val + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return ReimageNodeResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("request-id"); val != "" { + result.RequestID = &val + } + return result, nil +} + +// RemoveNodes - Removes Compute Nodes from the specified Pool. +// +// This operation can only run when the allocation state of the Pool is steady. +// When this operation runs, the allocation state changes from steady to resizing. +// Each request may remove up to 100 nodes. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-07-01.20.0 +// - poolID - The ID of the Pool to get. +// - content - The options to use for removing the node. +// - options - RemoveNodesOptions contains the optional parameters for the Client.RemoveNodes method. +func (client *Client) RemoveNodes(ctx context.Context, poolID string, content RemoveNodeContent, options *RemoveNodesOptions) (RemoveNodesResponse, error) { + var err error + ctx, endSpan := runtime.StartSpan(ctx, "Client.RemoveNodes", client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.removeNodesCreateRequest(ctx, poolID, content, options) + if err != nil { + return RemoveNodesResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return RemoveNodesResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return RemoveNodesResponse{}, err + } + resp, err := client.removeNodesHandleResponse(httpResp) + return resp, err +} + +// removeNodesCreateRequest creates the RemoveNodes request. +func (client *Client) removeNodesCreateRequest(ctx context.Context, poolID string, content RemoveNodeContent, options *RemoveNodesOptions) (*policy.Request, error) { + host := "{endpoint}" + host = strings.ReplaceAll(host, "{endpoint}", client.endpoint) + urlPath := "/pools/{poolId}/removenodes" + if poolID == "" { + return nil, errors.New("parameter poolID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{poolId}", url.PathEscape(poolID)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2024-07-01.20.0") + if options != nil && options.Timeout != nil { + reqQP.Set("timeOut", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.IfMatch != nil { + req.Raw().Header["If-Match"] = []string{*options.IfMatch} + } + if options != nil && options.IfModifiedSince != nil { + req.Raw().Header["If-Modified-Since"] = []string{options.IfModifiedSince.Format(time.RFC1123)} + } + if options != nil && options.IfNoneMatch != nil { + req.Raw().Header["If-None-Match"] = []string{*options.IfNoneMatch} + } + if options != nil && options.IfUnmodifiedSince != nil { + req.Raw().Header["If-Unmodified-Since"] = []string{options.IfUnmodifiedSince.Format(time.RFC1123)} + } + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.Ocpdate != nil { + req.Raw().Header["ocp-date"] = []string{options.Ocpdate.Format(time.RFC1123)} + } + if options != nil && options.ReturnClientRequestID != nil { + req.Raw().Header["return-client-request-id"] = []string{strconv.FormatBool(*options.ReturnClientRequestID)} + } + req.Raw().Header["Content-Type"] = []string{"application/json; odata=minimalmetadata"} + if err := runtime.MarshalAsJSON(req, content); err != nil { + return nil, err + } + return req, nil +} + +// removeNodesHandleResponse handles the RemoveNodes response. +func (client *Client) removeNodesHandleResponse(resp *http.Response) (RemoveNodesResponse, error) { + result := RemoveNodesResponse{} + if val := resp.Header.Get("client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("DataServiceId"); val != "" { + result.DataServiceID = &val + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = &val + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return RemoveNodesResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("request-id"); val != "" { + result.RequestID = &val + } + return result, nil +} + +// ReplaceJob - Updates the properties of the specified Job. +// +// This fully replaces all the updatable properties of the Job. For example, if +// the Job has constraints associated with it and if constraints is not specified +// with this request, then the Batch service will remove the existing constraints. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-07-01.20.0 +// - jobID - The ID of the Job whose properties you want to update. +// - job - A job with updated properties +// - options - ReplaceJobOptions contains the optional parameters for the Client.ReplaceJob method. +func (client *Client) ReplaceJob(ctx context.Context, jobID string, job Job, options *ReplaceJobOptions) (ReplaceJobResponse, error) { + var err error + ctx, endSpan := runtime.StartSpan(ctx, "Client.ReplaceJob", client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.replaceJobCreateRequest(ctx, jobID, job, options) + if err != nil { + return ReplaceJobResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ReplaceJobResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ReplaceJobResponse{}, err + } + resp, err := client.replaceJobHandleResponse(httpResp) + return resp, err +} + +// replaceJobCreateRequest creates the ReplaceJob request. +func (client *Client) replaceJobCreateRequest(ctx context.Context, jobID string, job Job, options *ReplaceJobOptions) (*policy.Request, error) { + host := "{endpoint}" + host = strings.ReplaceAll(host, "{endpoint}", client.endpoint) + urlPath := "/jobs/{jobId}" + if jobID == "" { + return nil, errors.New("parameter jobID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{jobId}", url.PathEscape(jobID)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2024-07-01.20.0") + if options != nil && options.Timeout != nil { + reqQP.Set("timeOut", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.IfMatch != nil { + req.Raw().Header["If-Match"] = []string{*options.IfMatch} + } + if options != nil && options.IfModifiedSince != nil { + req.Raw().Header["If-Modified-Since"] = []string{options.IfModifiedSince.Format(time.RFC1123)} + } + if options != nil && options.IfNoneMatch != nil { + req.Raw().Header["If-None-Match"] = []string{*options.IfNoneMatch} + } + if options != nil && options.IfUnmodifiedSince != nil { + req.Raw().Header["If-Unmodified-Since"] = []string{options.IfUnmodifiedSince.Format(time.RFC1123)} + } + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.Ocpdate != nil { + req.Raw().Header["ocp-date"] = []string{options.Ocpdate.Format(time.RFC1123)} + } + if options != nil && options.ReturnClientRequestID != nil { + req.Raw().Header["return-client-request-id"] = []string{strconv.FormatBool(*options.ReturnClientRequestID)} + } + req.Raw().Header["Content-Type"] = []string{"application/json; odata=minimalmetadata"} + if err := runtime.MarshalAsJSON(req, job); err != nil { + return nil, err + } + return req, nil +} + +// replaceJobHandleResponse handles the ReplaceJob response. +func (client *Client) replaceJobHandleResponse(resp *http.Response) (ReplaceJobResponse, error) { + result := ReplaceJobResponse{} + if val := resp.Header.Get("client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("DataServiceId"); val != "" { + result.DataServiceID = &val + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = &val + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return ReplaceJobResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("request-id"); val != "" { + result.RequestID = &val + } + return result, nil +} + +// ReplaceJobSchedule - Updates the properties of the specified Job Schedule. +// +// This fully replaces all the updatable properties of the Job Schedule. For +// example, if the schedule property is not specified with this request, then the +// Batch service will remove the existing schedule. Changes to a Job Schedule only +// impact Jobs created by the schedule after the update has taken place; currently +// running Jobs are unaffected. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-07-01.20.0 +// - jobScheduleID - The ID of the Job Schedule to update. +// - jobSchedule - A Job Schedule with updated properties +// - options - ReplaceJobScheduleOptions contains the optional parameters for the Client.ReplaceJobSchedule method. +func (client *Client) ReplaceJobSchedule(ctx context.Context, jobScheduleID string, jobSchedule JobSchedule, options *ReplaceJobScheduleOptions) (ReplaceJobScheduleResponse, error) { + var err error + ctx, endSpan := runtime.StartSpan(ctx, "Client.ReplaceJobSchedule", client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.replaceJobScheduleCreateRequest(ctx, jobScheduleID, jobSchedule, options) + if err != nil { + return ReplaceJobScheduleResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ReplaceJobScheduleResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ReplaceJobScheduleResponse{}, err + } + resp, err := client.replaceJobScheduleHandleResponse(httpResp) + return resp, err +} + +// replaceJobScheduleCreateRequest creates the ReplaceJobSchedule request. +func (client *Client) replaceJobScheduleCreateRequest(ctx context.Context, jobScheduleID string, jobSchedule JobSchedule, options *ReplaceJobScheduleOptions) (*policy.Request, error) { + host := "{endpoint}" + host = strings.ReplaceAll(host, "{endpoint}", client.endpoint) + urlPath := "/jobschedules/{jobScheduleId}" + if jobScheduleID == "" { + return nil, errors.New("parameter jobScheduleID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{jobScheduleId}", url.PathEscape(jobScheduleID)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2024-07-01.20.0") + if options != nil && options.Timeout != nil { + reqQP.Set("timeOut", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.IfMatch != nil { + req.Raw().Header["If-Match"] = []string{*options.IfMatch} + } + if options != nil && options.IfModifiedSince != nil { + req.Raw().Header["If-Modified-Since"] = []string{options.IfModifiedSince.Format(time.RFC1123)} + } + if options != nil && options.IfNoneMatch != nil { + req.Raw().Header["If-None-Match"] = []string{*options.IfNoneMatch} + } + if options != nil && options.IfUnmodifiedSince != nil { + req.Raw().Header["If-Unmodified-Since"] = []string{options.IfUnmodifiedSince.Format(time.RFC1123)} + } + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.Ocpdate != nil { + req.Raw().Header["ocp-date"] = []string{options.Ocpdate.Format(time.RFC1123)} + } + if options != nil && options.ReturnClientRequestID != nil { + req.Raw().Header["return-client-request-id"] = []string{strconv.FormatBool(*options.ReturnClientRequestID)} + } + req.Raw().Header["Content-Type"] = []string{"application/json; odata=minimalmetadata"} + if err := runtime.MarshalAsJSON(req, jobSchedule); err != nil { + return nil, err + } + return req, nil +} + +// replaceJobScheduleHandleResponse handles the ReplaceJobSchedule response. +func (client *Client) replaceJobScheduleHandleResponse(resp *http.Response) (ReplaceJobScheduleResponse, error) { + result := ReplaceJobScheduleResponse{} + if val := resp.Header.Get("client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("DataServiceId"); val != "" { + result.DataServiceID = &val + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = &val + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return ReplaceJobScheduleResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("request-id"); val != "" { + result.RequestID = &val + } + return result, nil +} + +// ReplaceNodeUser - Updates the password and expiration time of a user Account on the specified Compute Node. +// +// This operation replaces of all the updatable properties of the Account. For +// example, if the expiryTime element is not specified, the current value is +// replaced with the default value, not left unmodified. You can update a user +// Account on a Compute Node only when it is in the idle or running state. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-07-01.20.0 +// - poolID - The ID of the Pool that contains the Compute Node. +// - nodeID - The ID of the machine on which you want to update a user Account. +// - userName - The name of the user Account to update. +// - content - The options to use for updating the user. +// - options - ReplaceNodeUserOptions contains the optional parameters for the Client.ReplaceNodeUser method. +func (client *Client) ReplaceNodeUser(ctx context.Context, poolID string, nodeID string, userName string, content UpdateNodeUserContent, options *ReplaceNodeUserOptions) (ReplaceNodeUserResponse, error) { + var err error + ctx, endSpan := runtime.StartSpan(ctx, "Client.ReplaceNodeUser", client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.replaceNodeUserCreateRequest(ctx, poolID, nodeID, userName, content, options) + if err != nil { + return ReplaceNodeUserResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ReplaceNodeUserResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ReplaceNodeUserResponse{}, err + } + resp, err := client.replaceNodeUserHandleResponse(httpResp) + return resp, err +} + +// replaceNodeUserCreateRequest creates the ReplaceNodeUser request. +func (client *Client) replaceNodeUserCreateRequest(ctx context.Context, poolID string, nodeID string, userName string, content UpdateNodeUserContent, options *ReplaceNodeUserOptions) (*policy.Request, error) { + host := "{endpoint}" + host = strings.ReplaceAll(host, "{endpoint}", client.endpoint) + urlPath := "/pools/{poolId}/nodes/{nodeId}/users/{userName}" + if poolID == "" { + return nil, errors.New("parameter poolID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{poolId}", url.PathEscape(poolID)) + if nodeID == "" { + return nil, errors.New("parameter nodeID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{nodeId}", url.PathEscape(nodeID)) + if userName == "" { + return nil, errors.New("parameter userName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{userName}", url.PathEscape(userName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2024-07-01.20.0") + if options != nil && options.Timeout != nil { + reqQP.Set("timeOut", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.Ocpdate != nil { + req.Raw().Header["ocp-date"] = []string{options.Ocpdate.Format(time.RFC1123)} + } + if options != nil && options.ReturnClientRequestID != nil { + req.Raw().Header["return-client-request-id"] = []string{strconv.FormatBool(*options.ReturnClientRequestID)} + } + req.Raw().Header["Content-Type"] = []string{"application/json; odata=minimalmetadata"} + if err := runtime.MarshalAsJSON(req, content); err != nil { + return nil, err + } + return req, nil +} + +// replaceNodeUserHandleResponse handles the ReplaceNodeUser response. +func (client *Client) replaceNodeUserHandleResponse(resp *http.Response) (ReplaceNodeUserResponse, error) { + result := ReplaceNodeUserResponse{} + if val := resp.Header.Get("client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("DataServiceId"); val != "" { + result.DataServiceID = &val + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = &val + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return ReplaceNodeUserResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("request-id"); val != "" { + result.RequestID = &val + } + return result, nil +} + +// ReplacePoolProperties - Updates the properties of the specified Pool. +// +// This fully replaces all the updatable properties of the Pool. For example, if +// the Pool has a StartTask associated with it and if StartTask is not specified +// with this request, then the Batch service will remove the existing StartTask. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-07-01.20.0 +// - poolID - The ID of the Pool to update. +// - pool - The options to use for replacing properties on the pool. +// - options - ReplacePoolPropertiesOptions contains the optional parameters for the Client.ReplacePoolProperties method. +func (client *Client) ReplacePoolProperties(ctx context.Context, poolID string, pool ReplacePoolContent, options *ReplacePoolPropertiesOptions) (ReplacePoolPropertiesResponse, error) { + var err error + ctx, endSpan := runtime.StartSpan(ctx, "Client.ReplacePoolProperties", client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.replacePoolPropertiesCreateRequest(ctx, poolID, pool, options) + if err != nil { + return ReplacePoolPropertiesResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ReplacePoolPropertiesResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ReplacePoolPropertiesResponse{}, err + } + resp, err := client.replacePoolPropertiesHandleResponse(httpResp) + return resp, err +} + +// replacePoolPropertiesCreateRequest creates the ReplacePoolProperties request. +func (client *Client) replacePoolPropertiesCreateRequest(ctx context.Context, poolID string, pool ReplacePoolContent, options *ReplacePoolPropertiesOptions) (*policy.Request, error) { + host := "{endpoint}" + host = strings.ReplaceAll(host, "{endpoint}", client.endpoint) + urlPath := "/pools/{poolId}/updateproperties" + if poolID == "" { + return nil, errors.New("parameter poolID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{poolId}", url.PathEscape(poolID)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2024-07-01.20.0") + if options != nil && options.Timeout != nil { + reqQP.Set("timeOut", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.Ocpdate != nil { + req.Raw().Header["ocp-date"] = []string{options.Ocpdate.Format(time.RFC1123)} + } + if options != nil && options.ReturnClientRequestID != nil { + req.Raw().Header["return-client-request-id"] = []string{strconv.FormatBool(*options.ReturnClientRequestID)} + } + req.Raw().Header["Content-Type"] = []string{"application/json; odata=minimalmetadata"} + if err := runtime.MarshalAsJSON(req, pool); err != nil { + return nil, err + } + return req, nil +} + +// replacePoolPropertiesHandleResponse handles the ReplacePoolProperties response. +func (client *Client) replacePoolPropertiesHandleResponse(resp *http.Response) (ReplacePoolPropertiesResponse, error) { + result := ReplacePoolPropertiesResponse{} + if val := resp.Header.Get("client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("DataServiceId"); val != "" { + result.DataServiceID = &val + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = &val + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return ReplacePoolPropertiesResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("request-id"); val != "" { + result.RequestID = &val + } + return result, nil +} + +// ReplaceTask - Updates the properties of the specified Task. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-07-01.20.0 +// - jobID - The ID of the Job containing the Task. +// - taskID - The ID of the Task to update. +// - task - The Task to update. +// - options - ReplaceTaskOptions contains the optional parameters for the Client.ReplaceTask method. +func (client *Client) ReplaceTask(ctx context.Context, jobID string, taskID string, task Task, options *ReplaceTaskOptions) (ReplaceTaskResponse, error) { + var err error + ctx, endSpan := runtime.StartSpan(ctx, "Client.ReplaceTask", client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.replaceTaskCreateRequest(ctx, jobID, taskID, task, options) + if err != nil { + return ReplaceTaskResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ReplaceTaskResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ReplaceTaskResponse{}, err + } + resp, err := client.replaceTaskHandleResponse(httpResp) + return resp, err +} + +// replaceTaskCreateRequest creates the ReplaceTask request. +func (client *Client) replaceTaskCreateRequest(ctx context.Context, jobID string, taskID string, task Task, options *ReplaceTaskOptions) (*policy.Request, error) { + host := "{endpoint}" + host = strings.ReplaceAll(host, "{endpoint}", client.endpoint) + urlPath := "/jobs/{jobId}/tasks/{taskId}" + if jobID == "" { + return nil, errors.New("parameter jobID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{jobId}", url.PathEscape(jobID)) + if taskID == "" { + return nil, errors.New("parameter taskID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{taskId}", url.PathEscape(taskID)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2024-07-01.20.0") + if options != nil && options.Timeout != nil { + reqQP.Set("timeOut", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.IfMatch != nil { + req.Raw().Header["If-Match"] = []string{*options.IfMatch} + } + if options != nil && options.IfModifiedSince != nil { + req.Raw().Header["If-Modified-Since"] = []string{options.IfModifiedSince.Format(time.RFC1123)} + } + if options != nil && options.IfNoneMatch != nil { + req.Raw().Header["If-None-Match"] = []string{*options.IfNoneMatch} + } + if options != nil && options.IfUnmodifiedSince != nil { + req.Raw().Header["If-Unmodified-Since"] = []string{options.IfUnmodifiedSince.Format(time.RFC1123)} + } + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.Ocpdate != nil { + req.Raw().Header["ocp-date"] = []string{options.Ocpdate.Format(time.RFC1123)} + } + if options != nil && options.ReturnClientRequestID != nil { + req.Raw().Header["return-client-request-id"] = []string{strconv.FormatBool(*options.ReturnClientRequestID)} + } + req.Raw().Header["Content-Type"] = []string{"application/json; odata=minimalmetadata"} + if err := runtime.MarshalAsJSON(req, task); err != nil { + return nil, err + } + return req, nil +} + +// replaceTaskHandleResponse handles the ReplaceTask response. +func (client *Client) replaceTaskHandleResponse(resp *http.Response) (ReplaceTaskResponse, error) { + result := ReplaceTaskResponse{} + if val := resp.Header.Get("client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("DataServiceId"); val != "" { + result.DataServiceID = &val + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = &val + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return ReplaceTaskResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("request-id"); val != "" { + result.RequestID = &val + } + return result, nil +} + +// ResizePool - Changes the number of Compute Nodes that are assigned to a Pool. +// +// You can only resize a Pool when its allocation state is steady. If the Pool is +// already resizing, the request fails with status code 409. When you resize a +// Pool, the Pool's allocation state changes from steady to resizing. You cannot +// resize Pools which are configured for automatic scaling. If you try to do this, +// the Batch service returns an error 409. If you resize a Pool downwards, the +// Batch service chooses which Compute Nodes to remove. To remove specific Compute +// Nodes, use the Pool remove Compute Nodes API instead. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-07-01.20.0 +// - poolID - The ID of the Pool to get. +// - content - The options to use for resizing the pool. +// - options - ResizePoolOptions contains the optional parameters for the Client.ResizePool method. +func (client *Client) ResizePool(ctx context.Context, poolID string, content ResizePoolContent, options *ResizePoolOptions) (ResizePoolResponse, error) { + var err error + ctx, endSpan := runtime.StartSpan(ctx, "Client.ResizePool", client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.resizePoolCreateRequest(ctx, poolID, content, options) + if err != nil { + return ResizePoolResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ResizePoolResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return ResizePoolResponse{}, err + } + resp, err := client.resizePoolHandleResponse(httpResp) + return resp, err +} + +// resizePoolCreateRequest creates the ResizePool request. +func (client *Client) resizePoolCreateRequest(ctx context.Context, poolID string, content ResizePoolContent, options *ResizePoolOptions) (*policy.Request, error) { + host := "{endpoint}" + host = strings.ReplaceAll(host, "{endpoint}", client.endpoint) + urlPath := "/pools/{poolId}/resize" + if poolID == "" { + return nil, errors.New("parameter poolID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{poolId}", url.PathEscape(poolID)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2024-07-01.20.0") + if options != nil && options.Timeout != nil { + reqQP.Set("timeOut", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.IfMatch != nil { + req.Raw().Header["If-Match"] = []string{*options.IfMatch} + } + if options != nil && options.IfModifiedSince != nil { + req.Raw().Header["If-Modified-Since"] = []string{options.IfModifiedSince.Format(time.RFC1123)} + } + if options != nil && options.IfNoneMatch != nil { + req.Raw().Header["If-None-Match"] = []string{*options.IfNoneMatch} + } + if options != nil && options.IfUnmodifiedSince != nil { + req.Raw().Header["If-Unmodified-Since"] = []string{options.IfUnmodifiedSince.Format(time.RFC1123)} + } + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.Ocpdate != nil { + req.Raw().Header["ocp-date"] = []string{options.Ocpdate.Format(time.RFC1123)} + } + if options != nil && options.ReturnClientRequestID != nil { + req.Raw().Header["return-client-request-id"] = []string{strconv.FormatBool(*options.ReturnClientRequestID)} + } + req.Raw().Header["Content-Type"] = []string{"application/json; odata=minimalmetadata"} + if err := runtime.MarshalAsJSON(req, content); err != nil { + return nil, err + } + return req, nil +} + +// resizePoolHandleResponse handles the ResizePool response. +func (client *Client) resizePoolHandleResponse(resp *http.Response) (ResizePoolResponse, error) { + result := ResizePoolResponse{} + if val := resp.Header.Get("client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("DataServiceId"); val != "" { + result.DataServiceID = &val + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = &val + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return ResizePoolResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("request-id"); val != "" { + result.RequestID = &val + } + return result, nil +} + +// StartNode - Starts the specified Compute Node. +// +// You can start a Compute Node only if it has been deallocated. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-07-01.20.0 +// - poolID - The ID of the Pool that contains the Compute Node. +// - nodeID - The ID of the Compute Node that you want to restart. +// - options - StartNodeOptions contains the optional parameters for the Client.StartNode method. +func (client *Client) StartNode(ctx context.Context, poolID string, nodeID string, options *StartNodeOptions) (StartNodeResponse, error) { + var err error + ctx, endSpan := runtime.StartSpan(ctx, "Client.StartNode", client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.startNodeCreateRequest(ctx, poolID, nodeID, options) + if err != nil { + return StartNodeResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return StartNodeResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return StartNodeResponse{}, err + } + resp, err := client.startNodeHandleResponse(httpResp) + return resp, err +} + +// startNodeCreateRequest creates the StartNode request. +func (client *Client) startNodeCreateRequest(ctx context.Context, poolID string, nodeID string, options *StartNodeOptions) (*policy.Request, error) { + host := "{endpoint}" + host = strings.ReplaceAll(host, "{endpoint}", client.endpoint) + urlPath := "/pools/{poolId}/nodes/{nodeId}/start" + if poolID == "" { + return nil, errors.New("parameter poolID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{poolId}", url.PathEscape(poolID)) + if nodeID == "" { + return nil, errors.New("parameter nodeID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{nodeId}", url.PathEscape(nodeID)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2024-07-01.20.0") + if options != nil && options.Timeout != nil { + reqQP.Set("timeOut", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.Ocpdate != nil { + req.Raw().Header["ocp-date"] = []string{options.Ocpdate.Format(time.RFC1123)} + } + if options != nil && options.ReturnClientRequestID != nil { + req.Raw().Header["return-client-request-id"] = []string{strconv.FormatBool(*options.ReturnClientRequestID)} + } + return req, nil +} + +// startNodeHandleResponse handles the StartNode response. +func (client *Client) startNodeHandleResponse(resp *http.Response) (StartNodeResponse, error) { + result := StartNodeResponse{} + if val := resp.Header.Get("client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("DataServiceId"); val != "" { + result.DataServiceID = &val + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = &val + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return StartNodeResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("request-id"); val != "" { + result.RequestID = &val + } + return result, nil +} + +// StopPoolResize - Stops an ongoing resize operation on the Pool. +// +// This does not restore the Pool to its previous state before the resize +// operation: it only stops any further changes being made, and the Pool maintains +// its current state. After stopping, the Pool stabilizes at the number of Compute +// Nodes it was at when the stop operation was done. During the stop operation, +// the Pool allocation state changes first to stopping and then to steady. A +// resize operation need not be an explicit resize Pool request; this API can also +// be used to halt the initial sizing of the Pool when it is created. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-07-01.20.0 +// - poolID - The ID of the Pool to get. +// - options - StopPoolResizeOptions contains the optional parameters for the Client.StopPoolResize method. +func (client *Client) StopPoolResize(ctx context.Context, poolID string, options *StopPoolResizeOptions) (StopPoolResizeResponse, error) { + var err error + ctx, endSpan := runtime.StartSpan(ctx, "Client.StopPoolResize", client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.stopPoolResizeCreateRequest(ctx, poolID, options) + if err != nil { + return StopPoolResizeResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return StopPoolResizeResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return StopPoolResizeResponse{}, err + } + resp, err := client.stopPoolResizeHandleResponse(httpResp) + return resp, err +} + +// stopPoolResizeCreateRequest creates the StopPoolResize request. +func (client *Client) stopPoolResizeCreateRequest(ctx context.Context, poolID string, options *StopPoolResizeOptions) (*policy.Request, error) { + host := "{endpoint}" + host = strings.ReplaceAll(host, "{endpoint}", client.endpoint) + urlPath := "/pools/{poolId}/stopresize" + if poolID == "" { + return nil, errors.New("parameter poolID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{poolId}", url.PathEscape(poolID)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2024-07-01.20.0") + if options != nil && options.Timeout != nil { + reqQP.Set("timeOut", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.IfMatch != nil { + req.Raw().Header["If-Match"] = []string{*options.IfMatch} + } + if options != nil && options.IfModifiedSince != nil { + req.Raw().Header["If-Modified-Since"] = []string{options.IfModifiedSince.Format(time.RFC1123)} + } + if options != nil && options.IfNoneMatch != nil { + req.Raw().Header["If-None-Match"] = []string{*options.IfNoneMatch} + } + if options != nil && options.IfUnmodifiedSince != nil { + req.Raw().Header["If-Unmodified-Since"] = []string{options.IfUnmodifiedSince.Format(time.RFC1123)} + } + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.Ocpdate != nil { + req.Raw().Header["ocp-date"] = []string{options.Ocpdate.Format(time.RFC1123)} + } + if options != nil && options.ReturnClientRequestID != nil { + req.Raw().Header["return-client-request-id"] = []string{strconv.FormatBool(*options.ReturnClientRequestID)} + } + return req, nil +} + +// stopPoolResizeHandleResponse handles the StopPoolResize response. +func (client *Client) stopPoolResizeHandleResponse(resp *http.Response) (StopPoolResizeResponse, error) { + result := StopPoolResizeResponse{} + if val := resp.Header.Get("client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("DataServiceId"); val != "" { + result.DataServiceID = &val + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = &val + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return StopPoolResizeResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("request-id"); val != "" { + result.RequestID = &val + } + return result, nil +} + +// TerminateJob - Terminates the specified Job, marking it as completed. +// +// When a Terminate Job request is received, the Batch service sets the Job to the +// terminating state. The Batch service then terminates any running Tasks +// associated with the Job and runs any required Job release Tasks. Then the Job +// moves into the completed state. If there are any Tasks in the Job in the active +// state, they will remain in the active state. Once a Job is terminated, new +// Tasks cannot be added and any remaining active Tasks will not be scheduled. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-07-01.20.0 +// - jobID - The ID of the Job to terminate. +// - options - TerminateJobOptions contains the optional parameters for the Client.TerminateJob method. +func (client *Client) TerminateJob(ctx context.Context, jobID string, options *TerminateJobOptions) (TerminateJobResponse, error) { + var err error + ctx, endSpan := runtime.StartSpan(ctx, "Client.TerminateJob", client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.terminateJobCreateRequest(ctx, jobID, options) + if err != nil { + return TerminateJobResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return TerminateJobResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return TerminateJobResponse{}, err + } + resp, err := client.terminateJobHandleResponse(httpResp) + return resp, err +} + +// terminateJobCreateRequest creates the TerminateJob request. +func (client *Client) terminateJobCreateRequest(ctx context.Context, jobID string, options *TerminateJobOptions) (*policy.Request, error) { + host := "{endpoint}" + host = strings.ReplaceAll(host, "{endpoint}", client.endpoint) + urlPath := "/jobs/{jobId}/terminate" + if jobID == "" { + return nil, errors.New("parameter jobID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{jobId}", url.PathEscape(jobID)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2024-07-01.20.0") + if options != nil && options.Force != nil { + reqQP.Set("force", strconv.FormatBool(*options.Force)) + } + if options != nil && options.Timeout != nil { + reqQP.Set("timeOut", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.IfMatch != nil { + req.Raw().Header["If-Match"] = []string{*options.IfMatch} + } + if options != nil && options.IfModifiedSince != nil { + req.Raw().Header["If-Modified-Since"] = []string{options.IfModifiedSince.Format(time.RFC1123)} + } + if options != nil && options.IfNoneMatch != nil { + req.Raw().Header["If-None-Match"] = []string{*options.IfNoneMatch} + } + if options != nil && options.IfUnmodifiedSince != nil { + req.Raw().Header["If-Unmodified-Since"] = []string{options.IfUnmodifiedSince.Format(time.RFC1123)} + } + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.Ocpdate != nil { + req.Raw().Header["ocp-date"] = []string{options.Ocpdate.Format(time.RFC1123)} + } + if options != nil && options.ReturnClientRequestID != nil { + req.Raw().Header["return-client-request-id"] = []string{strconv.FormatBool(*options.ReturnClientRequestID)} + } + if options != nil && options.Parameters != nil { + req.Raw().Header["Content-Type"] = []string{"application/json; odata=minimalmetadata"} + if err := runtime.MarshalAsJSON(req, *options.Parameters); err != nil { + return nil, err + } + return req, nil + } + return req, nil +} + +// terminateJobHandleResponse handles the TerminateJob response. +func (client *Client) terminateJobHandleResponse(resp *http.Response) (TerminateJobResponse, error) { + result := TerminateJobResponse{} + if val := resp.Header.Get("client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("DataServiceId"); val != "" { + result.DataServiceID = &val + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = &val + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return TerminateJobResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("request-id"); val != "" { + result.RequestID = &val + } + return result, nil +} + +// TerminateJobSchedule - Terminates a Job Schedule. +// +// Terminates a Job Schedule. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-07-01.20.0 +// - jobScheduleID - The ID of the Job Schedule to terminates. +// - options - TerminateJobScheduleOptions contains the optional parameters for the Client.TerminateJobSchedule method. +func (client *Client) TerminateJobSchedule(ctx context.Context, jobScheduleID string, options *TerminateJobScheduleOptions) (TerminateJobScheduleResponse, error) { + var err error + ctx, endSpan := runtime.StartSpan(ctx, "Client.TerminateJobSchedule", client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.terminateJobScheduleCreateRequest(ctx, jobScheduleID, options) + if err != nil { + return TerminateJobScheduleResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return TerminateJobScheduleResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return TerminateJobScheduleResponse{}, err + } + resp, err := client.terminateJobScheduleHandleResponse(httpResp) + return resp, err +} + +// terminateJobScheduleCreateRequest creates the TerminateJobSchedule request. +func (client *Client) terminateJobScheduleCreateRequest(ctx context.Context, jobScheduleID string, options *TerminateJobScheduleOptions) (*policy.Request, error) { + host := "{endpoint}" + host = strings.ReplaceAll(host, "{endpoint}", client.endpoint) + urlPath := "/jobschedules/{jobScheduleId}/terminate" + if jobScheduleID == "" { + return nil, errors.New("parameter jobScheduleID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{jobScheduleId}", url.PathEscape(jobScheduleID)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2024-07-01.20.0") + if options != nil && options.Force != nil { + reqQP.Set("force", strconv.FormatBool(*options.Force)) + } + if options != nil && options.Timeout != nil { + reqQP.Set("timeOut", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.IfMatch != nil { + req.Raw().Header["If-Match"] = []string{*options.IfMatch} + } + if options != nil && options.IfModifiedSince != nil { + req.Raw().Header["If-Modified-Since"] = []string{options.IfModifiedSince.Format(time.RFC1123)} + } + if options != nil && options.IfNoneMatch != nil { + req.Raw().Header["If-None-Match"] = []string{*options.IfNoneMatch} + } + if options != nil && options.IfUnmodifiedSince != nil { + req.Raw().Header["If-Unmodified-Since"] = []string{options.IfUnmodifiedSince.Format(time.RFC1123)} + } + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.Ocpdate != nil { + req.Raw().Header["ocp-date"] = []string{options.Ocpdate.Format(time.RFC1123)} + } + if options != nil && options.ReturnClientRequestID != nil { + req.Raw().Header["return-client-request-id"] = []string{strconv.FormatBool(*options.ReturnClientRequestID)} + } + return req, nil +} + +// terminateJobScheduleHandleResponse handles the TerminateJobSchedule response. +func (client *Client) terminateJobScheduleHandleResponse(resp *http.Response) (TerminateJobScheduleResponse, error) { + result := TerminateJobScheduleResponse{} + if val := resp.Header.Get("client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("DataServiceId"); val != "" { + result.DataServiceID = &val + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = &val + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return TerminateJobScheduleResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("request-id"); val != "" { + result.RequestID = &val + } + return result, nil +} + +// TerminateTask - Terminates the specified Task. +// +// When the Task has been terminated, it moves to the completed state. For +// multi-instance Tasks, the terminate Task operation applies synchronously to the +// primary task; subtasks are then terminated asynchronously in the background. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-07-01.20.0 +// - jobID - The ID of the Job containing the Task. +// - taskID - The ID of the Task to terminate. +// - options - TerminateTaskOptions contains the optional parameters for the Client.TerminateTask method. +func (client *Client) TerminateTask(ctx context.Context, jobID string, taskID string, options *TerminateTaskOptions) (TerminateTaskResponse, error) { + var err error + ctx, endSpan := runtime.StartSpan(ctx, "Client.TerminateTask", client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.terminateTaskCreateRequest(ctx, jobID, taskID, options) + if err != nil { + return TerminateTaskResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return TerminateTaskResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return TerminateTaskResponse{}, err + } + resp, err := client.terminateTaskHandleResponse(httpResp) + return resp, err +} + +// terminateTaskCreateRequest creates the TerminateTask request. +func (client *Client) terminateTaskCreateRequest(ctx context.Context, jobID string, taskID string, options *TerminateTaskOptions) (*policy.Request, error) { + host := "{endpoint}" + host = strings.ReplaceAll(host, "{endpoint}", client.endpoint) + urlPath := "/jobs/{jobId}/tasks/{taskId}/terminate" + if jobID == "" { + return nil, errors.New("parameter jobID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{jobId}", url.PathEscape(jobID)) + if taskID == "" { + return nil, errors.New("parameter taskID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{taskId}", url.PathEscape(taskID)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2024-07-01.20.0") + if options != nil && options.Timeout != nil { + reqQP.Set("timeOut", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.IfMatch != nil { + req.Raw().Header["If-Match"] = []string{*options.IfMatch} + } + if options != nil && options.IfModifiedSince != nil { + req.Raw().Header["If-Modified-Since"] = []string{options.IfModifiedSince.Format(time.RFC1123)} + } + if options != nil && options.IfNoneMatch != nil { + req.Raw().Header["If-None-Match"] = []string{*options.IfNoneMatch} + } + if options != nil && options.IfUnmodifiedSince != nil { + req.Raw().Header["If-Unmodified-Since"] = []string{options.IfUnmodifiedSince.Format(time.RFC1123)} + } + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.Ocpdate != nil { + req.Raw().Header["ocp-date"] = []string{options.Ocpdate.Format(time.RFC1123)} + } + if options != nil && options.ReturnClientRequestID != nil { + req.Raw().Header["return-client-request-id"] = []string{strconv.FormatBool(*options.ReturnClientRequestID)} + } + return req, nil +} + +// terminateTaskHandleResponse handles the TerminateTask response. +func (client *Client) terminateTaskHandleResponse(resp *http.Response) (TerminateTaskResponse, error) { + result := TerminateTaskResponse{} + if val := resp.Header.Get("client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("DataServiceId"); val != "" { + result.DataServiceID = &val + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = &val + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return TerminateTaskResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("request-id"); val != "" { + result.RequestID = &val + } + return result, nil +} + +// UpdateJob - Updates the properties of the specified Job. +// +// This replaces only the Job properties specified in the request. For example, if +// the Job has constraints, and a request does not specify the constraints +// element, then the Job keeps the existing constraints. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-07-01.20.0 +// - jobID - The ID of the Job whose properties you want to update. +// - job - The options to use for updating the Job. +// - options - UpdateJobOptions contains the optional parameters for the Client.UpdateJob method. +func (client *Client) UpdateJob(ctx context.Context, jobID string, job UpdateJobContent, options *UpdateJobOptions) (UpdateJobResponse, error) { + var err error + ctx, endSpan := runtime.StartSpan(ctx, "Client.UpdateJob", client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateJobCreateRequest(ctx, jobID, job, options) + if err != nil { + return UpdateJobResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return UpdateJobResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return UpdateJobResponse{}, err + } + resp, err := client.updateJobHandleResponse(httpResp) + return resp, err +} + +// updateJobCreateRequest creates the UpdateJob request. +func (client *Client) updateJobCreateRequest(ctx context.Context, jobID string, job UpdateJobContent, options *UpdateJobOptions) (*policy.Request, error) { + host := "{endpoint}" + host = strings.ReplaceAll(host, "{endpoint}", client.endpoint) + urlPath := "/jobs/{jobId}" + if jobID == "" { + return nil, errors.New("parameter jobID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{jobId}", url.PathEscape(jobID)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2024-07-01.20.0") + if options != nil && options.Timeout != nil { + reqQP.Set("timeOut", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.IfMatch != nil { + req.Raw().Header["If-Match"] = []string{*options.IfMatch} + } + if options != nil && options.IfModifiedSince != nil { + req.Raw().Header["If-Modified-Since"] = []string{options.IfModifiedSince.Format(time.RFC1123)} + } + if options != nil && options.IfNoneMatch != nil { + req.Raw().Header["If-None-Match"] = []string{*options.IfNoneMatch} + } + if options != nil && options.IfUnmodifiedSince != nil { + req.Raw().Header["If-Unmodified-Since"] = []string{options.IfUnmodifiedSince.Format(time.RFC1123)} + } + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.Ocpdate != nil { + req.Raw().Header["ocp-date"] = []string{options.Ocpdate.Format(time.RFC1123)} + } + if options != nil && options.ReturnClientRequestID != nil { + req.Raw().Header["return-client-request-id"] = []string{strconv.FormatBool(*options.ReturnClientRequestID)} + } + req.Raw().Header["Content-Type"] = []string{"application/json; odata=minimalmetadata"} + if err := runtime.MarshalAsJSON(req, job); err != nil { + return nil, err + } + return req, nil +} + +// updateJobHandleResponse handles the UpdateJob response. +func (client *Client) updateJobHandleResponse(resp *http.Response) (UpdateJobResponse, error) { + result := UpdateJobResponse{} + if val := resp.Header.Get("client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("DataServiceId"); val != "" { + result.DataServiceID = &val + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = &val + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return UpdateJobResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("request-id"); val != "" { + result.RequestID = &val + } + return result, nil +} + +// UpdateJobSchedule - Updates the properties of the specified Job Schedule. +// +// This replaces only the Job Schedule properties specified in the request. For +// example, if the schedule property is not specified with this request, then the +// Batch service will keep the existing schedule. Changes to a Job Schedule only +// impact Jobs created by the schedule after the update has taken place; currently +// running Jobs are unaffected. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-07-01.20.0 +// - jobScheduleID - The ID of the Job Schedule to update. +// - jobSchedule - The options to use for updating the Job Schedule. +// - options - UpdateJobScheduleOptions contains the optional parameters for the Client.UpdateJobSchedule method. +func (client *Client) UpdateJobSchedule(ctx context.Context, jobScheduleID string, jobSchedule UpdateJobScheduleContent, options *UpdateJobScheduleOptions) (UpdateJobScheduleResponse, error) { + var err error + ctx, endSpan := runtime.StartSpan(ctx, "Client.UpdateJobSchedule", client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateJobScheduleCreateRequest(ctx, jobScheduleID, jobSchedule, options) + if err != nil { + return UpdateJobScheduleResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return UpdateJobScheduleResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return UpdateJobScheduleResponse{}, err + } + resp, err := client.updateJobScheduleHandleResponse(httpResp) + return resp, err +} + +// updateJobScheduleCreateRequest creates the UpdateJobSchedule request. +func (client *Client) updateJobScheduleCreateRequest(ctx context.Context, jobScheduleID string, jobSchedule UpdateJobScheduleContent, options *UpdateJobScheduleOptions) (*policy.Request, error) { + host := "{endpoint}" + host = strings.ReplaceAll(host, "{endpoint}", client.endpoint) + urlPath := "/jobschedules/{jobScheduleId}" + if jobScheduleID == "" { + return nil, errors.New("parameter jobScheduleID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{jobScheduleId}", url.PathEscape(jobScheduleID)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2024-07-01.20.0") + if options != nil && options.Timeout != nil { + reqQP.Set("timeOut", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.IfMatch != nil { + req.Raw().Header["If-Match"] = []string{*options.IfMatch} + } + if options != nil && options.IfModifiedSince != nil { + req.Raw().Header["If-Modified-Since"] = []string{options.IfModifiedSince.Format(time.RFC1123)} + } + if options != nil && options.IfNoneMatch != nil { + req.Raw().Header["If-None-Match"] = []string{*options.IfNoneMatch} + } + if options != nil && options.IfUnmodifiedSince != nil { + req.Raw().Header["If-Unmodified-Since"] = []string{options.IfUnmodifiedSince.Format(time.RFC1123)} + } + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.Ocpdate != nil { + req.Raw().Header["ocp-date"] = []string{options.Ocpdate.Format(time.RFC1123)} + } + if options != nil && options.ReturnClientRequestID != nil { + req.Raw().Header["return-client-request-id"] = []string{strconv.FormatBool(*options.ReturnClientRequestID)} + } + req.Raw().Header["Content-Type"] = []string{"application/json; odata=minimalmetadata"} + if err := runtime.MarshalAsJSON(req, jobSchedule); err != nil { + return nil, err + } + return req, nil +} + +// updateJobScheduleHandleResponse handles the UpdateJobSchedule response. +func (client *Client) updateJobScheduleHandleResponse(resp *http.Response) (UpdateJobScheduleResponse, error) { + result := UpdateJobScheduleResponse{} + if val := resp.Header.Get("client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("DataServiceId"); val != "" { + result.DataServiceID = &val + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = &val + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return UpdateJobScheduleResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("request-id"); val != "" { + result.RequestID = &val + } + return result, nil +} + +// UpdatePool - Updates the properties of the specified Pool. +// +// This only replaces the Pool properties specified in the request. For example, +// if the Pool has a StartTask associated with it, and a request does not specify +// a StartTask element, then the Pool keeps the existing StartTask. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-07-01.20.0 +// - poolID - The ID of the Pool to get. +// - pool - The pool properties to update. +// - options - UpdatePoolOptions contains the optional parameters for the Client.UpdatePool method. +func (client *Client) UpdatePool(ctx context.Context, poolID string, pool UpdatePoolContent, options *UpdatePoolOptions) (UpdatePoolResponse, error) { + var err error + ctx, endSpan := runtime.StartSpan(ctx, "Client.UpdatePool", client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updatePoolCreateRequest(ctx, poolID, pool, options) + if err != nil { + return UpdatePoolResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return UpdatePoolResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return UpdatePoolResponse{}, err + } + resp, err := client.updatePoolHandleResponse(httpResp) + return resp, err +} + +// updatePoolCreateRequest creates the UpdatePool request. +func (client *Client) updatePoolCreateRequest(ctx context.Context, poolID string, pool UpdatePoolContent, options *UpdatePoolOptions) (*policy.Request, error) { + host := "{endpoint}" + host = strings.ReplaceAll(host, "{endpoint}", client.endpoint) + urlPath := "/pools/{poolId}" + if poolID == "" { + return nil, errors.New("parameter poolID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{poolId}", url.PathEscape(poolID)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2024-07-01.20.0") + if options != nil && options.Timeout != nil { + reqQP.Set("timeOut", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.IfMatch != nil { + req.Raw().Header["If-Match"] = []string{*options.IfMatch} + } + if options != nil && options.IfModifiedSince != nil { + req.Raw().Header["If-Modified-Since"] = []string{options.IfModifiedSince.Format(time.RFC1123)} + } + if options != nil && options.IfNoneMatch != nil { + req.Raw().Header["If-None-Match"] = []string{*options.IfNoneMatch} + } + if options != nil && options.IfUnmodifiedSince != nil { + req.Raw().Header["If-Unmodified-Since"] = []string{options.IfUnmodifiedSince.Format(time.RFC1123)} + } + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.Ocpdate != nil { + req.Raw().Header["ocp-date"] = []string{options.Ocpdate.Format(time.RFC1123)} + } + if options != nil && options.ReturnClientRequestID != nil { + req.Raw().Header["return-client-request-id"] = []string{strconv.FormatBool(*options.ReturnClientRequestID)} + } + req.Raw().Header["Content-Type"] = []string{"application/json; odata=minimalmetadata"} + if err := runtime.MarshalAsJSON(req, pool); err != nil { + return nil, err + } + return req, nil +} + +// updatePoolHandleResponse handles the UpdatePool response. +func (client *Client) updatePoolHandleResponse(resp *http.Response) (UpdatePoolResponse, error) { + result := UpdatePoolResponse{} + if val := resp.Header.Get("client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("DataServiceId"); val != "" { + result.DataServiceID = &val + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = &val + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return UpdatePoolResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("request-id"); val != "" { + result.RequestID = &val + } + return result, nil +} + +// UploadNodeLogs - Upload Azure Batch service log files from the specified Compute Node to Azure +// Blob Storage. +// +// This is for gathering Azure Batch service log files in an automated fashion +// from Compute Nodes if you are experiencing an error and wish to escalate to +// Azure support. The Azure Batch service log files should be shared with Azure +// support to aid in debugging issues with the Batch service. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-07-01.20.0 +// - poolID - The ID of the Pool that contains the Compute Node. +// - nodeID - The ID of the Compute Node for which you want to get the Remote Desktop +// Protocol file. +// - content - The Azure Batch service log files upload options. +// - options - UploadNodeLogsOptions contains the optional parameters for the Client.UploadNodeLogs method. +func (client *Client) UploadNodeLogs(ctx context.Context, poolID string, nodeID string, content UploadNodeLogsContent, options *UploadNodeLogsOptions) (UploadNodeLogsResponse, error) { + var err error + ctx, endSpan := runtime.StartSpan(ctx, "Client.UploadNodeLogs", client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.uploadNodeLogsCreateRequest(ctx, poolID, nodeID, content, options) + if err != nil { + return UploadNodeLogsResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return UploadNodeLogsResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return UploadNodeLogsResponse{}, err + } + resp, err := client.uploadNodeLogsHandleResponse(httpResp) + return resp, err +} + +// uploadNodeLogsCreateRequest creates the UploadNodeLogs request. +func (client *Client) uploadNodeLogsCreateRequest(ctx context.Context, poolID string, nodeID string, content UploadNodeLogsContent, options *UploadNodeLogsOptions) (*policy.Request, error) { + host := "{endpoint}" + host = strings.ReplaceAll(host, "{endpoint}", client.endpoint) + urlPath := "/pools/{poolId}/nodes/{nodeId}/uploadbatchservicelogs" + if poolID == "" { + return nil, errors.New("parameter poolID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{poolId}", url.PathEscape(poolID)) + if nodeID == "" { + return nil, errors.New("parameter nodeID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{nodeId}", url.PathEscape(nodeID)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2024-07-01.20.0") + if options != nil && options.Timeout != nil { + reqQP.Set("timeOut", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.Ocpdate != nil { + req.Raw().Header["ocp-date"] = []string{options.Ocpdate.Format(time.RFC1123)} + } + if options != nil && options.ReturnClientRequestID != nil { + req.Raw().Header["return-client-request-id"] = []string{strconv.FormatBool(*options.ReturnClientRequestID)} + } + req.Raw().Header["Content-Type"] = []string{"application/json; odata=minimalmetadata"} + if err := runtime.MarshalAsJSON(req, content); err != nil { + return nil, err + } + return req, nil +} + +// uploadNodeLogsHandleResponse handles the UploadNodeLogs response. +func (client *Client) uploadNodeLogsHandleResponse(resp *http.Response) (UploadNodeLogsResponse, error) { + result := UploadNodeLogsResponse{} + if val := resp.Header.Get("client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = &val + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return UploadNodeLogsResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("request-id"); val != "" { + result.RequestID = &val + } + if err := runtime.UnmarshalAsJSON(resp, &result.UploadNodeLogsResult); err != nil { + return UploadNodeLogsResponse{}, err + } + return result, nil +} + +// newListPoolUsageMetricsPager - Lists the usage metrics, aggregated by Pool across individual time intervals, +// for the specified Account. +// +// If you do not specify a $filter clause including a poolId, the response +// includes all Pools that existed in the Account in the time range of the +// returned aggregation intervals. If you do not specify a $filter clause +// including a startTime or endTime these filters default to the start and end +// times of the last aggregation interval currently available; that is, only the +// last aggregation interval is returned. +// +// Generated from API version 2024-07-01.20.0 +// - options - listPoolUsageMetricsOptions contains the optional parameters for the Client.NewlistPoolUsageMetricsPager method. +func (client *Client) newListPoolUsageMetricsPager(options *listPoolUsageMetricsOptions) *runtime.Pager[listPoolUsageMetricsResponse] { + return runtime.NewPager(runtime.PagingHandler[listPoolUsageMetricsResponse]{ + More: func(page listPoolUsageMetricsResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *listPoolUsageMetricsResponse) (listPoolUsageMetricsResponse, error) { + 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.listPoolUsageMetricsCreateRequest(ctx, options) + }, nil) + if err != nil { + return listPoolUsageMetricsResponse{}, err + } + return client.listPoolUsageMetricsHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listPoolUsageMetricsCreateRequest creates the listPoolUsageMetrics request. +func (client *Client) listPoolUsageMetricsCreateRequest(ctx context.Context, options *listPoolUsageMetricsOptions) (*policy.Request, error) { + host := "{endpoint}" + host = strings.ReplaceAll(host, "{endpoint}", client.endpoint) + urlPath := "/poolusagemetrics" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Filter != nil { + reqQP.Set("$filter", *options.Filter) + } + reqQP.Set("api-version", "2024-07-01.20.0") + if options != nil && options.Endtime != nil { + reqQP.Set("endtime", options.Endtime.Format(time.RFC3339Nano)) + } + if options != nil && options.MaxResults != nil { + reqQP.Set("maxresults", strconv.FormatInt(int64(*options.MaxResults), 10)) + } + if options != nil && options.Starttime != nil { + reqQP.Set("startTime", options.Starttime.Format(time.RFC3339Nano)) + } + if options != nil && options.Timeout != nil { + reqQP.Set("timeOut", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.Ocpdate != nil { + req.Raw().Header["ocp-date"] = []string{options.Ocpdate.Format(time.RFC1123)} + } + if options != nil && options.ReturnClientRequestID != nil { + req.Raw().Header["return-client-request-id"] = []string{strconv.FormatBool(*options.ReturnClientRequestID)} + } + return req, nil +} + +// listPoolUsageMetricsHandleResponse handles the listPoolUsageMetrics response. +func (client *Client) listPoolUsageMetricsHandleResponse(resp *http.Response) (listPoolUsageMetricsResponse, error) { + result := listPoolUsageMetricsResponse{} + if val := resp.Header.Get("client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = &val + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return listPoolUsageMetricsResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("request-id"); val != "" { + result.RequestID = &val + } + if err := runtime.UnmarshalAsJSON(resp, &result.listPoolUsageMetricsResult); err != nil { + return listPoolUsageMetricsResponse{}, err + } + return result, nil +} diff --git a/sdk/batch/azbatch/constants.go b/sdk/batch/azbatch/constants.go new file mode 100644 index 000000000000..6828956410a2 --- /dev/null +++ b/sdk/batch/azbatch/constants.go @@ -0,0 +1,1241 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package azbatch + +// AccessScope - AccessScope enums +type AccessScope string + +const ( + // AccessScopeJob - Grants access to perform all operations on the Job containing the Task. + AccessScopeJob AccessScope = "job" +) + +// PossibleAccessScopeValues returns the possible values for the AccessScope const type. +func PossibleAccessScopeValues() []AccessScope { + return []AccessScope{ + AccessScopeJob, + } +} + +// AllocationState - AllocationState enums +type AllocationState string + +const ( + // AllocationStateResizing - The Pool is resizing; that is, Compute Nodes are being added to or removed from the Pool. + AllocationStateResizing AllocationState = "resizing" + // AllocationStateSteady - The Pool is not resizing. There are no changes to the number of Compute Nodes in the Pool in progress. + // A Pool enters this state when it is created and when no operations are being performed on the Pool to change the number + // of Compute Nodes. + AllocationStateSteady AllocationState = "steady" + // AllocationStateStopping - The Pool was resizing, but the user has requested that the resize be stopped, but the stop request + // has not yet been completed. + AllocationStateStopping AllocationState = "stopping" +) + +// PossibleAllocationStateValues returns the possible values for the AllocationState const type. +func PossibleAllocationStateValues() []AllocationState { + return []AllocationState{ + AllocationStateResizing, + AllocationStateSteady, + AllocationStateStopping, + } +} + +// AutoUserScope - AutoUserScope enums +type AutoUserScope string + +const ( + // AutoUserScopePool - Specifies that the Task runs as the common auto user Account which is created on every Compute Node + // in a Pool. + AutoUserScopePool AutoUserScope = "pool" + // AutoUserScopeTask - Specifies that the service should create a new user for the Task. + AutoUserScopeTask AutoUserScope = "task" +) + +// PossibleAutoUserScopeValues returns the possible values for the AutoUserScope const type. +func PossibleAutoUserScopeValues() []AutoUserScope { + return []AutoUserScope{ + AutoUserScopePool, + AutoUserScopeTask, + } +} + +// CachingType - CachingType enums +type CachingType string + +const ( + // CachingTypeNone - The caching mode for the disk is not enabled. + CachingTypeNone CachingType = "none" + // CachingTypeReadOnly - The caching mode for the disk is read only. + CachingTypeReadOnly CachingType = "readonly" + // CachingTypeReadWrite - The caching mode for the disk is read and write. + CachingTypeReadWrite CachingType = "readwrite" +) + +// PossibleCachingTypeValues returns the possible values for the CachingType const type. +func PossibleCachingTypeValues() []CachingType { + return []CachingType{ + CachingTypeNone, + CachingTypeReadOnly, + CachingTypeReadWrite, + } +} + +// CertificateFormat - BatchCertificateFormat enums +type CertificateFormat string + +const ( + // CertificateFormatCER - The Certificate is a base64-encoded X.509 Certificate. + CertificateFormatCER CertificateFormat = "cer" + // CertificateFormatPFX - The Certificate is a PFX (PKCS#12) formatted Certificate or Certificate chain. + CertificateFormatPFX CertificateFormat = "pfx" +) + +// PossibleCertificateFormatValues returns the possible values for the CertificateFormat const type. +func PossibleCertificateFormatValues() []CertificateFormat { + return []CertificateFormat{ + CertificateFormatCER, + CertificateFormatPFX, + } +} + +// CertificateState - BatchCertificateState enums +type CertificateState string + +const ( + // CertificateStateActive - The Certificate is available for use in Pools. + CertificateStateActive CertificateState = "active" + // CertificateStateDeleteFailed - The user requested that the Certificate be deleted, but there are Pools that still have + // references to the Certificate, or it is still installed on one or more Nodes. (The latter can occur if the Certificate + // has been removed from the Pool, but the Compute Node has not yet restarted. Compute Nodes refresh their Certificates only + // when they restart.) You may use the cancel Certificate delete operation to cancel the delete, or the delete Certificate + // operation to retry the delete. + CertificateStateDeleteFailed CertificateState = "deletefailed" + // CertificateStateDeleting - The user has requested that the Certificate be deleted, but the delete operation has not yet + // completed. You may not reference the Certificate when creating or updating Pools. + CertificateStateDeleting CertificateState = "deleting" +) + +// PossibleCertificateStateValues returns the possible values for the CertificateState const type. +func PossibleCertificateStateValues() []CertificateState { + return []CertificateState{ + CertificateStateActive, + CertificateStateDeleteFailed, + CertificateStateDeleting, + } +} + +// CertificateStoreLocation - BatchCertificateStoreLocation enums +type CertificateStoreLocation string + +const ( + // CertificateStoreLocationCurrentUser - Certificates should be installed to the CurrentUser Certificate store. + CertificateStoreLocationCurrentUser CertificateStoreLocation = "currentuser" + // CertificateStoreLocationLocalMachine - Certificates should be installed to the LocalMachine Certificate store. + CertificateStoreLocationLocalMachine CertificateStoreLocation = "localmachine" +) + +// PossibleCertificateStoreLocationValues returns the possible values for the CertificateStoreLocation const type. +func PossibleCertificateStoreLocationValues() []CertificateStoreLocation { + return []CertificateStoreLocation{ + CertificateStoreLocationCurrentUser, + CertificateStoreLocationLocalMachine, + } +} + +// CertificateVisibility - BatchCertificateVisibility enums +type CertificateVisibility string + +const ( + // CertificateVisibilityRemoteUser - The Certificate should be visible to the user accounts under which users remotely access + // the Compute Node. + CertificateVisibilityRemoteUser CertificateVisibility = "remoteuser" + // CertificateVisibilityStartTask - The Certificate should be visible to the user account under which the StartTask is run. + // Note that if AutoUser Scope is Pool for both the StartTask and a Task, this certificate will be visible to the Task as + // well. + CertificateVisibilityStartTask CertificateVisibility = "starttask" + // CertificateVisibilityTask - The Certificate should be visible to the user accounts under which Job Tasks are run. + CertificateVisibilityTask CertificateVisibility = "task" +) + +// PossibleCertificateVisibilityValues returns the possible values for the CertificateVisibility const type. +func PossibleCertificateVisibilityValues() []CertificateVisibility { + return []CertificateVisibility{ + CertificateVisibilityRemoteUser, + CertificateVisibilityStartTask, + CertificateVisibilityTask, + } +} + +// ContainerHostDataPath - The paths which will be mounted to container task's container. +type ContainerHostDataPath string + +const ( + // ContainerHostDataPathApplications - The applications path. + ContainerHostDataPathApplications ContainerHostDataPath = "Applications" + // ContainerHostDataPathJobPrep - The job-prep task path. + ContainerHostDataPathJobPrep ContainerHostDataPath = "JobPrep" + // ContainerHostDataPathShared - The path for multi-instances task to shared their files. + ContainerHostDataPathShared ContainerHostDataPath = "Shared" + // ContainerHostDataPathStartup - The path for start task. + ContainerHostDataPathStartup ContainerHostDataPath = "Startup" + // ContainerHostDataPathTask - The task path. + ContainerHostDataPathTask ContainerHostDataPath = "Task" + // ContainerHostDataPathVfsMounts - The path contains all virtual file systems are mounted on this node. + ContainerHostDataPathVfsMounts ContainerHostDataPath = "VfsMounts" +) + +// PossibleContainerHostDataPathValues returns the possible values for the ContainerHostDataPath const type. +func PossibleContainerHostDataPathValues() []ContainerHostDataPath { + return []ContainerHostDataPath{ + ContainerHostDataPathApplications, + ContainerHostDataPathJobPrep, + ContainerHostDataPathShared, + ContainerHostDataPathStartup, + ContainerHostDataPathTask, + ContainerHostDataPathVfsMounts, + } +} + +// ContainerType - ContainerType enums +type ContainerType string + +const ( + // ContainerTypeCriCompatible - A CRI based technology will be used to launch the containers. + ContainerTypeCriCompatible ContainerType = "criCompatible" + // ContainerTypeDockerCompatible - A Docker compatible container technology will be used to launch the containers. + ContainerTypeDockerCompatible ContainerType = "dockerCompatible" +) + +// PossibleContainerTypeValues returns the possible values for the ContainerType const type. +func PossibleContainerTypeValues() []ContainerType { + return []ContainerType{ + ContainerTypeCriCompatible, + ContainerTypeDockerCompatible, + } +} + +// ContainerWorkingDirectory - ContainerWorkingDirectory enums +type ContainerWorkingDirectory string + +const ( + // ContainerWorkingDirectoryContainerImageDefault - Use the working directory defined in the container Image. Beware that + // this directory will not contain the Resource Files downloaded by Batch. + ContainerWorkingDirectoryContainerImageDefault ContainerWorkingDirectory = "containerImageDefault" + // ContainerWorkingDirectoryTaskWorkingDirectory - Use the standard Batch service Task working directory, which will contain + // the Task Resource Files populated by Batch. + ContainerWorkingDirectoryTaskWorkingDirectory ContainerWorkingDirectory = "taskWorkingDirectory" +) + +// PossibleContainerWorkingDirectoryValues returns the possible values for the ContainerWorkingDirectory const type. +func PossibleContainerWorkingDirectoryValues() []ContainerWorkingDirectory { + return []ContainerWorkingDirectory{ + ContainerWorkingDirectoryContainerImageDefault, + ContainerWorkingDirectoryTaskWorkingDirectory, + } +} + +// DependencyAction - DependencyAction enums +type DependencyAction string + +const ( + // DependencyActionBlock - Blocks tasks waiting on this task, preventing them from being scheduled. + DependencyActionBlock DependencyAction = "block" + // DependencyActionSatisfy - Satisfy tasks waiting on this task; once all dependencies are satisfied, the task will be scheduled + // to run. + DependencyActionSatisfy DependencyAction = "satisfy" +) + +// PossibleDependencyActionValues returns the possible values for the DependencyAction const type. +func PossibleDependencyActionValues() []DependencyAction { + return []DependencyAction{ + DependencyActionBlock, + DependencyActionSatisfy, + } +} + +// DiffDiskPlacement - Specifies the ephemeral disk placement for operating system disk for all compute nodes (VMs) in the +// pool. This property can be used by user in the request to choose which location the operating system should be in. e.g., +// cache disk space for Ephemeral OS disk provisioning. For more information on Ephemeral OS disk size requirements, please +// refer to Ephemeral OS disk size requirements for Windows VMs at https://learn.microsoft.com/azure/virtual-machines/windows/ephemeral-os-disks#size-requirements +// and Linux VMs at https://learn.microsoft.com/azure/virtual-machines/linux/ephemeral-os-disks#size-requirements +type DiffDiskPlacement string + +const ( + // DiffDiskPlacementCacheDisk - The Ephemeral OS Disk is stored on the VM cache. + DiffDiskPlacementCacheDisk DiffDiskPlacement = "cachedisk" +) + +// PossibleDiffDiskPlacementValues returns the possible values for the DiffDiskPlacement const type. +func PossibleDiffDiskPlacementValues() []DiffDiskPlacement { + return []DiffDiskPlacement{ + DiffDiskPlacementCacheDisk, + } +} + +// DisableJobOption - DisableBatchJobOption enums +type DisableJobOption string + +const ( + // DisableJobOptionRequeue - Terminate running Tasks and requeue them. The Tasks will run again when the Job is enabled. + DisableJobOptionRequeue DisableJobOption = "requeue" + // DisableJobOptionTerminate - Terminate running Tasks. The Tasks will be completed with failureInfo indicating that they + // were terminated, and will not run again. + DisableJobOptionTerminate DisableJobOption = "terminate" + // DisableJobOptionWait - Allow currently running Tasks to complete. + DisableJobOptionWait DisableJobOption = "wait" +) + +// PossibleDisableJobOptionValues returns the possible values for the DisableJobOption const type. +func PossibleDisableJobOptionValues() []DisableJobOption { + return []DisableJobOption{ + DisableJobOptionRequeue, + DisableJobOptionTerminate, + DisableJobOptionWait, + } +} + +// DiskEncryptionTarget - DiskEncryptionTarget enums +type DiskEncryptionTarget string + +const ( + // DiskEncryptionTargetOsDisk - The OS Disk on the compute node is encrypted. + DiskEncryptionTargetOsDisk DiskEncryptionTarget = "osdisk" + // DiskEncryptionTargetTemporaryDisk - The temporary disk on the compute node is encrypted. On Linux this encryption applies + // to other partitions (such as those on mounted data disks) when encryption occurs at boot time. + DiskEncryptionTargetTemporaryDisk DiskEncryptionTarget = "temporarydisk" +) + +// PossibleDiskEncryptionTargetValues returns the possible values for the DiskEncryptionTarget const type. +func PossibleDiskEncryptionTargetValues() []DiskEncryptionTarget { + return []DiskEncryptionTarget{ + DiskEncryptionTargetOsDisk, + DiskEncryptionTargetTemporaryDisk, + } +} + +// DynamicVNetAssignmentScope - DynamicVNetAssignmentScope enums +type DynamicVNetAssignmentScope string + +const ( + // DynamicVNetAssignmentScopeJob - Dynamic VNet assignment is done per-job. + DynamicVNetAssignmentScopeJob DynamicVNetAssignmentScope = "job" + // DynamicVNetAssignmentScopeNone - No dynamic VNet assignment is enabled. + DynamicVNetAssignmentScopeNone DynamicVNetAssignmentScope = "none" +) + +// PossibleDynamicVNetAssignmentScopeValues returns the possible values for the DynamicVNetAssignmentScope const type. +func PossibleDynamicVNetAssignmentScopeValues() []DynamicVNetAssignmentScope { + return []DynamicVNetAssignmentScope{ + DynamicVNetAssignmentScopeJob, + DynamicVNetAssignmentScopeNone, + } +} + +// ElevationLevel - ElevationLevel enums +type ElevationLevel string + +const ( + // ElevationLevelAdmin - The user is a user with elevated access and operates with full Administrator permissions. + ElevationLevelAdmin ElevationLevel = "admin" + // ElevationLevelNonAdmin - The user is a standard user without elevated access. + ElevationLevelNonAdmin ElevationLevel = "nonadmin" +) + +// PossibleElevationLevelValues returns the possible values for the ElevationLevel const type. +func PossibleElevationLevelValues() []ElevationLevel { + return []ElevationLevel{ + ElevationLevelAdmin, + ElevationLevelNonAdmin, + } +} + +// ErrorCategory - ErrorCategory enums +type ErrorCategory string + +const ( + // ErrorCategoryServerError - The error is due to an internal server issue. + ErrorCategoryServerError ErrorCategory = "servererror" + // ErrorCategoryUserError - The error is due to a user issue, such as misconfiguration. + ErrorCategoryUserError ErrorCategory = "usererror" +) + +// PossibleErrorCategoryValues returns the possible values for the ErrorCategory const type. +func PossibleErrorCategoryValues() []ErrorCategory { + return []ErrorCategory{ + ErrorCategoryServerError, + ErrorCategoryUserError, + } +} + +// IPAddressProvisioningType - IPAddressProvisioningType enums +type IPAddressProvisioningType string + +const ( + // IPAddressProvisioningTypeBatchManaged - A public IP will be created and managed by Batch. There may be multiple public + // IPs depending on the size of the Pool. + IPAddressProvisioningTypeBatchManaged IPAddressProvisioningType = "batchmanaged" + // IPAddressProvisioningTypeNoPublicIPAddresses - No public IP Address will be created. + IPAddressProvisioningTypeNoPublicIPAddresses IPAddressProvisioningType = "nopublicipaddresses" + // IPAddressProvisioningTypeUserManaged - Public IPs are provided by the user and will be used to provision the Compute Nodes. + IPAddressProvisioningTypeUserManaged IPAddressProvisioningType = "usermanaged" +) + +// PossibleIPAddressProvisioningTypeValues returns the possible values for the IPAddressProvisioningType const type. +func PossibleIPAddressProvisioningTypeValues() []IPAddressProvisioningType { + return []IPAddressProvisioningType{ + IPAddressProvisioningTypeBatchManaged, + IPAddressProvisioningTypeNoPublicIPAddresses, + IPAddressProvisioningTypeUserManaged, + } +} + +// ImageVerificationType - ImageVerificationType enums +type ImageVerificationType string + +const ( + // ImageVerificationTypeUnverified - The associated Compute Node agent SKU should have binary compatibility with the Image, + // but specific functionality has not been verified. + ImageVerificationTypeUnverified ImageVerificationType = "unverified" + // ImageVerificationTypeVerified - The Image is guaranteed to be compatible with the associated Compute Node agent SKU and + // all Batch features have been confirmed to work as expected. + ImageVerificationTypeVerified ImageVerificationType = "verified" +) + +// PossibleImageVerificationTypeValues returns the possible values for the ImageVerificationType const type. +func PossibleImageVerificationTypeValues() []ImageVerificationType { + return []ImageVerificationType{ + ImageVerificationTypeUnverified, + ImageVerificationTypeVerified, + } +} + +// InboundEndpointProtocol - InboundEndpointProtocol enums +type InboundEndpointProtocol string + +const ( + // InboundEndpointProtocolTCP - Use TCP for the endpoint. + InboundEndpointProtocolTCP InboundEndpointProtocol = "tcp" + // InboundEndpointProtocolUDP - Use UDP for the endpoint. + InboundEndpointProtocolUDP InboundEndpointProtocol = "udp" +) + +// PossibleInboundEndpointProtocolValues returns the possible values for the InboundEndpointProtocol const type. +func PossibleInboundEndpointProtocolValues() []InboundEndpointProtocol { + return []InboundEndpointProtocol{ + InboundEndpointProtocolTCP, + InboundEndpointProtocolUDP, + } +} + +// JobAction - BatchJobAction enums +type JobAction string + +const ( + // JobActionDisable - Disable the Job. This is equivalent to calling the disable Job API, with a disableTasks value of requeue. + JobActionDisable JobAction = "disable" + // JobActionNone - Take no action. + JobActionNone JobAction = "none" + // JobActionTerminate - Terminate the Job. The terminationReason in the Job's executionInfo is set to "TaskFailed". + JobActionTerminate JobAction = "terminate" +) + +// PossibleJobActionValues returns the possible values for the JobAction const type. +func PossibleJobActionValues() []JobAction { + return []JobAction{ + JobActionDisable, + JobActionNone, + JobActionTerminate, + } +} + +// JobPreparationTaskState - BatchJobPreparationTaskState enums +type JobPreparationTaskState string + +const ( + // JobPreparationTaskStateCompleted - The Task has exited with exit code 0, or the Task has exhausted its retry limit, or + // the Batch service was unable to start the Task due to Task preparation errors (such as resource file download failures). + JobPreparationTaskStateCompleted JobPreparationTaskState = "completed" + // JobPreparationTaskStateRunning - The Task is currently running (including retrying). + JobPreparationTaskStateRunning JobPreparationTaskState = "running" +) + +// PossibleJobPreparationTaskStateValues returns the possible values for the JobPreparationTaskState const type. +func PossibleJobPreparationTaskStateValues() []JobPreparationTaskState { + return []JobPreparationTaskState{ + JobPreparationTaskStateCompleted, + JobPreparationTaskStateRunning, + } +} + +// JobReleaseTaskState - BatchJobReleaseTaskState enums +type JobReleaseTaskState string + +const ( + // JobReleaseTaskStateCompleted - The Task has exited with exit code 0, or the Task has exhausted its retry limit, or the + // Batch service was unable to start the Task due to Task preparation errors (such as resource file download failures). + JobReleaseTaskStateCompleted JobReleaseTaskState = "completed" + // JobReleaseTaskStateRunning - The Task is currently running (including retrying). + JobReleaseTaskStateRunning JobReleaseTaskState = "running" +) + +// PossibleJobReleaseTaskStateValues returns the possible values for the JobReleaseTaskState const type. +func PossibleJobReleaseTaskStateValues() []JobReleaseTaskState { + return []JobReleaseTaskState{ + JobReleaseTaskStateCompleted, + JobReleaseTaskStateRunning, + } +} + +// JobScheduleState - BatchJobScheduleState enums +type JobScheduleState string + +const ( + // JobScheduleStateActive - The Job Schedule is active and will create Jobs as per its schedule. + JobScheduleStateActive JobScheduleState = "active" + // JobScheduleStateCompleted - The Job Schedule has terminated, either by reaching its end time or by the user terminating + // it explicitly. + JobScheduleStateCompleted JobScheduleState = "completed" + // JobScheduleStateDeleting - The user has requested that the Job Schedule be deleted, but the delete operation is still in + // progress. The scheduler will not initiate any new Jobs for this Job Schedule, and will delete any existing Jobs and Tasks + // under the Job Schedule, including any active Job. The Job Schedule will be deleted when all Jobs and Tasks under the Job + // Schedule have been deleted. + JobScheduleStateDeleting JobScheduleState = "deleting" + // JobScheduleStateDisabled - The user has disabled the Job Schedule. The scheduler will not initiate any new Jobs will on + // this schedule, but any existing active Job will continue to run. + JobScheduleStateDisabled JobScheduleState = "disabled" + // JobScheduleStateTerminating - The Job Schedule has no more work to do, or has been explicitly terminated by the user, but + // the termination operation is still in progress. The scheduler will not initiate any new Jobs for this Job Schedule, nor + // is any existing Job active. + JobScheduleStateTerminating JobScheduleState = "terminating" +) + +// PossibleJobScheduleStateValues returns the possible values for the JobScheduleState const type. +func PossibleJobScheduleStateValues() []JobScheduleState { + return []JobScheduleState{ + JobScheduleStateActive, + JobScheduleStateCompleted, + JobScheduleStateDeleting, + JobScheduleStateDisabled, + JobScheduleStateTerminating, + } +} + +// JobState - BatchJobState enums +type JobState string + +const ( + // JobStateActive - The Job is available to have Tasks scheduled. + JobStateActive JobState = "active" + // JobStateCompleted - All Tasks have terminated, and the system will not accept any more Tasks or any further changes to + // the Job. + JobStateCompleted JobState = "completed" + // JobStateDeleting - A user has requested that the Job be deleted, but the delete operation is still in progress (for example, + // because the system is still terminating running Tasks). + JobStateDeleting JobState = "deleting" + // JobStateDisabled - A user has disabled the Job. No Tasks are running, and no new Tasks will be scheduled. + JobStateDisabled JobState = "disabled" + // JobStateDisabling - A user has requested that the Job be disabled, but the disable operation is still in progress (for + // example, waiting for Tasks to terminate). + JobStateDisabling JobState = "disabling" + // JobStateEnabling - A user has requested that the Job be enabled, but the enable operation is still in progress. + JobStateEnabling JobState = "enabling" + // JobStateTerminating - The Job is about to complete, either because a Job Manager Task has completed or because the user + // has terminated the Job, but the terminate operation is still in progress (for example, because Job Release Tasks are running). + JobStateTerminating JobState = "terminating" +) + +// PossibleJobStateValues returns the possible values for the JobState const type. +func PossibleJobStateValues() []JobState { + return []JobState{ + JobStateActive, + JobStateCompleted, + JobStateDeleting, + JobStateDisabled, + JobStateDisabling, + JobStateEnabling, + JobStateTerminating, + } +} + +// LoginMode - LoginMode enums +type LoginMode string + +const ( + // LoginModeBatch - The LOGON32_LOGON_BATCH Win32 login mode. The batch login mode is recommended for long running parallel + // processes. + LoginModeBatch LoginMode = "batch" + // LoginModeInteractive - The LOGON32_LOGON_INTERACTIVE Win32 login mode. UAC is enabled on Windows VirtualMachineConfiguration + // Pools. If this option is used with an elevated user identity in a Windows VirtualMachineConfiguration Pool, the user session + // will not be elevated unless the application executed by the Task command line is configured to always require administrative + // privilege or to always require maximum privilege. + LoginModeInteractive LoginMode = "interactive" +) + +// PossibleLoginModeValues returns the possible values for the LoginMode const type. +func PossibleLoginModeValues() []LoginMode { + return []LoginMode{ + LoginModeBatch, + LoginModeInteractive, + } +} + +// NetworkSecurityGroupRuleAccess - NetworkSecurityGroupRuleAccess enums +type NetworkSecurityGroupRuleAccess string + +const ( + // NetworkSecurityGroupRuleAccessAllow - Allow access. + NetworkSecurityGroupRuleAccessAllow NetworkSecurityGroupRuleAccess = "allow" + // NetworkSecurityGroupRuleAccessDeny - Deny access. + NetworkSecurityGroupRuleAccessDeny NetworkSecurityGroupRuleAccess = "deny" +) + +// PossibleNetworkSecurityGroupRuleAccessValues returns the possible values for the NetworkSecurityGroupRuleAccess const type. +func PossibleNetworkSecurityGroupRuleAccessValues() []NetworkSecurityGroupRuleAccess { + return []NetworkSecurityGroupRuleAccess{ + NetworkSecurityGroupRuleAccessAllow, + NetworkSecurityGroupRuleAccessDeny, + } +} + +// NodeCommunicationMode - BatchNodeCommunicationMode enums +type NodeCommunicationMode string + +const ( + // NodeCommunicationModeClassic - Nodes using the classic communication mode require inbound TCP communication on ports 29876 + // and 29877 from the "BatchNodeManagement.{region}" service tag and outbound TCP communication on port 443 to the "Storage.region" + // and "BatchNodeManagement.{region}" service tags. + NodeCommunicationModeClassic NodeCommunicationMode = "classic" + // NodeCommunicationModeDefault - The node communication mode is automatically set by the Batch service. + NodeCommunicationModeDefault NodeCommunicationMode = "default" + // NodeCommunicationModeSimplified - Nodes using the simplified communication mode require outbound TCP communication on port + // 443 to the "BatchNodeManagement.{region}" service tag. No open inbound ports are required. + NodeCommunicationModeSimplified NodeCommunicationMode = "simplified" +) + +// PossibleNodeCommunicationModeValues returns the possible values for the NodeCommunicationMode const type. +func PossibleNodeCommunicationModeValues() []NodeCommunicationMode { + return []NodeCommunicationMode{ + NodeCommunicationModeClassic, + NodeCommunicationModeDefault, + NodeCommunicationModeSimplified, + } +} + +// NodeDeallocateOption - BatchNodeDeallocateOption enums +type NodeDeallocateOption string + +const ( + // NodeDeallocateOptionRequeue - Terminate running Task processes and requeue the Tasks. The Tasks will run again when a Compute + // Node is available. Deallocate the Compute Node as soon as Tasks have been terminated. + NodeDeallocateOptionRequeue NodeDeallocateOption = "requeue" + // NodeDeallocateOptionRetainedData - Allow currently running Tasks to complete, then wait for all Task data retention periods + // to expire. Schedule no new Tasks while waiting. Deallocate the Compute Node when all Task retention periods have expired. + NodeDeallocateOptionRetainedData NodeDeallocateOption = "retaineddata" + // NodeDeallocateOptionTaskCompletion - Allow currently running Tasks to complete. Schedule no new Tasks while waiting. Deallocate + // the Compute Node when all Tasks have completed. + NodeDeallocateOptionTaskCompletion NodeDeallocateOption = "taskcompletion" + // NodeDeallocateOptionTerminate - Terminate running Tasks. The Tasks will be completed with failureInfo indicating that they + // were terminated, and will not run again. Deallocate the Compute Node as soon as Tasks have been terminated. + NodeDeallocateOptionTerminate NodeDeallocateOption = "terminate" +) + +// PossibleNodeDeallocateOptionValues returns the possible values for the NodeDeallocateOption const type. +func PossibleNodeDeallocateOptionValues() []NodeDeallocateOption { + return []NodeDeallocateOption{ + NodeDeallocateOptionRequeue, + NodeDeallocateOptionRetainedData, + NodeDeallocateOptionTaskCompletion, + NodeDeallocateOptionTerminate, + } +} + +// NodeDeallocationOption - BatchNodeDeallocationOption enums +type NodeDeallocationOption string + +const ( + // NodeDeallocationOptionRequeue - Terminate running Task processes and requeue the Tasks. The Tasks will run again when a + // Compute Node is available. Remove Compute Nodes as soon as Tasks have been terminated. + NodeDeallocationOptionRequeue NodeDeallocationOption = "requeue" + // NodeDeallocationOptionRetainedData - Allow currently running Tasks to complete, then wait for all Task data retention periods + // to expire. Schedule no new Tasks while waiting. Remove Compute Nodes when all Task retention periods have expired. + NodeDeallocationOptionRetainedData NodeDeallocationOption = "retaineddata" + // NodeDeallocationOptionTaskCompletion - Allow currently running Tasks to complete. Schedule no new Tasks while waiting. + // Remove Compute Nodes when all Tasks have completed. + NodeDeallocationOptionTaskCompletion NodeDeallocationOption = "taskcompletion" + // NodeDeallocationOptionTerminate - Terminate running Tasks. The Tasks will be completed with failureInfo indicating that + // they were terminated, and will not run again. Remove Compute Nodes as soon as Tasks have been terminated. + NodeDeallocationOptionTerminate NodeDeallocationOption = "terminate" +) + +// PossibleNodeDeallocationOptionValues returns the possible values for the NodeDeallocationOption const type. +func PossibleNodeDeallocationOptionValues() []NodeDeallocationOption { + return []NodeDeallocationOption{ + NodeDeallocationOptionRequeue, + NodeDeallocationOptionRetainedData, + NodeDeallocationOptionTaskCompletion, + NodeDeallocationOptionTerminate, + } +} + +// NodeDisableSchedulingOption - BatchNodeDisableSchedulingOption enums +type NodeDisableSchedulingOption string + +const ( + // NodeDisableSchedulingOptionRequeue - Terminate running Task processes and requeue the Tasks. The Tasks may run again on + // other Compute Nodes, or when Task scheduling is re-enabled on this Compute Node. Enter offline state as soon as Tasks have + // been terminated. + NodeDisableSchedulingOptionRequeue NodeDisableSchedulingOption = "requeue" + // NodeDisableSchedulingOptionTaskCompletion - Allow currently running Tasks to complete. Schedule no new Tasks while waiting. + // Enter offline state when all Tasks have completed. + NodeDisableSchedulingOptionTaskCompletion NodeDisableSchedulingOption = "taskcompletion" + // NodeDisableSchedulingOptionTerminate - Terminate running Tasks. The Tasks will be completed with failureInfo indicating + // that they were terminated, and will not run again. Enter offline state as soon as Tasks have been terminated. + NodeDisableSchedulingOptionTerminate NodeDisableSchedulingOption = "terminate" +) + +// PossibleNodeDisableSchedulingOptionValues returns the possible values for the NodeDisableSchedulingOption const type. +func PossibleNodeDisableSchedulingOptionValues() []NodeDisableSchedulingOption { + return []NodeDisableSchedulingOption{ + NodeDisableSchedulingOptionRequeue, + NodeDisableSchedulingOptionTaskCompletion, + NodeDisableSchedulingOptionTerminate, + } +} + +// NodeFillType - BatchNodeFillType enums +type NodeFillType string + +const ( + // NodeFillTypePack - As many Tasks as possible (taskSlotsPerNode) should be assigned to each Compute Node in the Pool before + // any Tasks are assigned to the next Compute Node in the Pool. + NodeFillTypePack NodeFillType = "pack" + // NodeFillTypeSpread - Tasks should be assigned evenly across all Compute Nodes in the Pool. + NodeFillTypeSpread NodeFillType = "spread" +) + +// PossibleNodeFillTypeValues returns the possible values for the NodeFillType const type. +func PossibleNodeFillTypeValues() []NodeFillType { + return []NodeFillType{ + NodeFillTypePack, + NodeFillTypeSpread, + } +} + +// NodePlacementPolicyType - BatchNodePlacementPolicyType enums +type NodePlacementPolicyType string + +const ( + // NodePlacementPolicyTypeRegional - All nodes in the pool will be allocated in the same region. + NodePlacementPolicyTypeRegional NodePlacementPolicyType = "regional" + // NodePlacementPolicyTypeZonal - Nodes in the pool will be spread across different availability zones with best effort balancing. + NodePlacementPolicyTypeZonal NodePlacementPolicyType = "zonal" +) + +// PossibleNodePlacementPolicyTypeValues returns the possible values for the NodePlacementPolicyType const type. +func PossibleNodePlacementPolicyTypeValues() []NodePlacementPolicyType { + return []NodePlacementPolicyType{ + NodePlacementPolicyTypeRegional, + NodePlacementPolicyTypeZonal, + } +} + +// NodeRebootOption - BatchNodeRebootOption enums +type NodeRebootOption string + +const ( + // NodeRebootOptionRequeue - Terminate running Task processes and requeue the Tasks. The Tasks will run again when a Compute + // Node is available. Restart the Compute Node as soon as Tasks have been terminated. + NodeRebootOptionRequeue NodeRebootOption = "requeue" + // NodeRebootOptionRetainedData - Allow currently running Tasks to complete, then wait for all Task data retention periods + // to expire. Schedule no new Tasks while waiting. Restart the Compute Node when all Task retention periods have expired. + NodeRebootOptionRetainedData NodeRebootOption = "retaineddata" + // NodeRebootOptionTaskCompletion - Allow currently running Tasks to complete. Schedule no new Tasks while waiting. Restart + // the Compute Node when all Tasks have completed. + NodeRebootOptionTaskCompletion NodeRebootOption = "taskcompletion" + // NodeRebootOptionTerminate - Terminate running Tasks. The Tasks will be completed with failureInfo indicating that they + // were terminated, and will not run again. Restart the Compute Node as soon as Tasks have been terminated. + NodeRebootOptionTerminate NodeRebootOption = "terminate" +) + +// PossibleNodeRebootOptionValues returns the possible values for the NodeRebootOption const type. +func PossibleNodeRebootOptionValues() []NodeRebootOption { + return []NodeRebootOption{ + NodeRebootOptionRequeue, + NodeRebootOptionRetainedData, + NodeRebootOptionTaskCompletion, + NodeRebootOptionTerminate, + } +} + +// NodeReimageOption - BatchNodeReimageOption enums +type NodeReimageOption string + +const ( + // NodeReimageOptionRequeue - Terminate running Task processes and requeue the Tasks. The Tasks will run again when a Compute + // Node is available. Reimage the Compute Node as soon as Tasks have been terminated. + NodeReimageOptionRequeue NodeReimageOption = "requeue" + // NodeReimageOptionRetainedData - Allow currently running Tasks to complete, then wait for all Task data retention periods + // to expire. Schedule no new Tasks while waiting. Reimage the Compute Node when all Task retention periods have expired. + NodeReimageOptionRetainedData NodeReimageOption = "retaineddata" + // NodeReimageOptionTaskCompletion - Allow currently running Tasks to complete. Schedule no new Tasks while waiting. Reimage + // the Compute Node when all Tasks have completed. + NodeReimageOptionTaskCompletion NodeReimageOption = "taskcompletion" + // NodeReimageOptionTerminate - Terminate running Tasks. The Tasks will be completed with failureInfo indicating that they + // were terminated, and will not run again. Reimage the Compute Node as soon as Tasks have been terminated. + NodeReimageOptionTerminate NodeReimageOption = "terminate" +) + +// PossibleNodeReimageOptionValues returns the possible values for the NodeReimageOption const type. +func PossibleNodeReimageOptionValues() []NodeReimageOption { + return []NodeReimageOption{ + NodeReimageOptionRequeue, + NodeReimageOptionRetainedData, + NodeReimageOptionTaskCompletion, + NodeReimageOptionTerminate, + } +} + +// NodeState - BatchNodeState enums +type NodeState string + +const ( + // NodeStateCreating - The Batch service has obtained the underlying virtual machine from Azure Compute, but it has not yet + // started to join the Pool. + NodeStateCreating NodeState = "creating" + // NodeStateDeallocated - The Compute Node is deallocated. + NodeStateDeallocated NodeState = "deallocated" + // NodeStateDeallocating - The Compute Node is deallocating. + NodeStateDeallocating NodeState = "deallocating" + // NodeStateIdle - The Compute Node is not currently running a Task. + NodeStateIdle NodeState = "idle" + // NodeStateLeavingPool - The Compute Node is leaving the Pool, either because the user explicitly removed it or because the + // Pool is resizing or autoscaling down. + NodeStateLeavingPool NodeState = "leavingpool" + // NodeStateOffline - The Compute Node is not currently running a Task, and scheduling of new Tasks to the Compute Node is + // disabled. + NodeStateOffline NodeState = "offline" + // NodeStatePreempted - The Spot/Low-priority Compute Node has been preempted. Tasks which were running on the Compute Node + // when it was preempted will be rescheduled when another Compute Node becomes available. + NodeStatePreempted NodeState = "preempted" + // NodeStateRebooting - The Compute Node is rebooting. + NodeStateRebooting NodeState = "rebooting" + // NodeStateReimaging - The Compute Node is reimaging. + NodeStateReimaging NodeState = "reimaging" + // NodeStateRunning - The Compute Node is running one or more Tasks (other than a StartTask). + NodeStateRunning NodeState = "running" + // NodeStateStartTaskFailed - The StartTask has failed on the Compute Node (and exhausted all retries), and waitForSuccess + // is set. The Compute Node is not usable for running Tasks. + NodeStateStartTaskFailed NodeState = "starttaskfailed" + // NodeStateStarting - The Batch service is starting on the underlying virtual machine. + NodeStateStarting NodeState = "starting" + // NodeStateUnknown - The Batch service has lost contact with the Compute Node, and does not know its true state. + NodeStateUnknown NodeState = "unknown" + // NodeStateUnusable - The Compute Node cannot be used for Task execution due to errors. + NodeStateUnusable NodeState = "unusable" + // NodeStateUpgradingOS - The Compute Node is undergoing an OS upgrade operation. + NodeStateUpgradingOS NodeState = "upgradingos" + // NodeStateWaitingForStartTask - The StartTask has started running on the Compute Node, but waitForSuccess is set and the + // StartTask has not yet completed. + NodeStateWaitingForStartTask NodeState = "waitingforstarttask" +) + +// PossibleNodeStateValues returns the possible values for the NodeState const type. +func PossibleNodeStateValues() []NodeState { + return []NodeState{ + NodeStateCreating, + NodeStateDeallocated, + NodeStateDeallocating, + NodeStateIdle, + NodeStateLeavingPool, + NodeStateOffline, + NodeStatePreempted, + NodeStateRebooting, + NodeStateReimaging, + NodeStateRunning, + NodeStateStartTaskFailed, + NodeStateStarting, + NodeStateUnknown, + NodeStateUnusable, + NodeStateUpgradingOS, + NodeStateWaitingForStartTask, + } +} + +// OSType - OSType enums +type OSType string + +const ( + // OSTypeLinux - The Linux operating system. + OSTypeLinux OSType = "linux" + // OSTypeWindows - The Windows operating system. + OSTypeWindows OSType = "windows" +) + +// PossibleOSTypeValues returns the possible values for the OSType const type. +func PossibleOSTypeValues() []OSType { + return []OSType{ + OSTypeLinux, + OSTypeWindows, + } +} + +// OnAllTasksComplete - The action the Batch service should take when all Tasks in the Job are in the completed state. +type OnAllTasksComplete string + +const ( + // OnAllTasksCompleteNoAction - Do nothing. The Job remains active unless terminated or disabled by some other means. + OnAllTasksCompleteNoAction OnAllTasksComplete = "noaction" + // OnAllTasksCompleteTerminateJob - Terminate the Job. The Job's terminationReason is set to 'AllTasksComplete'. + OnAllTasksCompleteTerminateJob OnAllTasksComplete = "terminatejob" +) + +// PossibleOnAllTasksCompleteValues returns the possible values for the OnAllTasksComplete const type. +func PossibleOnAllTasksCompleteValues() []OnAllTasksComplete { + return []OnAllTasksComplete{ + OnAllTasksCompleteNoAction, + OnAllTasksCompleteTerminateJob, + } +} + +// OnTaskFailure - OnTaskFailure enums +type OnTaskFailure string + +const ( + // OnTaskFailureNoAction - Do nothing. The Job remains active unless terminated or disabled by some other means. + OnTaskFailureNoAction OnTaskFailure = "noaction" + // OnTaskFailurePerformExitOptionsJobAction - Terminate the Job. The Job's terminationReason is set to 'AllTasksComplete'. + OnTaskFailurePerformExitOptionsJobAction OnTaskFailure = "performexitoptionsjobaction" +) + +// PossibleOnTaskFailureValues returns the possible values for the OnTaskFailure const type. +func PossibleOnTaskFailureValues() []OnTaskFailure { + return []OnTaskFailure{ + OnTaskFailureNoAction, + OnTaskFailurePerformExitOptionsJobAction, + } +} + +// OutputFileUploadCondition - OutputFileUploadCondition enums +type OutputFileUploadCondition string + +const ( + // OutputFileUploadConditionTaskCompletion - Upload the file(s) after the Task process exits, no matter what the exit code + // was. + OutputFileUploadConditionTaskCompletion OutputFileUploadCondition = "taskcompletion" + // OutputFileUploadConditionTaskFailure - Upload the file(s) only after the Task process exits with a nonzero exit code. + OutputFileUploadConditionTaskFailure OutputFileUploadCondition = "taskfailure" + // OutputFileUploadConditionTaskSuccess - Upload the file(s) only after the Task process exits with an exit code of 0. + OutputFileUploadConditionTaskSuccess OutputFileUploadCondition = "tasksuccess" +) + +// PossibleOutputFileUploadConditionValues returns the possible values for the OutputFileUploadCondition const type. +func PossibleOutputFileUploadConditionValues() []OutputFileUploadCondition { + return []OutputFileUploadCondition{ + OutputFileUploadConditionTaskCompletion, + OutputFileUploadConditionTaskFailure, + OutputFileUploadConditionTaskSuccess, + } +} + +// PoolIdentityType - BatchPoolIdentityType enums +type PoolIdentityType string + +const ( + // PoolIdentityTypeNone - Batch pool has no identity associated with it. Setting `None` in update pool will remove existing + // identities. + PoolIdentityTypeNone PoolIdentityType = "None" + // PoolIdentityTypeUserAssigned - Batch pool has user assigned identities with it. + PoolIdentityTypeUserAssigned PoolIdentityType = "UserAssigned" +) + +// PossiblePoolIdentityTypeValues returns the possible values for the PoolIdentityType const type. +func PossiblePoolIdentityTypeValues() []PoolIdentityType { + return []PoolIdentityType{ + PoolIdentityTypeNone, + PoolIdentityTypeUserAssigned, + } +} + +// PoolLifetimeOption - BatchPoolLifetimeOption enums +type PoolLifetimeOption string + +const ( + // PoolLifetimeOptionJob - The Pool exists for the lifetime of the Job to which it is dedicated. The Batch service creates + // the Pool when it creates the Job. If the 'job' option is applied to a Job Schedule, the Batch service creates a new auto + // Pool for every Job created on the schedule. + PoolLifetimeOptionJob PoolLifetimeOption = "job" + // PoolLifetimeOptionJobSchedule - The Pool exists for the lifetime of the Job Schedule. The Batch Service creates the Pool + // when it creates the first Job on the schedule. You may apply this option only to Job Schedules, not to Jobs. + PoolLifetimeOptionJobSchedule PoolLifetimeOption = "jobschedule" +) + +// PossiblePoolLifetimeOptionValues returns the possible values for the PoolLifetimeOption const type. +func PossiblePoolLifetimeOptionValues() []PoolLifetimeOption { + return []PoolLifetimeOption{ + PoolLifetimeOptionJob, + PoolLifetimeOptionJobSchedule, + } +} + +// PoolState - BatchPoolState enums +type PoolState string + +const ( + // PoolStateActive - The Pool is available to run Tasks subject to the availability of Compute Nodes. + PoolStateActive PoolState = "active" + // PoolStateDeleting - The user has requested that the Pool be deleted, but the delete operation has not yet completed. + PoolStateDeleting PoolState = "deleting" +) + +// PossiblePoolStateValues returns the possible values for the PoolState const type. +func PossiblePoolStateValues() []PoolState { + return []PoolState{ + PoolStateActive, + PoolStateDeleting, + } +} + +// SchedulingState - SchedulingState enums +type SchedulingState string + +const ( + // SchedulingStateDisabled - No new Tasks will be scheduled on the Compute Node. Tasks already running on the Compute Node + // may still run to completion. All Compute Nodes start with scheduling enabled. + SchedulingStateDisabled SchedulingState = "disabled" + // SchedulingStateEnabled - Tasks can be scheduled on the Compute Node. + SchedulingStateEnabled SchedulingState = "enabled" +) + +// PossibleSchedulingStateValues returns the possible values for the SchedulingState const type. +func PossibleSchedulingStateValues() []SchedulingState { + return []SchedulingState{ + SchedulingStateDisabled, + SchedulingStateEnabled, + } +} + +// SecurityEncryptionTypes - SecurityEncryptionTypes enums +type SecurityEncryptionTypes string + +const ( + // SecurityEncryptionTypesNonPersistedTPM - NonPersistedTPM + SecurityEncryptionTypesNonPersistedTPM SecurityEncryptionTypes = "NonPersistedTPM" + // SecurityEncryptionTypesVMGuestStateOnly - VMGuestStateOnly + SecurityEncryptionTypesVMGuestStateOnly SecurityEncryptionTypes = "VMGuestStateOnly" +) + +// PossibleSecurityEncryptionTypesValues returns the possible values for the SecurityEncryptionTypes const type. +func PossibleSecurityEncryptionTypesValues() []SecurityEncryptionTypes { + return []SecurityEncryptionTypes{ + SecurityEncryptionTypesNonPersistedTPM, + SecurityEncryptionTypesVMGuestStateOnly, + } +} + +// SecurityTypes - Specifies the SecurityType of the virtual machine. It has to be set to any specified value to enable UefiSettings. +type SecurityTypes string + +const ( + // SecurityTypesConfidentialVM - Azure confidential computing offers confidential VMs are for tenants with high security and + // confidentiality requirements. These VMs provide a strong, hardware-enforced boundary to help meet your security needs. + // You can use confidential VMs for migrations without making changes to your code, with the platform protecting your VM's + // state from being read or modified. + SecurityTypesConfidentialVM SecurityTypes = "confidentialVM" + // SecurityTypesTrustedLaunch - Trusted launch protects against advanced and persistent attack techniques. + SecurityTypesTrustedLaunch SecurityTypes = "trustedLaunch" +) + +// PossibleSecurityTypesValues returns the possible values for the SecurityTypes const type. +func PossibleSecurityTypesValues() []SecurityTypes { + return []SecurityTypes{ + SecurityTypesConfidentialVM, + SecurityTypesTrustedLaunch, + } +} + +// StartTaskState - BatchStartTaskState enums +type StartTaskState string + +const ( + // StartTaskStateCompleted - The StartTask has exited with exit code 0, or the StartTask has failed and the retry limit has + // reached, or the StartTask process did not run due to Task preparation errors (such as resource file download failures). + StartTaskStateCompleted StartTaskState = "completed" + // StartTaskStateRunning - The StartTask is currently running. + StartTaskStateRunning StartTaskState = "running" +) + +// PossibleStartTaskStateValues returns the possible values for the StartTaskState const type. +func PossibleStartTaskStateValues() []StartTaskState { + return []StartTaskState{ + StartTaskStateCompleted, + StartTaskStateRunning, + } +} + +// StatusLevelTypes - Level code. +type StatusLevelTypes string + +const ( + // StatusLevelTypesError - Error + StatusLevelTypesError StatusLevelTypes = "Error" + // StatusLevelTypesInfo - Info + StatusLevelTypesInfo StatusLevelTypes = "Info" + // StatusLevelTypesWarning - Warning + StatusLevelTypesWarning StatusLevelTypes = "Warning" +) + +// PossibleStatusLevelTypesValues returns the possible values for the StatusLevelTypes const type. +func PossibleStatusLevelTypesValues() []StatusLevelTypes { + return []StatusLevelTypes{ + StatusLevelTypesError, + StatusLevelTypesInfo, + StatusLevelTypesWarning, + } +} + +// StorageAccountType - StorageAccountType enums +type StorageAccountType string + +const ( + // StorageAccountTypePremiumLRS - The data disk should use premium locally redundant storage. + StorageAccountTypePremiumLRS StorageAccountType = "premium_lrs" + // StorageAccountTypeStandardLRS - The data disk should use standard locally redundant storage. + StorageAccountTypeStandardLRS StorageAccountType = "standard_lrs" + // StorageAccountTypeStandardSSDLRS - The data disk / OS disk should use standard SSD locally redundant storage. + StorageAccountTypeStandardSSDLRS StorageAccountType = "standardssd_lrs" +) + +// PossibleStorageAccountTypeValues returns the possible values for the StorageAccountType const type. +func PossibleStorageAccountTypeValues() []StorageAccountType { + return []StorageAccountType{ + StorageAccountTypePremiumLRS, + StorageAccountTypeStandardLRS, + StorageAccountTypeStandardSSDLRS, + } +} + +// SubtaskState - BatchSubtaskState enums +type SubtaskState string + +const ( + // SubtaskStateCompleted - The Task is no longer eligible to run, usually because the Task has finished successfully, or the + // Task has finished unsuccessfully and has exhausted its retry limit. A Task is also marked as completed if an error occurred + // launching the Task, or when the Task has been terminated. + SubtaskStateCompleted SubtaskState = "completed" + // SubtaskStatePreparing - The Task has been assigned to a Compute Node, but is waiting for a required Job Preparation Task + // to complete on the Compute Node. If the Job Preparation Task succeeds, the Task will move to running. If the Job Preparation + // Task fails, the Task will return to active and will be eligible to be assigned to a different Compute Node. + SubtaskStatePreparing SubtaskState = "preparing" + // SubtaskStateRunning - The Task is running on a Compute Node. This includes task-level preparation such as downloading resource + // files or deploying Packages specified on the Task - it does not necessarily mean that the Task command line has started + // executing. + SubtaskStateRunning SubtaskState = "running" +) + +// PossibleSubtaskStateValues returns the possible values for the SubtaskState const type. +func PossibleSubtaskStateValues() []SubtaskState { + return []SubtaskState{ + SubtaskStateCompleted, + SubtaskStatePreparing, + SubtaskStateRunning, + } +} + +// TaskAddStatus - BatchTaskAddStatus enums +type TaskAddStatus string + +const ( + // TaskAddStatusClientError - The Task failed to add due to a client error and should not be retried without modifying the + // request as appropriate. + TaskAddStatusClientError TaskAddStatus = "clienterror" + // TaskAddStatusServerError - Task failed to add due to a server error and can be retried without modification. + TaskAddStatusServerError TaskAddStatus = "servererror" + // TaskAddStatusSuccess - The Task was added successfully. + TaskAddStatusSuccess TaskAddStatus = "success" +) + +// PossibleTaskAddStatusValues returns the possible values for the TaskAddStatus const type. +func PossibleTaskAddStatusValues() []TaskAddStatus { + return []TaskAddStatus{ + TaskAddStatusClientError, + TaskAddStatusServerError, + TaskAddStatusSuccess, + } +} + +// TaskExecutionResult - BatchTaskExecutionResult enums +type TaskExecutionResult string + +const ( + // TaskExecutionResultFailure - There was an error during processing of the Task. The failure may have occurred before the + // Task process was launched, while the Task process was executing, or after the Task process exited. + TaskExecutionResultFailure TaskExecutionResult = "failure" + // TaskExecutionResultSuccess - The Task ran successfully. + TaskExecutionResultSuccess TaskExecutionResult = "success" +) + +// PossibleTaskExecutionResultValues returns the possible values for the TaskExecutionResult const type. +func PossibleTaskExecutionResultValues() []TaskExecutionResult { + return []TaskExecutionResult{ + TaskExecutionResultFailure, + TaskExecutionResultSuccess, + } +} + +// TaskState - BatchTaskState enums +type TaskState string + +const ( + // TaskStateActive - The Task is queued and able to run, but is not currently assigned to a Compute Node. A Task enters this + // state when it is created, when it is enabled after being disabled, or when it is awaiting a retry after a failed run. + TaskStateActive TaskState = "active" + // TaskStateCompleted - The Task is no longer eligible to run, usually because the Task has finished successfully, or the + // Task has finished unsuccessfully and has exhausted its retry limit. A Task is also marked as completed if an error occurred + // launching the Task, or when the Task has been terminated. + TaskStateCompleted TaskState = "completed" + // TaskStatePreparing - The Task has been assigned to a Compute Node, but is waiting for a required Job Preparation Task to + // complete on the Compute Node. If the Job Preparation Task succeeds, the Task will move to running. If the Job Preparation + // Task fails, the Task will return to active and will be eligible to be assigned to a different Compute Node. + TaskStatePreparing TaskState = "preparing" + // TaskStateRunning - The Task is running on a Compute Node. This includes task-level preparation such as downloading resource + // files or deploying Packages specified on the Task - it does not necessarily mean that the Task command line has started + // executing. + TaskStateRunning TaskState = "running" +) + +// PossibleTaskStateValues returns the possible values for the TaskState const type. +func PossibleTaskStateValues() []TaskState { + return []TaskState{ + TaskStateActive, + TaskStateCompleted, + TaskStatePreparing, + TaskStateRunning, + } +} + +// UpgradeMode - UpgradeMode enums +type UpgradeMode string + +const ( + // UpgradeModeAutomatic - TAll virtual machines in the scale set are automatically updated at the same time. + UpgradeModeAutomatic UpgradeMode = "automatic" + // UpgradeModeManual - You control the application of updates to virtual machines in the scale set. You do this by using the + // manualUpgrade action. + UpgradeModeManual UpgradeMode = "manual" + // UpgradeModeRolling - The existing instances in a scale set are brought down in batches to be upgraded. Once the upgraded + // batch is complete, the instances will begin taking traffic again and the next batch will begin. This continues until all + // instances brought up-to-date. + UpgradeModeRolling UpgradeMode = "rolling" +) + +// PossibleUpgradeModeValues returns the possible values for the UpgradeMode const type. +func PossibleUpgradeModeValues() []UpgradeMode { + return []UpgradeMode{ + UpgradeModeAutomatic, + UpgradeModeManual, + UpgradeModeRolling, + } +} diff --git a/sdk/batch/azbatch/go.mod b/sdk/batch/azbatch/go.mod new file mode 100644 index 000000000000..3f7b9ab71736 --- /dev/null +++ b/sdk/batch/azbatch/go.mod @@ -0,0 +1,13 @@ +module github.com/Azure/azure-sdk-for-go/sdk/batch/azbatch + +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/batch/azbatch/go.sum b/sdk/batch/azbatch/go.sum new file mode 100644 index 000000000000..cfff861c9769 --- /dev/null +++ b/sdk/batch/azbatch/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/batch/azbatch/models.go b/sdk/batch/azbatch/models.go new file mode 100644 index 000000000000..f560a4e877d9 --- /dev/null +++ b/sdk/batch/azbatch/models.go @@ -0,0 +1,4023 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package azbatch + +import "time" + +// AccountListSupportedImagesResult - The result of listing the supported Virtual Machine Images. +type AccountListSupportedImagesResult struct { + // The URL to get the next set of results. + NextLink *string + + // The list of supported Virtual Machine Images. + Value []SupportedImage +} + +// AddTaskCollectionResult - The result of adding a collection of Tasks to a Job. +type AddTaskCollectionResult struct { + // The results of the add Task collection operation. + Value []TaskAddResult +} + +// AffinityInfo - A locality hint that can be used by the Batch service to select a Compute Node +// on which to start a Task. +type AffinityInfo struct { + // REQUIRED; An opaque string representing the location of a Compute Node or a Task that has run previously. You can pass + // the affinityId of a Node to indicate that this Task needs to run on that Compute Node. Note that this is just a soft affinity. + // If the target Compute Node is busy or unavailable at the time the Task is scheduled, then the Task will be scheduled elsewhere. + AffinityID *string +} + +// Application - Contains information about an application in an Azure Batch Account. +type Application struct { + // REQUIRED; The display name for the application. + DisplayName *string + + // REQUIRED; A string that uniquely identifies the application within the Account. + ID *string + + // REQUIRED; The list of available versions of the application. + Versions []string +} + +// ApplicationListResult - The result of listing the applications available in an Account. +type ApplicationListResult struct { + // The URL to get the next set of results. + NextLink *string + + // The list of applications available in the Account. + Value []Application +} + +// ApplicationPackageReference - A reference to an Package to be deployed to Compute Nodes. +type ApplicationPackageReference struct { + // REQUIRED; The ID of the application to deploy. When creating a pool, the package's application ID must be fully qualified + // (/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationName}). + ApplicationID *string + + // The version of the application to deploy. If omitted, the default version is deployed. If this is omitted on a Pool, and + // no default version is specified for this application, the request fails with the error code InvalidApplicationPackageReferences + // and HTTP status code 409. If this is omitted on a Task, and no default version is specified for this application, the Task + // fails with a pre-processing error. + Version *string +} + +// AuthenticationTokenSettings - The settings for an authentication token that the Task can use to perform Batch +// service operations. +type AuthenticationTokenSettings struct { + // The Batch resources to which the token grants access. The authentication token grants access to a limited set of Batch + // service operations. Currently the only supported value for the access property is 'job', which grants access to all operations + // related to the Job which contains the Task. + Access []AccessScope +} + +// AutoPoolSpecification - Specifies characteristics for a temporary 'auto pool'. The Batch service will +// create this auto Pool when the Job is submitted. +type AutoPoolSpecification struct { + // REQUIRED; The minimum lifetime of created auto Pools, and how multiple Jobs on a schedule are assigned to Pools. + PoolLifetimeOption *PoolLifetimeOption + + // A prefix to be added to the unique identifier when a Pool is automatically created. The Batch service assigns each auto + // Pool a unique identifier on creation. To distinguish between Pools created for different purposes, you can specify this + // element to add a prefix to the ID that is assigned. The prefix can be up to 20 characters long. + AutoPoolIDPrefix *string + + // Whether to keep an auto Pool alive after its lifetime expires. If false, the Batch service deletes the Pool once its lifetime + // (as determined by the poolLifetimeOption setting) expires; that is, when the Job or Job Schedule completes. If true, the + // Batch service does not delete the Pool automatically. It is up to the user to delete auto Pools created with this option. + KeepAlive *bool + + // The Pool specification for the auto Pool. + Pool *PoolSpecification +} + +// AutoScaleRun - The results and errors from an execution of a Pool autoscale formula. +type AutoScaleRun struct { + // REQUIRED; The time at which the autoscale formula was last evaluated. + Timestamp *time.Time + + // Details of the error encountered evaluating the autoscale formula on the Pool, if the evaluation was unsuccessful. + Error *AutoScaleRunError + + // The final values of all variables used in the evaluation of the autoscale formula. Each variable value is returned in the + // form $variable=value, and variables are separated by semicolons. + Results *string +} + +// AutoScaleRunError - An error that occurred when executing or evaluating a Pool autoscale formula. +type AutoScaleRunError struct { + // An identifier for the autoscale error. Codes are invariant and are intended to be consumed programmatically. + Code *string + + // A message describing the autoscale error, intended to be suitable for display in a user interface. + Message *string + + // A list of additional error details related to the autoscale error. + Values []NameValuePair +} + +// AutoUserSpecification - Specifies the options for the auto user that runs an Azure Batch Task. +type AutoUserSpecification struct { + // The elevation level of the auto user. The default value is nonAdmin. + ElevationLevel *ElevationLevel + + // The scope for the auto user. The default value is pool. If the pool is running Windows a value of Task should be specified + // if stricter isolation between tasks is required. For example, if the task mutates the registry in a way which could impact + // other tasks, or if certificates have been specified on the pool which should not be accessible by normal tasks but should + // be accessible by StartTasks. + Scope *AutoUserScope +} + +// AutomaticOSUpgradePolicy - The configuration parameters used for performing automatic OS upgrade. +type AutomaticOSUpgradePolicy struct { + // Whether OS image rollback feature should be disabled. + DisableAutomaticRollback *bool + + // Indicates whether OS upgrades should automatically be applied to scale set instances in a rolling fashion when a newer + // version of the OS image becomes available.

If this is set to true for Windows based pools, [WindowsConfiguration.enableAutomaticUpdates](https://learn.microsoft.com/rest/api/batchservice/pool/add?tabs=HTTP#windowsconfiguration) + // cannot be set to true. + EnableAutomaticOsUpgrade *bool + + // Defer OS upgrades on the TVMs if they are running tasks. + OSRollingUpgradeDeferral *bool + + // Indicates whether rolling upgrade policy should be used during Auto OS Upgrade. Auto OS Upgrade will fallback to the default + // policy if no policy is defined on the VMSS. + UseRollingUpgradePolicy *bool +} + +// AzureBlobFileSystemConfiguration - Information used to connect to an Azure Storage Container using Blobfuse. +type AzureBlobFileSystemConfiguration struct { + // REQUIRED; The Azure Storage Account name. + AccountName *string + + // REQUIRED; The Azure Blob Storage Container name. + ContainerName *string + + // REQUIRED; The relative path on the compute node where the file system will be mounted. All file systems are mounted relative + // to the Batch mounts directory, accessible via the AZ_BATCH_NODE_MOUNTS_DIR environment variable. + RelativeMountPath *string + + // The Azure Storage Account key. This property is mutually exclusive with both sasKey and identity; exactly one must be specified. + AccountKey *string + + // Additional command line options to pass to the mount command. These are 'net use' options in Windows and 'mount' options + // in Linux. + BlobfuseOptions *string + + // The reference to the user assigned identity to use to access containerName. This property is mutually exclusive with both + // accountKey and sasKey; exactly one must be specified. + IdentityReference *NodeIdentityReference + + // The Azure Storage SAS token. This property is mutually exclusive with both accountKey and identity; exactly one must be + // specified. + SASKey *string +} + +// AzureFileShareConfiguration - Information used to connect to an Azure Fileshare. +type AzureFileShareConfiguration struct { + // REQUIRED; The Azure Storage account key. + AccountKey *string + + // REQUIRED; The Azure Storage account name. + AccountName *string + + // REQUIRED; The Azure Files URL. This is of the form 'https://{account}.file.core.windows.net/'. + AzureFileURL *string + + // REQUIRED; The relative path on the compute node where the file system will be mounted. All file systems are mounted relative + // to the Batch mounts directory, accessible via the AZ_BATCH_NODE_MOUNTS_DIR environment variable. + RelativeMountPath *string + + // Additional command line options to pass to the mount command. These are 'net use' options in Windows and 'mount' options + // in Linux. + MountOptions *string +} + +// CIFSMountConfiguration - Information used to connect to a CIFS file system. +type CIFSMountConfiguration struct { + // REQUIRED; The password to use for authentication against the CIFS file system. + Password *string + + // REQUIRED; The relative path on the compute node where the file system will be mounted. All file systems are mounted relative + // to the Batch mounts directory, accessible via the AZ_BATCH_NODE_MOUNTS_DIR environment variable. + RelativeMountPath *string + + // REQUIRED; The URI of the file system to mount. + Source *string + + // REQUIRED; The user to use for authentication against the CIFS file system. + Username *string + + // Additional command line options to pass to the mount command. These are 'net use' options in Windows and 'mount' options + // in Linux. + MountOptions *string +} + +// Certificate - A Certificate that can be installed on Compute Nodes and can be used to +// authenticate operations on the machine. +type Certificate struct { + // REQUIRED; The base64-encoded contents of the Certificate. The maximum size is 10KB. + Data *string + + // REQUIRED; The X.509 thumbprint of the Certificate. This is a sequence of up to 40 hex digits (it may include spaces but + // these are removed). + Thumbprint *string + + // REQUIRED; The algorithm used to derive the thumbprint. This must be sha1. + ThumbprintAlgorithm *string + + // The format of the Certificate data. + Format *CertificateFormat + + // The password to access the Certificate's private key. This must be omitted if the Certificate format is cer. + Password *string + + // READ-ONLY; The error that occurred on the last attempt to delete this Certificate. This property is set only if the Certificate + // is in the DeleteFailed state. + DeleteCertificateError *DeleteCertificateError + + // READ-ONLY; The previous state of the Certificate. This property is not set if the Certificate is in its initial active + // state. + PreviousState *CertificateState + + // READ-ONLY; The time at which the Certificate entered its previous state. This property is not set if the Certificate is + // in its initial Active state. + PreviousStateTransitionTime *time.Time + + // READ-ONLY; The public part of the Certificate as a base-64 encoded .cer file. + PublicData *string + + // READ-ONLY; The state of the Certificate. + State *CertificateState + + // READ-ONLY; The time at which the Certificate entered its current state. + StateTransitionTime *time.Time + + // READ-ONLY; The URL of the Certificate. + URL *string +} + +// CertificateListResult - The result of listing the Certificates in the Account. +type CertificateListResult struct { + // The URL to get the next set of results. + NextLink *string + + // The list of Certificates. + Value []Certificate +} + +// CertificateReference - A reference to a Certificate to be installed on Compute Nodes in a Pool. Warning: This object is +// deprecated and will be removed after February, 2024. Please use the [Azure KeyVault Extension](https://learn.microsoft.com/azure/batch/batch-certificate-migration-guide) +// instead. +type CertificateReference struct { + // REQUIRED; The thumbprint of the Certificate. + Thumbprint *string + + // REQUIRED; The algorithm with which the thumbprint is associated. This must be sha1. + ThumbprintAlgorithm *string + + // The location of the Certificate store on the Compute Node into which to install the Certificate. The default value is currentuser. + // This property is applicable only for Pools configured with Windows Compute Nodes (that is, created with cloudServiceConfiguration, + // or with virtualMachineConfiguration using a Windows Image reference). For Linux Compute Nodes, the Certificates are stored + // in a directory inside the Task working directory and an environment variable AZ_BATCH_CERTIFICATES_DIR is supplied to the + // Task to query for this location. For Certificates with visibility of 'remoteUser', a 'certs' directory is created in the + // user's home directory (e.g., /home/{user-name}/certs) and Certificates are placed in that directory. + StoreLocation *CertificateStoreLocation + + // The name of the Certificate store on the Compute Node into which to install the Certificate. This property is applicable + // only for Pools configured with Windows Compute Nodes (that is, created with cloudServiceConfiguration, or with virtualMachineConfiguration + // using a Windows Image reference). Common store names include: My, Root, CA, Trust, Disallowed, TrustedPeople, TrustedPublisher, + // AuthRoot, AddressBook, but any custom store name can also be used. The default value is My. + StoreName *string + + // Which user Accounts on the Compute Node should have access to the private data of the Certificate. You can specify more + // than one visibility in this collection. The default is all Accounts. + Visibility []CertificateVisibility +} + +// ContainerConfiguration - The configuration for container-enabled Pools. +type ContainerConfiguration struct { + // REQUIRED; The container technology to be used. + Type *ContainerType + + // The collection of container Image names. This is the full Image reference, as would be specified to "docker pull". An Image + // will be sourced from the default Docker registry unless the Image is fully qualified with an alternative registry. + ContainerImageNames []string + + // Additional private registries from which containers can be pulled. If any Images must be downloaded from a private registry + // which requires credentials, then those credentials must be provided here. + ContainerRegistries []ContainerRegistryReference +} + +// ContainerHostBindMountEntry - The entry of path and mount mode you want to mount into task container. +type ContainerHostBindMountEntry struct { + // Mount this source path as read-only mode or not. Default value is false (read/write mode). For Linux, if you mount this + // path as a read/write mode, this does not mean that all users in container have the read/write access for the path, it depends + // on the access in host VM. If this path is mounted read-only, all users within the container will not be able to modify + // the path. + IsReadOnly *bool + + // The path which be mounted to container customer can select. + Source *ContainerHostDataPath +} + +// ContainerRegistryReference - A private container registry. +type ContainerRegistryReference struct { + // The reference to the user assigned identity to use to access an Azure Container Registry instead of username and password. + IdentityReference *NodeIdentityReference + + // The password to log into the registry server. + Password *string + + // The registry URL. If omitted, the default is "docker.io". + RegistryServer *string + + // The user name to log into the registry server. + Username *string +} + +// CreateJobContent - Parameters for creating an Azure Batch Job. +type CreateJobContent struct { + // REQUIRED; A string that uniquely identifies the Job within the Account. The ID can contain any combination of alphanumeric + // characters including hyphens and underscores, and cannot contain more than 64 characters. The ID is case-preserving and + // case-insensitive (that is, you may not have two IDs within an Account that differ only by case). + ID *string + + // REQUIRED; The Pool on which the Batch service runs the Job's Tasks. + PoolInfo *PoolInfo + + // Whether Tasks in this job can be preempted by other high priority jobs. If the value is set to True, other high priority + // jobs submitted to the system will take precedence and will be able requeue tasks from this job. You can update a job's + // allowTaskPreemption after it has been created using the update job API. + AllowTaskPreemption *bool + + // The list of common environment variable settings. These environment variables are set for all Tasks in the Job (including + // the Job Manager, Job Preparation and Job Release Tasks). Individual Tasks can override an environment setting specified + // here by specifying the same setting name with a different value. + CommonEnvironmentSettings []EnvironmentSetting + + // The execution constraints for the Job. + Constraints *JobConstraints + + // The display name for the Job. The display name need not be unique and can contain any Unicode characters up to a maximum + // length of 1024. + DisplayName *string + + // Details of a Job Manager Task to be launched when the Job is started. If the Job does not specify a Job Manager Task, the + // user must explicitly add Tasks to the Job. If the Job does specify a Job Manager Task, the Batch service creates the Job + // Manager Task when the Job is created, and will try to schedule the Job Manager Task before scheduling other Tasks in the + // Job. The Job Manager Task's typical purpose is to control and/or monitor Job execution, for example by deciding what additional + // Tasks to run, determining when the work is complete, etc. (However, a Job Manager Task is not restricted to these activities + // - it is a fully-fledged Task in the system and perform whatever actions are required for the Job.) For example, a Job Manager + // Task might download a file specified as a parameter, analyze the contents of that file and submit additional Tasks based + // on those contents. + JobManagerTask *JobManagerTask + + // The Job Preparation Task. If a Job has a Job Preparation Task, the Batch service will run the Job Preparation Task on a + // Node before starting any Tasks of that Job on that Compute Node. + JobPreparationTask *JobPreparationTask + + // The Job Release Task. A Job Release Task cannot be specified without also specifying a Job Preparation Task for the Job. + // The Batch service runs the Job Release Task on the Nodes that have run the Job Preparation Task. The primary purpose of + // the Job Release Task is to undo changes to Compute Nodes made by the Job Preparation Task. Example activities include deleting + // local files, or shutting down services that were started as part of Job preparation. + JobReleaseTask *JobReleaseTask + + // The maximum number of tasks that can be executed in parallel for the job. The value of maxParallelTasks must be -1 or greater + // than 0 if specified. If not specified, the default value is -1, which means there's no limit to the number of tasks that + // can be run at once. You can update a job's maxParallelTasks after it has been created using the update job API. + MaxParallelTasks *int32 + + // A list of name-value pairs associated with the Job as metadata. The Batch service does not assign any meaning to metadata; + // it is solely for the use of user code. + Metadata []MetadataItem + + // The network configuration for the Job. + NetworkConfiguration *JobNetworkConfiguration + + // The action the Batch service should take when all Tasks in the Job are in the completed state. Note that if a Job contains + // no Tasks, then all Tasks are considered complete. This option is therefore most commonly used with a Job Manager task; + // if you want to use automatic Job termination without a Job Manager, you should initially set onAllTasksComplete to noaction + // and update the Job properties to set onAllTasksComplete to terminatejob once you have finished adding Tasks. The default + // is noaction. + OnAllTasksComplete *OnAllTasksComplete + + // The action the Batch service should take when any Task in the Job fails. A Task is considered to have failed if has a failureInfo. + // A failureInfo is set if the Task completes with a non-zero exit code after exhausting its retry count, or if there was + // an error starting the Task, for example due to a resource file download error. The default is noaction. + OnTaskFailure *OnTaskFailure + + // The priority of the Job. Priority values can range from -1000 to 1000, with -1000 being the lowest priority and 1000 being + // the highest priority. The default value is 0. + Priority *int32 + + // Whether Tasks in the Job can define dependencies on each other. The default is false. + UsesTaskDependencies *bool +} + +// CreateJobScheduleContent - Parameters for creating an Azure Batch Job Schedule +type CreateJobScheduleContent struct { + // REQUIRED; A string that uniquely identifies the schedule within the Account. The ID can contain any combination of alphanumeric + // characters including hyphens and underscores, and cannot contain more than 64 characters. The ID is case-preserving and + // case-insensitive (that is, you may not have two IDs within an Account that differ only by case). + ID *string + + // REQUIRED; The details of the Jobs to be created on this schedule. + JobSpecification *JobSpecification + + // REQUIRED; The schedule according to which Jobs will be created. All times are fixed respective to UTC and are not impacted + // by daylight saving time. + Schedule *JobScheduleConfiguration + + // The display name for the schedule. The display name need not be unique and can contain any Unicode characters up to a maximum + // length of 1024. + DisplayName *string + + // A list of name-value pairs associated with the schedule as metadata. The Batch service does not assign any meaning to metadata; + // it is solely for the use of user code. + Metadata []MetadataItem +} + +// CreateNodeUserContent - Parameters for creating a user account for RDP or SSH access on an Azure Batch Compute Node. +type CreateNodeUserContent struct { + // REQUIRED; The user name of the Account. + Name *string + + // The time at which the Account should expire. If omitted, the default is 1 day from the current time. For Linux Compute + // Nodes, the expiryTime has a precision up to a day. + ExpiryTime *time.Time + + // Whether the Account should be an administrator on the Compute Node. The default value is false. + IsAdmin *bool + + // The password of the Account. The password is required for Windows Compute Nodes. For Linux Compute Nodes, the password + // can optionally be specified along with the sshPublicKey property. + Password *string + + // The SSH public key that can be used for remote login to the Compute Node. The public key should be compatible with OpenSSH + // encoding and should be base 64 encoded. This property can be specified only for Linux Compute Nodes. If this is specified + // for a Windows Compute Node, then the Batch service rejects the request; if you are calling the REST API directly, the HTTP + // status code is 400 (Bad Request). + SSHPublicKey *string +} + +// CreatePoolContent - Parameters for creating an Azure Batch Pool. +type CreatePoolContent struct { + // REQUIRED; A string that uniquely identifies the Pool within the Account. The ID can contain any combination of alphanumeric + // characters including hyphens and underscores, and cannot contain more than 64 characters. The ID is case-preserving and + // case-insensitive (that is, you may not have two Pool IDs within an Account that differ only by case). + ID *string + + // REQUIRED; The size of virtual machines in the Pool. All virtual machines in a Pool are the same size. For information about + // available VM sizes for Pools using Images from the Virtual Machines Marketplace (pools created with virtualMachineConfiguration), + // see Sizes for Virtual Machines in Azure (https://learn.microsoft.com/azure/virtual-machines/sizes/overview). Batch supports + // all Azure VM sizes except STANDARD_A0 and those with premium storage (STANDARD_GS, STANDARD_DS, and STANDARD_DSV2 series). + VMSize *string + + // The list of Packages to be installed on each Compute Node in the Pool. When creating a pool, the package's application + // ID must be fully qualified (/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationName}). + // Changes to Package references affect all new Nodes joining the Pool, but do not affect Compute Nodes that are already in + // the Pool until they are rebooted or reimaged. There is a maximum of 10 Package references on any given Pool. + ApplicationPackageReferences []ApplicationPackageReference + + // The time interval at which to automatically adjust the Pool size according to the autoscale formula. The default value + // is 15 minutes. The minimum and maximum value are 5 minutes and 168 hours respectively. If you specify a value less than + // 5 minutes or greater than 168 hours, the Batch service returns an error; if you are calling the REST API directly, the + // HTTP status code is 400 (Bad Request). + AutoScaleEvaluationInterval *string + + // A formula for the desired number of Compute Nodes in the Pool. This property must not be specified if enableAutoScale is + // set to false. It is required if enableAutoScale is set to true. The formula is checked for validity before the Pool is + // created. If the formula is not valid, the Batch service rejects the request with detailed error information. For more information + // about specifying this formula, see 'Automatically scale Compute Nodes in an Azure Batch Pool' (https://learn.microsoft.com/azure/batch/batch-automatic-scaling). + AutoScaleFormula *string + + // For Windows Nodes, the Batch service installs the Certificates to the specified Certificate store and location. + // For Linux Compute Nodes, the Certificates are stored in a directory inside the Task working directory and an environment + // variable AZ_BATCH_CERTIFICATES_DIR is supplied to the Task to query for this location. + // For Certificates with visibility of 'remoteUser', a 'certs' directory is created in the user's home directory (e.g., /home/{user-name}/certs) + // and Certificates are placed in that directory. + // Warning: This property is deprecated and will be removed after February, 2024. Please use the [Azure KeyVault Extension](https://learn.microsoft.com/azure/batch/batch-certificate-migration-guide) + // instead. + CertificateReferences []CertificateReference + + // The display name for the Pool. The display name need not be unique and can contain any Unicode characters up to a maximum + // length of 1024. + DisplayName *string + + // Whether the Pool size should automatically adjust over time. If false, at least one of targetDedicatedNodes and targetLowPriorityNodes + // must be specified. If true, the autoScaleFormula property is required and the Pool automatically resizes according to the + // formula. The default value is false. + EnableAutoScale *bool + + // Whether the Pool permits direct communication between Compute Nodes. Enabling inter-node communication limits the maximum + // size of the Pool due to deployment restrictions on the Compute Nodes of the Pool. This may result in the Pool not reaching + // its desired size. The default value is false. + EnableInterNodeCommunication *bool + + // A list of name-value pairs associated with the Pool as metadata. The Batch service does not assign any meaning to metadata; + // it is solely for the use of user code. + Metadata []MetadataItem + + // Mount storage using specified file system for the entire lifetime of the pool. Mount the storage using Azure fileshare, + // NFS, CIFS or Blobfuse based file system. + MountConfiguration []MountConfiguration + + // The network configuration for the Pool. + NetworkConfiguration *NetworkConfiguration + + // The timeout for allocation of Compute Nodes to the Pool. This timeout applies only to manual scaling; it has no effect + // when enableAutoScale is set to true. The default value is 15 minutes. The minimum value is 5 minutes. If you specify a + // value less than 5 minutes, the Batch service returns an error; if you are calling the REST API directly, the HTTP status + // code is 400 (Bad Request). + ResizeTimeout *string + + // The user-specified tags associated with the pool. The user-defined tags to be associated with the Azure Batch Pool. When + // specified, these tags are propagated to the backing Azure resources associated with the pool. This property can only be + // specified when the Batch account was created with the poolAllocationMode property set to 'UserSubscription'. + ResourceTags map[string]*string + + // A Task specified to run on each Compute Node as it joins the Pool. The Task runs when the Compute Node is added to the + // Pool or when the Compute Node is restarted. + StartTask *StartTask + + // The desired number of dedicated Compute Nodes in the Pool. This property must not be specified if enableAutoScale is set + // to true. If enableAutoScale is set to false, then you must set either targetDedicatedNodes, targetLowPriorityNodes, or + // both. + TargetDedicatedNodes *int32 + + // The desired number of Spot/Low-priority Compute Nodes in the Pool. This property must not be specified if enableAutoScale + // is set to true. If enableAutoScale is set to false, then you must set either targetDedicatedNodes, targetLowPriorityNodes, + // or both. + TargetLowPriorityNodes *int32 + + // The desired node communication mode for the pool. If omitted, the default value is Default. + TargetNodeCommunicationMode *NodeCommunicationMode + + // How Tasks are distributed across Compute Nodes in a Pool. If not specified, the default is spread. + TaskSchedulingPolicy *TaskSchedulingPolicy + + // The number of task slots that can be used to run concurrent tasks on a single compute node in the pool. The default value + // is 1. The maximum value is the smaller of 4 times the number of cores of the vmSize of the pool or 256. + TaskSlotsPerNode *int32 + + // The upgrade policy for the Pool. Describes an upgrade policy - automatic, manual, or rolling. + UpgradePolicy *UpgradePolicy + + // The list of user Accounts to be created on each Compute Node in the Pool. + UserAccounts []UserAccount + + // The virtual machine configuration for the Pool. This property must be specified. + VirtualMachineConfiguration *VirtualMachineConfiguration +} + +// CreateTaskContent - Parameters for creating an Azure Batch Task. +type CreateTaskContent struct { + // REQUIRED; The command line of the Task. For multi-instance Tasks, the command line is executed as the primary Task, after + // the primary Task and all subtasks have finished executing the coordination command line. The command line does not run + // under a shell, and therefore cannot take advantage of shell features such as environment variable expansion. If you want + // to take advantage of such features, you should invoke the shell in the command line, for example using "cmd /c MyCommand" + // in Windows or "/bin/sh -c MyCommand" in Linux. If the command line refers to file paths, it should use a relative path + // (relative to the Task working directory), or use the Batch provided environment variable (https://learn.microsoft.com/azure/batch/batch-compute-node-environment-variables). + CommandLine *string + + // REQUIRED; A string that uniquely identifies the Task within the Job. The ID can contain any combination of alphanumeric + // characters including hyphens and underscores, and cannot contain more than 64 characters. The ID is case-preserving and + // case-insensitive (that is, you may not have two IDs within a Job that differ only by case). + ID *string + + // A locality hint that can be used by the Batch service to select a Compute Node on which to start the new Task. + AffinityInfo *AffinityInfo + + // A list of Packages that the Batch service will deploy to the Compute Node before running the command line. Application + // packages are downloaded and deployed to a shared directory, not the Task working directory. Therefore, if a referenced + // package is already on the Node, and is up to date, then it is not re-downloaded; the existing copy on the Compute Node + // is used. If a referenced Package cannot be installed, for example because the package has been deleted or because download + // failed, the Task fails. + ApplicationPackageReferences []ApplicationPackageReference + + // The settings for an authentication token that the Task can use to perform Batch service operations. If this property is + // set, the Batch service provides the Task with an authentication token which can be used to authenticate Batch service operations + // without requiring an Account access key. The token is provided via the AZ_BATCH_AUTHENTICATION_TOKEN environment variable. + // The operations that the Task can carry out using the token depend on the settings. For example, a Task can request Job + // permissions in order to add other Tasks to the Job, or check the status of the Job or of other Tasks under the Job. + AuthenticationTokenSettings *AuthenticationTokenSettings + + // The execution constraints that apply to this Task. If you do not specify constraints, the maxTaskRetryCount is the maxTaskRetryCount + // specified for the Job, the maxWallClockTime is infinite, and the retentionTime is 7 days. + Constraints *TaskConstraints + + // The settings for the container under which the Task runs. If the Pool that will run this Task has containerConfiguration + // set, this must be set as well. If the Pool that will run this Task doesn't have containerConfiguration set, this must not + // be set. When this is specified, all directories recursively below the AZ_BATCH_NODE_ROOT_DIR (the root of Azure Batch directories + // on the node) are mapped into the container, all Task environment variables are mapped into the container, and the Task + // command line is executed in the container. Files produced in the container outside of AZ_BATCH_NODE_ROOT_DIR might not + // be reflected to the host disk, meaning that Batch file APIs will not be able to access those files. + ContainerSettings *TaskContainerSettings + + // The Tasks that this Task depends on. This Task will not be scheduled until all Tasks that it depends on have completed + // successfully. If any of those Tasks fail and exhaust their retry counts, this Task will never be scheduled. If the Job + // does not have usesTaskDependencies set to true, and this element is present, the request fails with error code TaskDependenciesNotSpecifiedOnJob. + DependsOn *TaskDependencies + + // A display name for the Task. The display name need not be unique and can contain any Unicode characters up to a maximum + // length of 1024. + DisplayName *string + + // A list of environment variable settings for the Task. + EnvironmentSettings []EnvironmentSetting + + // How the Batch service should respond when the Task completes. + ExitConditions *ExitConditions + + // An object that indicates that the Task is a multi-instance Task, and contains information about how to run the multi-instance + // Task. + MultiInstanceSettings *MultiInstanceSettings + + // A list of files that the Batch service will upload from the Compute Node after running the command line. For multi-instance + // Tasks, the files will only be uploaded from the Compute Node on which the primary Task is executed. + OutputFiles []OutputFile + + // The number of scheduling slots that the Task required to run. The default is 1. A Task can only be scheduled to run on + // a compute node if the node has enough free scheduling slots available. For multi-instance Tasks, this must be 1. + RequiredSlots *int32 + + // A list of files that the Batch service will download to the Compute Node before running the command line. For multi-instance + // Tasks, the resource files will only be downloaded to the Compute Node on which the primary Task is executed. There is a + // maximum size for the list of resource files. When the max size is exceeded, the request will fail and the response error + // code will be RequestEntityTooLarge. If this occurs, the collection of ResourceFiles must be reduced in size. This can be + // achieved using .zip files, Application Packages, or Docker Containers. + ResourceFiles []ResourceFile + + // The user identity under which the Task runs. If omitted, the Task runs as a non-administrative user unique to the Task. + UserIdentity *UserIdentity +} + +// DataDisk - Settings which will be used by the data disks associated to Compute Nodes in +// the Pool. When using attached data disks, you need to mount and format the +// disks from within a VM to use them. +type DataDisk struct { + // REQUIRED; The initial disk size in gigabytes. + DiskSizeGB *int32 + + // REQUIRED; The logical unit number. The logicalUnitNumber is used to uniquely identify each data disk. If attaching multiple + // disks, each should have a distinct logicalUnitNumber. The value must be between 0 and 63, inclusive. + LogicalUnitNumber *int32 + + // The type of caching to be enabled for the data disks. The default value for caching is readwrite. For information about + // the caching options see: https://blogs.msdn.microsoft.com/windowsazurestorage/2012/06/27/exploring-windows-azure-drives-disks-and-images/. + Caching *CachingType + + // The storage Account type to be used for the data disk. If omitted, the default is "standard_lrs". + StorageAccountType *StorageAccountType +} + +// DeallocateNodeContent - Options for deallocating a Compute Node. +type DeallocateNodeContent struct { + // When to deallocate the Compute Node and what to do with currently running Tasks. The default value is requeue. + NodeDeallocateOption *NodeDeallocateOption +} + +// DeleteCertificateError - An error encountered by the Batch service when deleting a Certificate. +type DeleteCertificateError struct { + // An identifier for the Certificate deletion error. Codes are invariant and are intended to be consumed programmatically. + Code *string + + // A message describing the Certificate deletion error, intended to be suitable for display in a user interface. + Message *string + + // A list of additional error details related to the Certificate deletion error. This list includes details such as the active + // Pools and Compute Nodes referencing this Certificate. However, if a large number of resources reference the Certificate, + // the list contains only about the first hundred. + Values []NameValuePair +} + +// DiffDiskSettings - Specifies the ephemeral Disk Settings for the operating system disk used by the +// compute node (VM). +type DiffDiskSettings struct { + // Specifies the ephemeral disk placement for operating system disk for all VMs in the pool. This property can be used by + // user in the request to choose the location e.g., cache disk space for Ephemeral OS disk provisioning. For more information + // on Ephemeral OS disk size requirements, please refer to Ephemeral OS disk size requirements for Windows VMs at https://learn.microsoft.com/azure/virtual-machines/windows/ephemeral-os-disks#size-requirements + // and Linux VMs at https://learn.microsoft.com/azure/virtual-machines/linux/ephemeral-os-disks#size-requirements. + Placement *DiffDiskPlacement +} + +// DisableJobContent - Parameters for disabling an Azure Batch Job. +type DisableJobContent struct { + // REQUIRED; What to do with active Tasks associated with the Job. + DisableTasks *DisableJobOption +} + +// DisableNodeSchedulingContent - Parameters for disabling scheduling on an Azure Batch Compute Node. +type DisableNodeSchedulingContent struct { + // What to do with currently running Tasks when disabling Task scheduling on the Compute Node. The default value is requeue. + NodeDisableSchedulingOption *NodeDisableSchedulingOption +} + +// DiskEncryptionConfiguration - The disk encryption configuration applied on compute nodes in the pool. +// Disk encryption configuration is not supported on Linux pool created with +// Azure Compute Gallery Image. +type DiskEncryptionConfiguration struct { + // The list of disk targets Batch Service will encrypt on the compute node. The list of disk targets Batch Service will encrypt + // on the compute node. + Targets []DiskEncryptionTarget +} + +// EnablePoolAutoScaleContent - Parameters for enabling automatic scaling on an Azure Batch Pool. +type EnablePoolAutoScaleContent struct { + // The time interval at which to automatically adjust the Pool size according to the autoscale formula. The default value + // is 15 minutes. The minimum and maximum value are 5 minutes and 168 hours respectively. If you specify a value less than + // 5 minutes or greater than 168 hours, the Batch service rejects the request with an invalid property value error; if you + // are calling the REST API directly, the HTTP status code is 400 (Bad Request). If you specify a new interval, then the existing + // autoscale evaluation schedule will be stopped and a new autoscale evaluation schedule will be started, with its starting + // time being the time when this request was issued. + AutoScaleEvaluationInterval *string + + // The formula for the desired number of Compute Nodes in the Pool. The default value is 15 minutes. The minimum and maximum + // value are 5 minutes and 168 hours respectively. If you specify a value less than 5 minutes or greater than 168 hours, the + // Batch service rejects the request with an invalid property value error; if you are calling the REST API directly, the HTTP + // status code is 400 (Bad Request). If you specify a new interval, then the existing autoscale evaluation schedule will be + // stopped and a new autoscale evaluation schedule will be started, with its starting time being the time when this request + // was issued. + AutoScaleFormula *string +} + +// EnvironmentSetting - An environment variable to be set on a Task process. +type EnvironmentSetting struct { + // REQUIRED; The name of the environment variable. + Name *string + + // The value of the environment variable. + Value *string +} + +// Error - An error response received from the Azure Batch service. +type Error struct { + // REQUIRED; An identifier for the error. Codes are invariant and are intended to be consumed programmatically. + Code *string + + // A message describing the error, intended to be suitable for display in a user interface. + Message *ErrorMessage + + // A collection of key-value pairs containing additional details about the error. + Values []ErrorDetail +} + +// ErrorDetail - An item of additional information included in an Azure Batch error response. +type ErrorDetail struct { + // An identifier specifying the meaning of the Value property. + Key *string + + // The additional information included with the error response. + Value *string +} + +// ErrorMessage - An error message received in an Azure Batch error response. +type ErrorMessage struct { + // The language code of the error message. + Lang *string + + // The text of the message. + Value *string +} + +// EvaluatePoolAutoScaleContent - Parameters for evaluating an automatic scaling formula on an Azure Batch Pool. +type EvaluatePoolAutoScaleContent struct { + // REQUIRED; The formula for the desired number of Compute Nodes in the Pool. The formula is validated and its results calculated, + // but it is not applied to the Pool. To apply the formula to the Pool, 'Enable automatic scaling on a Pool'. For more information + // about specifying this formula, see Automatically scale Compute Nodes in an Azure Batch Pool (https://learn.microsoft.com/azure/batch/batch-automatic-scaling). + AutoScaleFormula *string +} + +// ExitCodeMapping - How the Batch service should respond if a Task exits with a particular exit +// code. +type ExitCodeMapping struct { + // REQUIRED; A process exit code. + Code *int32 + + // REQUIRED; How the Batch service should respond if the Task exits with this exit code. + ExitOptions *ExitOptions +} + +// ExitCodeRangeMapping - A range of exit codes and how the Batch service should respond to exit codes +// within that range. +type ExitCodeRangeMapping struct { + // REQUIRED; The last exit code in the range. + End *int32 + + // REQUIRED; How the Batch service should respond if the Task exits with an exit code in the range start to end (inclusive). + ExitOptions *ExitOptions + + // REQUIRED; The first exit code in the range. + Start *int32 +} + +// ExitConditions - Specifies how the Batch service should respond when the Task completes. +type ExitConditions struct { + // How the Batch service should respond if the Task fails with an exit condition not covered by any of the other properties. + // This value is used if the Task exits with any nonzero exit code not listed in the exitCodes or exitCodeRanges collection, + // with a pre-processing error if the preProcessingError property is not present, or with a file upload error if the fileUploadError + // property is not present. If you want non-default behavior on exit code 0, you must list it explicitly using the exitCodes + // or exitCodeRanges collection. + Default *ExitOptions + + // A list of Task exit code ranges and how the Batch service should respond to them. + ExitCodeRanges []ExitCodeRangeMapping + + // A list of individual Task exit codes and how the Batch service should respond to them. + ExitCodes []ExitCodeMapping + + // How the Batch service should respond if a file upload error occurs. If the Task exited with an exit code that was specified + // via exitCodes or exitCodeRanges, and then encountered a file upload error, then the action specified by the exit code takes + // precedence. + FileUploadError *ExitOptions + + // How the Batch service should respond if the Task fails to start due to an error. + PreProcessingError *ExitOptions +} + +// ExitOptions - Specifies how the Batch service responds to a particular exit condition. +type ExitOptions struct { + // An action that the Batch service performs on Tasks that depend on this Task. Possible values are 'satisfy' (allowing dependent + // tasks to progress) and 'block' (dependent tasks continue to wait). Batch does not yet support cancellation of dependent + // tasks. + DependencyAction *DependencyAction + + // An action to take on the Job containing the Task, if the Task completes with the given exit condition and the Job's onTaskFailed + // property is 'performExitOptionsJobAction'. The default is none for exit code 0 and terminate for all other exit conditions. + // If the Job's onTaskFailed property is noaction, then specifying this property returns an error and the add Task request + // fails with an invalid property value error; if you are calling the REST API directly, the HTTP status code is 400 (Bad + // Request). + JobAction *JobAction +} + +// FileProperties - The properties of a file on a Compute Node. +type FileProperties struct { + // REQUIRED; The length of the file. + ContentLength *int64 + + // REQUIRED; The time at which the file was last modified. + LastModified *time.Time + + // The content type of the file. + ContentType *string + + // The file creation time. The creation time is not returned for files on Linux Compute Nodes. + CreationTime *time.Time + + // The file mode attribute in octal format. The file mode is returned only for files on Linux Compute Nodes. + FileMode *string +} + +// HTTPHeader - An HTTP header name-value pair +type HTTPHeader struct { + // REQUIRED; The case-insensitive name of the header to be used while uploading output files. + Name *string + + // The value of the header to be used while uploading output files. + Value *string +} + +// ImageReference - A reference to an Azure Virtual Machines Marketplace Image or a Azure Compute Gallery Image. +// To get the list of all Azure Marketplace Image references verified by Azure Batch, see the +// ' List Supported Images ' operation. +type ImageReference struct { + // The community gallery image unique identifier. This property is mutually exclusive with other properties and can be fetched + // from community gallery image GET call. + CommunityGalleryImageID *string + + // The offer type of the Azure Virtual Machines Marketplace Image. For example, UbuntuServer or WindowsServer. + Offer *string + + // The publisher of the Azure Virtual Machines Marketplace Image. For example, Canonical or MicrosoftWindowsServer. + Publisher *string + + // The SKU of the Azure Virtual Machines Marketplace Image. For example, 18.04-LTS or 2019-Datacenter. + SKU *string + + // The shared gallery image unique identifier. This property is mutually exclusive with other properties and can be fetched + // from shared gallery image GET call. + SharedGalleryImageID *string + + // The version of the Azure Virtual Machines Marketplace Image. A value of 'latest' can be specified to select the latest + // version of an Image. If omitted, the default is 'latest'. + Version *string + + // The ARM resource identifier of the Azure Compute Gallery Image. Compute Nodes in the Pool will be created using this Image + // Id. This is of the form /subscriptions/{subscriptionId}/resourceGroups/{resourceGroup}/providers/Microsoft.Compute/galleries/{galleryName}/images/{imageDefinitionName}/versions/{VersionId} + // or /subscriptions/{subscriptionId}/resourceGroups/{resourceGroup}/providers/Microsoft.Compute/galleries/{galleryName}/images/{imageDefinitionName} + // for always defaulting to the latest image version. This property is mutually exclusive with other ImageReference properties. + // The Azure Compute Gallery Image must have replicas in the same region and must be in the same subscription as the Azure + // Batch account. If the image version is not specified in the imageId, the latest version will be used. For information about + // the firewall settings for the Batch Compute Node agent to communicate with the Batch service see https://learn.microsoft.com/azure/batch/nodes-and-pools#virtual-network-vnet-and-firewall-configuration. + VirtualMachineImageID *string + + // READ-ONLY; The specific version of the platform image or marketplace image used to create the node. This read-only field + // differs from 'version' only if the value specified for 'version' when the pool was created was 'latest'. + ExactVersion *string +} + +// InboundEndpoint - An inbound endpoint on a Compute Node. +type InboundEndpoint struct { + // REQUIRED; The backend port number of the endpoint. + BackendPort *int32 + + // REQUIRED; The public port number of the endpoint. + FrontendPort *int32 + + // REQUIRED; The name of the endpoint. + Name *string + + // REQUIRED; The protocol of the endpoint. + Protocol *InboundEndpointProtocol + + // REQUIRED; The public fully qualified domain name for the Compute Node. + PublicFQDN *string + + // REQUIRED; The public IP address of the Compute Node. + PublicIPAddress *string +} + +// InboundNATPool - A inbound NAT Pool that can be used to address specific ports on Compute Nodes +// in a Batch Pool externally. +type InboundNATPool struct { + // REQUIRED; The port number on the Compute Node. This must be unique within a Batch Pool. Acceptable values are between 1 + // and 65535 except for 29876 and 29877 as these are reserved. If any reserved values are provided the request fails with + // HTTP status code 400. + BackendPort *int32 + + // REQUIRED; The last port number in the range of external ports that will be used to provide inbound access to the backendPort + // on individual Compute Nodes. Acceptable values range between 1 and 65534 except ports from 50000 to 55000 which are reserved + // by the Batch service. All ranges within a Pool must be distinct and cannot overlap. Each range must contain at least 40 + // ports. If any reserved or overlapping values are provided the request fails with HTTP status code 400. + FrontendPortRangeEnd *int32 + + // REQUIRED; The first port number in the range of external ports that will be used to provide inbound access to the backendPort + // on individual Compute Nodes. Acceptable values range between 1 and 65534 except ports from 50000 to 55000 which are reserved. + // All ranges within a Pool must be distinct and cannot overlap. Each range must contain at least 40 ports. If any reserved + // or overlapping values are provided the request fails with HTTP status code 400. + FrontendPortRangeStart *int32 + + // REQUIRED; The name of the endpoint. The name must be unique within a Batch Pool, can contain letters, numbers, underscores, + // periods, and hyphens. Names must start with a letter or number, must end with a letter, number, or underscore, and cannot + // exceed 77 characters. If any invalid values are provided the request fails with HTTP status code 400. + Name *string + + // REQUIRED; The protocol of the endpoint. + Protocol *InboundEndpointProtocol + + // A list of network security group rules that will be applied to the endpoint. The maximum number of rules that can be specified + // across all the endpoints on a Batch Pool is 25. If no network security group rules are specified, a default rule will be + // created to allow inbound access to the specified backendPort. If the maximum number of network security group rules is + // exceeded the request fails with HTTP status code 400. + NetworkSecurityGroupRules []NetworkSecurityGroupRule +} + +// InstanceViewStatus - The instance view status. +type InstanceViewStatus struct { + // The status code. + Code *string + + // The localized label for the status. + DisplayStatus *string + + // Level code. + Level *StatusLevelTypes + + // The detailed status message. + Message *string + + // The time of the status. + Time *time.Time +} + +// Job - An Azure Batch Job. +type Job struct { + // REQUIRED; The Pool settings associated with the Job. + PoolInfo *PoolInfo + + // Whether Tasks in this job can be preempted by other high priority jobs. If the value is set to True, other high priority + // jobs submitted to the system will take precedence and will be able requeue tasks from this job. You can update a job's + // allowTaskPreemption after it has been created using the update job API. + AllowTaskPreemption *bool + + // The execution constraints for the Job. + Constraints *JobConstraints + + // The maximum number of tasks that can be executed in parallel for the job. The value of maxParallelTasks must be -1 or greater + // than 0 if specified. If not specified, the default value is -1, which means there's no limit to the number of tasks that + // can be run at once. You can update a job's maxParallelTasks after it has been created using the update job API. + MaxParallelTasks *int32 + + // A list of name-value pairs associated with the Job as metadata. The Batch service does not assign any meaning to metadata; + // it is solely for the use of user code. + Metadata []MetadataItem + + // The action the Batch service should take when all Tasks in the Job are in the completed state. The default is noaction. + OnAllTasksComplete *OnAllTasksComplete + + // The priority of the Job. Priority values can range from -1000 to 1000, with -1000 being the lowest priority and 1000 being + // the highest priority. The default value is 0. + Priority *int32 + + // READ-ONLY; The list of common environment variable settings. These environment variables are set for all Tasks in the Job + // (including the Job Manager, Job Preparation and Job Release Tasks). Individual Tasks can override an environment setting + // specified here by specifying the same setting name with a different value. + CommonEnvironmentSettings []EnvironmentSetting + + // READ-ONLY; The creation time of the Job. + CreationTime *time.Time + + // READ-ONLY; The display name for the Job. + DisplayName *string + + // READ-ONLY; The ETag of the Job. This is an opaque string. You can use it to detect whether the Job has changed between + // requests. In particular, you can be pass the ETag when updating a Job to specify that your changes should take effect only + // if nobody else has modified the Job in the meantime. + ETag *string + + // READ-ONLY; The execution information for the Job. + ExecutionInfo *JobExecutionInfo + + // READ-ONLY; A string that uniquely identifies the Job within the Account. The ID is case-preserving and case-insensitive + // (that is, you may not have two IDs within an Account that differ only by case). + ID *string + + // READ-ONLY; Details of a Job Manager Task to be launched when the Job is started. + JobManagerTask *JobManagerTask + + // READ-ONLY; The Job Preparation Task. The Job Preparation Task is a special Task run on each Compute Node before any other + // Task of the Job. + JobPreparationTask *JobPreparationTask + + // READ-ONLY; The Job Release Task. The Job Release Task is a special Task run at the end of the Job on each Compute Node + // that has run any other Task of the Job. + JobReleaseTask *JobReleaseTask + + // READ-ONLY; The last modified time of the Job. This is the last time at which the Job level data, such as the Job state + // or priority, changed. It does not factor in task-level changes such as adding new Tasks or Tasks changing state. + LastModified *time.Time + + // READ-ONLY; The network configuration for the Job. + NetworkConfiguration *JobNetworkConfiguration + + // READ-ONLY; The action the Batch service should take when any Task in the Job fails. A Task is considered to have failed + // if has a failureInfo. A failureInfo is set if the Task completes with a non-zero exit code after exhausting its retry count, + // or if there was an error starting the Task, for example due to a resource file download error. The default is noaction. + OnTaskFailure *OnTaskFailure + + // READ-ONLY; The previous state of the Job. This property is not set if the Job is in its initial Active state. + PreviousState *JobState + + // READ-ONLY; The time at which the Job entered its previous state. This property is not set if the Job is in its initial + // Active state. + PreviousStateTransitionTime *time.Time + + // READ-ONLY; The current state of the Job. + State *JobState + + // READ-ONLY; The time at which the Job entered its current state. + StateTransitionTime *time.Time + + // READ-ONLY; Resource usage statistics for the entire lifetime of the Job. This property is populated only if the BatchJob + // was retrieved with an expand clause including the 'stats' attribute; otherwise it is null. The statistics may not be immediately + // available. The Batch service performs periodic roll-up of statistics. The typical delay is about 30 minutes. + Stats *JobStatistics + + // READ-ONLY; The URL of the Job. + URL *string + + // READ-ONLY; Whether Tasks in the Job can define dependencies on each other. The default is false. + UsesTaskDependencies *bool +} + +// JobConstraints - The execution constraints for a Job. +type JobConstraints struct { + // The maximum number of times each Task may be retried. The Batch service retries a Task if its exit code is nonzero. Note + // that this value specifically controls the number of retries. The Batch service will try each Task once, and may then retry + // up to this limit. For example, if the maximum retry count is 3, Batch tries a Task up to 4 times (one initial try and 3 + // retries). If the maximum retry count is 0, the Batch service does not retry Tasks. If the maximum retry count is -1, the + // Batch service retries Tasks without limit. The default value is 0 (no retries). + MaxTaskRetryCount *int32 + + // The maximum elapsed time that the Job may run, measured from the time the Job is created. If the Job does not complete + // within the time limit, the Batch service terminates it and any Tasks that are still running. In this case, the termination + // reason will be MaxWallClockTimeExpiry. If this property is not specified, there is no time limit on how long the Job may + // run. + MaxWallClockTime *string +} + +// JobExecutionInfo - Contains information about the execution of a Job in the Azure Batch service. +type JobExecutionInfo struct { + // REQUIRED; The start time of the Job. This is the time at which the Job was created. + StartTime *time.Time + + // The completion time of the Job. This property is set only if the Job is in the completed state. + EndTime *time.Time + + // The ID of the Pool to which this Job is assigned. This element contains the actual Pool where the Job is assigned. When + // you get Job details from the service, they also contain a poolInfo element, which contains the Pool configuration data + // from when the Job was added or updated. That poolInfo element may also contain a poolId element. If it does, the two IDs + // are the same. If it does not, it means the Job ran on an auto Pool, and this property contains the ID of that auto Pool. + PoolID *string + + // Details of any error encountered by the service in starting the Job. This property is not set if there was no error starting + // the Job. + SchedulingError *JobSchedulingError + + // A string describing the reason the Job ended. This property is set only if the Job is in the completed state. If the Batch + // service terminates the Job, it sets the reason as follows: JMComplete - the Job Manager Task completed, and killJobOnCompletion + // was set to true. MaxWallClockTimeExpiry - the Job reached its maxWallClockTime constraint. TerminateJobSchedule - the Job + // ran as part of a schedule, and the schedule terminated. AllTasksComplete - the Job's onAllTasksComplete attribute is set + // to terminatejob, and all Tasks in the Job are complete. TaskFailed - the Job's onTaskFailure attribute is set to performExitOptionsJobAction, + // and a Task in the Job failed with an exit condition that specified a jobAction of terminatejob. Any other string is a user-defined + // reason specified in a call to the 'Terminate a Job' operation. + TerminationReason *string +} + +// JobListResult - The result of listing the Jobs in an Account. +type JobListResult struct { + // The URL to get the next set of results. + NextLink *string + + // The list of Jobs. + Value []Job +} + +// JobManagerTask - Specifies details of a Job Manager Task. +// The Job Manager Task is automatically started when the Job is created. The +// Batch service tries to schedule the Job Manager Task before any other Tasks in +// the Job. When shrinking a Pool, the Batch service tries to preserve Nodes where +// Job Manager Tasks are running for as long as possible (that is, Compute Nodes +// running 'normal' Tasks are removed before Compute Nodes running Job Manager +// Tasks). When a Job Manager Task fails and needs to be restarted, the system +// tries to schedule it at the highest priority. If there are no idle Compute +// Nodes available, the system may terminate one of the running Tasks in the Pool +// and return it to the queue in order to make room for the Job Manager Task to +// restart. Note that a Job Manager Task in one Job does not have priority over +// Tasks in other Jobs. Across Jobs, only Job level priorities are observed. For +// example, if a Job Manager in a priority 0 Job needs to be restarted, it will +// not displace Tasks of a priority 1 Job. Batch will retry Tasks when a recovery +// operation is triggered on a Node. Examples of recovery operations include (but +// are not limited to) when an unhealthy Node is rebooted or a Compute Node +// disappeared due to host failure. Retries due to recovery operations are +// independent of and are not counted against the maxTaskRetryCount. Even if the +// maxTaskRetryCount is 0, an internal retry due to a recovery operation may +// occur. Because of this, all Tasks should be idempotent. This means Tasks need +// to tolerate being interrupted and restarted without causing any corruption or +// duplicate data. The best practice for long running Tasks is to use some form of +// checkpointing. +type JobManagerTask struct { + // REQUIRED; The command line of the Job Manager Task. The command line does not run under a shell, and therefore cannot take + // advantage of shell features such as environment variable expansion. If you want to take advantage of such features, you + // should invoke the shell in the command line, for example using "cmd /c MyCommand" in Windows or "/bin/sh -c MyCommand" + // in Linux. If the command line refers to file paths, it should use a relative path (relative to the Task working directory), + // or use the Batch provided environment variable (https://learn.microsoft.com/azure/batch/batch-compute-node-environment-variables). + CommandLine *string + + // REQUIRED; A string that uniquely identifies the Job Manager Task within the Job. The ID can contain any combination of + // alphanumeric characters including hyphens and underscores and cannot contain more than 64 characters. + ID *string + + // Whether the Job Manager Task may run on a Spot/Low-priority Compute Node. The default value is true. + AllowLowPriorityNode *bool + + // A list of Application Packages that the Batch service will deploy to the + // Compute Node before running the command line.Application Packages are + // downloaded and deployed to a shared directory, not the Task working + // directory. Therefore, if a referenced Application Package is already + // on the Compute Node, and is up to date, then it is not re-downloaded; + // the existing copy on the Compute Node is used. If a referenced Application + // Package cannot be installed, for example because the package has been deleted + // or because download failed, the Task fails. + ApplicationPackageReferences []ApplicationPackageReference + + // The settings for an authentication token that the Task can use to perform Batch service operations. If this property is + // set, the Batch service provides the Task with an authentication token which can be used to authenticate Batch service operations + // without requiring an Account access key. The token is provided via the AZ_BATCH_AUTHENTICATION_TOKEN environment variable. + // The operations that the Task can carry out using the token depend on the settings. For example, a Task can request Job + // permissions in order to add other Tasks to the Job, or check the status of the Job or of other Tasks under the Job. + AuthenticationTokenSettings *AuthenticationTokenSettings + + // Constraints that apply to the Job Manager Task. + Constraints *TaskConstraints + + // The settings for the container under which the Job Manager Task runs. If the Pool that will run this Task has containerConfiguration + // set, this must be set as well. If the Pool that will run this Task doesn't have containerConfiguration set, this must not + // be set. When this is specified, all directories recursively below the AZ_BATCH_NODE_ROOT_DIR (the root of Azure Batch directories + // on the node) are mapped into the container, all Task environment variables are mapped into the container, and the Task + // command line is executed in the container. Files produced in the container outside of AZ_BATCH_NODE_ROOT_DIR might not + // be reflected to the host disk, meaning that Batch file APIs will not be able to access those files. + ContainerSettings *TaskContainerSettings + + // The display name of the Job Manager Task. It need not be unique and can contain any Unicode characters up to a maximum + // length of 1024. + DisplayName *string + + // A list of environment variable settings for the Job Manager Task. + EnvironmentSettings []EnvironmentSetting + + // Whether completion of the Job Manager Task signifies completion of the entire Job. If true, when the Job Manager Task completes, + // the Batch service marks the Job as complete. If any Tasks are still running at this time (other than Job Release), those + // Tasks are terminated. If false, the completion of the Job Manager Task does not affect the Job status. In this case, you + // should either use the onAllTasksComplete attribute to terminate the Job, or have a client or user terminate the Job explicitly. + // An example of this is if the Job Manager creates a set of Tasks but then takes no further role in their execution. The + // default value is true. If you are using the onAllTasksComplete and onTaskFailure attributes to control Job lifetime, and + // using the Job Manager Task only to create the Tasks for the Job (not to monitor progress), then it is important to set + // killJobOnCompletion to false. + KillJobOnCompletion *bool + + // A list of files that the Batch service will upload from the Compute Node after running the command line. For multi-instance + // Tasks, the files will only be uploaded from the Compute Node on which the primary Task is executed. + OutputFiles []OutputFile + + // The number of scheduling slots that the Task requires to run. The default is 1. A Task can only be scheduled to run on + // a compute node if the node has enough free scheduling slots available. For multi-instance Tasks, this property is not supported + // and must not be specified. + RequiredSlots *int32 + + // A list of files that the Batch service will download to the Compute Node before running the command line. Files listed + // under this element are located in the Task's working directory. There is a maximum size for the list of resource files. + // When the max size is exceeded, the request will fail and the response error code will be RequestEntityTooLarge. If this + // occurs, the collection of ResourceFiles must be reduced in size. This can be achieved using .zip files, Application Packages, + // or Docker Containers. + ResourceFiles []ResourceFile + + // Whether the Job Manager Task requires exclusive use of the Compute Node where it runs. If true, no other Tasks will run + // on the same Node for as long as the Job Manager is running. If false, other Tasks can run simultaneously with the Job Manager + // on a Compute Node. The Job Manager Task counts normally against the Compute Node's concurrent Task limit, so this is only + // relevant if the Compute Node allows multiple concurrent Tasks. The default value is true. + RunExclusive *bool + + // The user identity under which the Job Manager Task runs. If omitted, the Task runs as a non-administrative user unique + // to the Task. + UserIdentity *UserIdentity +} + +// JobNetworkConfiguration - The network configuration for the Job. +type JobNetworkConfiguration struct { + // REQUIRED; Whether to withdraw Compute Nodes from the virtual network to DNC when the job is terminated or deleted. If true, + // nodes will remain joined to the virtual network to DNC. If false, nodes will automatically withdraw when the job ends. + // Defaults to false. + SkipWithdrawFromVNet *bool + + // REQUIRED; The ARM resource identifier of the virtual network subnet which Compute Nodes running Tasks from the Job will + // join for the duration of the Task. The virtual network must be in the same region and subscription as the Azure Batch Account. + // The specified subnet should have enough free IP addresses to accommodate the number of Compute Nodes which will run Tasks + // from the Job. This can be up to the number of Compute Nodes in the Pool. The 'MicrosoftAzureBatch' service principal must + // have the 'Classic Virtual Machine Contributor' Role-Based Access Control (RBAC) role for the specified VNet so that Azure + // Batch service can schedule Tasks on the Nodes. This can be verified by checking if the specified VNet has any associated + // Network Security Groups (NSG). If communication to the Nodes in the specified subnet is denied by an NSG, then the Batch + // service will set the state of the Compute Nodes to unusable. This is of the form /subscriptions/{subscription}/resourceGroups/{group}/providers/{provider}/virtualNetworks/{network}/subnets/{subnet}. + // If the specified VNet has any associated Network Security Groups (NSG), then a few reserved system ports must be enabled + // for inbound communication from the Azure Batch service. For Pools created with a Virtual Machine configuration, enable + // ports 29876 and 29877, as well as port 22 for Linux and port 3389 for Windows. Port 443 is also required to be open for + // outbound connections for communications to Azure Storage. For more details see: https://learn.microsoft.com/azure/batch/batch-api-basics#virtual-network-vnet-and-firewall-configuration. + SubnetID *string +} + +// JobPreparationAndReleaseTaskStatus - The status of the Job Preparation and Job Release Tasks on a Compute Node. +type JobPreparationAndReleaseTaskStatus struct { + // Information about the execution status of the Job Preparation Task on this Compute Node. + JobPreparationTaskExecutionInfo *JobPreparationTaskExecutionInfo + + // Information about the execution status of the Job Release Task on this Compute Node. This property is set only if the Job + // Release Task has run on the Compute Node. + JobReleaseTaskExecutionInfo *JobReleaseTaskExecutionInfo + + // The ID of the Compute Node to which this entry refers. + NodeID *string + + // The URL of the Compute Node to which this entry refers. + NodeURL *string + + // The ID of the Pool containing the Compute Node to which this entry refers. + PoolID *string +} + +// JobPreparationAndReleaseTaskStatusListResult - The result of listing the status of the Job Preparation and Job Release +// Tasks +// for a Job. +type JobPreparationAndReleaseTaskStatusListResult struct { + // The URL to get the next set of results. + NextLink *string + + // A list of Job Preparation and Job Release Task execution information. + Value []JobPreparationAndReleaseTaskStatus +} + +// JobPreparationTask - A Job Preparation Task to run before any Tasks of the Job on any given Compute Node. +// You can use Job Preparation to prepare a Node to run Tasks for the Job. +// Activities commonly performed in Job Preparation include: Downloading common +// resource files used by all the Tasks in the Job. The Job Preparation Task can +// download these common resource files to the shared location on the Node. +// (AZ_BATCH_NODE_ROOT_DIR\shared), or starting a local service on the Node so +// that all Tasks of that Job can communicate with it. If the Job Preparation Task +// fails (that is, exhausts its retry count before exiting with exit code 0), +// Batch will not run Tasks of this Job on the Node. The Compute Node remains +// ineligible to run Tasks of this Job until it is reimaged. The Compute Node +// remains active and can be used for other Jobs. The Job Preparation Task can run +// multiple times on the same Node. Therefore, you should write the Job +// Preparation Task to handle re-execution. If the Node is rebooted, the Job +// Preparation Task is run again on the Compute Node before scheduling any other +// Task of the Job, if rerunOnNodeRebootAfterSuccess is true or if the Job +// Preparation Task did not previously complete. If the Node is reimaged, the Job +// Preparation Task is run again before scheduling any Task of the Job. Batch will +// retry Tasks when a recovery operation is triggered on a Node. Examples of +// recovery operations include (but are not limited to) when an unhealthy Node is +// rebooted or a Compute Node disappeared due to host failure. Retries due to +// recovery operations are independent of and are not counted against the +// maxTaskRetryCount. Even if the maxTaskRetryCount is 0, an internal retry due to +// a recovery operation may occur. Because of this, all Tasks should be +// idempotent. This means Tasks need to tolerate being interrupted and restarted +// without causing any corruption or duplicate data. The best practice for long +// running Tasks is to use some form of checkpointing. +type JobPreparationTask struct { + // REQUIRED; The command line of the Job Preparation Task. The command line does not run under a shell, and therefore cannot + // take advantage of shell features such as environment variable expansion. If you want to take advantage of such features, + // you should invoke the shell in the command line, for example using "cmd /c MyCommand" in Windows or "/bin/sh -c MyCommand" + // in Linux. If the command line refers to file paths, it should use a relative path (relative to the Task working directory), + // or use the Batch provided environment variable (https://learn.microsoft.com/azure/batch/batch-compute-node-environment-variables). + CommandLine *string + + // Constraints that apply to the Job Preparation Task. + Constraints *TaskConstraints + + // The settings for the container under which the Job Preparation Task runs. When this is specified, all directories recursively + // below the AZ_BATCH_NODE_ROOT_DIR (the root of Azure Batch directories on the node) are mapped into the container, all Task + // environment variables are mapped into the container, and the Task command line is executed in the container. Files produced + // in the container outside of AZ_BATCH_NODE_ROOT_DIR might not be reflected to the host disk, meaning that Batch file APIs + // will not be able to access those files. + ContainerSettings *TaskContainerSettings + + // A list of environment variable settings for the Job Preparation Task. + EnvironmentSettings []EnvironmentSetting + + // A string that uniquely identifies the Job Preparation Task within the Job. The ID can contain any combination of alphanumeric + // characters including hyphens and underscores and cannot contain more than 64 characters. If you do not specify this property, + // the Batch service assigns a default value of 'jobpreparation'. No other Task in the Job can have the same ID as the Job + // Preparation Task. If you try to submit a Task with the same id, the Batch service rejects the request with error code TaskIdSameAsJobPreparationTask; + // if you are calling the REST API directly, the HTTP status code is 409 (Conflict). + ID *string + + // Whether the Batch service should rerun the Job Preparation Task after a Compute Node reboots. The Job Preparation Task + // is always rerun if a Compute Node is reimaged, or if the Job Preparation Task did not complete (e.g. because the reboot + // occurred while the Task was running). Therefore, you should always write a Job Preparation Task to be idempotent and to + // behave correctly if run multiple times. The default value is true. + RerunOnNodeRebootAfterSuccess *bool + + // A list of files that the Batch service will download to the Compute Node before running the command line. Files listed + // under this element are located in the Task's working directory. There is a maximum size for the list of resource files. + // When the max size is exceeded, the request will fail and the response error code will be RequestEntityTooLarge. If this + // occurs, the collection of ResourceFiles must be reduced in size. This can be achieved using .zip files, Application Packages, + // or Docker Containers. + ResourceFiles []ResourceFile + + // The user identity under which the Job Preparation Task runs. If omitted, the Task runs as a non-administrative user unique + // to the Task on Windows Compute Nodes, or a non-administrative user unique to the Pool on Linux Compute Nodes. + UserIdentity *UserIdentity + + // Whether the Batch service should wait for the Job Preparation Task to complete successfully before scheduling any other + // Tasks of the Job on the Compute Node. A Job Preparation Task has completed successfully if it exits with exit code 0. If + // true and the Job Preparation Task fails on a Node, the Batch service retries the Job Preparation Task up to its maximum + // retry count (as specified in the constraints element). If the Task has still not completed successfully after all retries, + // then the Batch service will not schedule Tasks of the Job to the Node. The Node remains active and eligible to run Tasks + // of other Jobs. If false, the Batch service will not wait for the Job Preparation Task to complete. In this case, other + // Tasks of the Job can start executing on the Compute Node while the Job Preparation Task is still running; and even if the + // Job Preparation Task fails, new Tasks will continue to be scheduled on the Compute Node. The default value is true. + WaitForSuccess *bool +} + +// JobPreparationTaskExecutionInfo - Contains information about the execution of a Job Preparation Task on a Compute +// Node. +type JobPreparationTaskExecutionInfo struct { + // REQUIRED; The number of times the Task has been retried by the Batch service. Task application failures (non-zero exit + // code) are retried, pre-processing errors (the Task could not be run) and file upload errors are not retried. The Batch + // service will retry the Task up to the limit specified by the constraints. Task application failures (non-zero exit code) + // are retried, pre-processing errors (the Task could not be run) and file upload errors are not retried. The Batch service + // will retry the Task up to the limit specified by the constraints. + RetryCount *int32 + + // REQUIRED; The time at which the Task started running. If the Task has been restarted or retried, this is the most recent + // time at which the Task started running. + StartTime *time.Time + + // REQUIRED; The current state of the Job Preparation Task on the Compute Node. + State *JobPreparationTaskState + + // Information about the container under which the Task is executing. This property is set only if the Task runs in a container + // context. + ContainerInfo *TaskContainerExecutionInfo + + // The time at which the Job Preparation Task completed. This property is set only if the Task is in the Completed state. + EndTime *time.Time + + // The exit code of the program specified on the Task command line. This parameter is returned only if the Task is in the + // completed state. The exit code for a process reflects the specific convention implemented by the application developer + // for that process. If you use the exit code value to make decisions in your code, be sure that you know the exit code convention + // used by the application process. Note that the exit code may also be generated by the Compute Node operating system, such + // as when a process is forcibly terminated. + ExitCode *int32 + + // Information describing the Task failure, if any. This property is set only if the Task is in the completed state and encountered + // a failure. + FailureInfo *TaskFailureInfo + + // The most recent time at which a retry of the Job Preparation Task started running. This property is set only if the Task + // was retried (i.e. retryCount is nonzero). If present, this is typically the same as startTime, but may be different if + // the Task has been restarted for reasons other than retry; for example, if the Compute Node was rebooted during a retry, + // then the startTime is updated but the lastRetryTime is not. + LastRetryTime *time.Time + + // The result of the Task execution. If the value is 'failed', then the details of the failure can be found in the failureInfo + // property. + Result *TaskExecutionResult + + // The root directory of the Job Preparation Task on the Compute Node. You can use this path to retrieve files created by + // the Task, such as log files. + TaskRootDirectory *string + + // The URL to the root directory of the Job Preparation Task on the Compute Node. + TaskRootDirectoryURL *string +} + +// JobReleaseTask - A Job Release Task to run on Job completion on any Compute Node where the Job has run. +// The Job Release Task runs when the Job ends, because of one of the following: +// The user calls the Terminate Job API, or the Delete Job API while the Job is +// still active, the Job's maximum wall clock time constraint is reached, and the +// Job is still active, or the Job's Job Manager Task completed, and the Job is +// configured to terminate when the Job Manager completes. The Job Release Task +// runs on each Node where Tasks of the Job have run and the Job Preparation Task +// ran and completed. If you reimage a Node after it has run the Job Preparation +// Task, and the Job ends without any further Tasks of the Job running on that +// Node (and hence the Job Preparation Task does not re-run), then the Job Release +// Task does not run on that Compute Node. If a Node reboots while the Job Release +// Task is still running, the Job Release Task runs again when the Compute Node +// starts up. The Job is not marked as complete until all Job Release Tasks have +// completed. The Job Release Task runs in the background. It does not occupy a +// scheduling slot; that is, it does not count towards the taskSlotsPerNode limit +// specified on the Pool. +type JobReleaseTask struct { + // REQUIRED; The command line of the Job Release Task. The command line does not run under a shell, and therefore cannot take + // advantage of shell features such as environment variable expansion. If you want to take advantage of such features, you + // should invoke the shell in the command line, for example using "cmd /c MyCommand" in Windows or "/bin/sh -c MyCommand" + // in Linux. If the command line refers to file paths, it should use a relative path (relative to the Task working directory), + // or use the Batch provided environment variable (https://learn.microsoft.com/azure/batch/batch-compute-node-environment-variables). + CommandLine *string + + // The settings for the container under which the Job Release Task runs. When this is specified, all directories recursively + // below the AZ_BATCH_NODE_ROOT_DIR (the root of Azure Batch directories on the node) are mapped into the container, all Task + // environment variables are mapped into the container, and the Task command line is executed in the container. Files produced + // in the container outside of AZ_BATCH_NODE_ROOT_DIR might not be reflected to the host disk, meaning that Batch file APIs + // will not be able to access those files. + ContainerSettings *TaskContainerSettings + + // A list of environment variable settings for the Job Release Task. + EnvironmentSettings []EnvironmentSetting + + // A string that uniquely identifies the Job Release Task within the Job. The ID can contain any combination of alphanumeric + // characters including hyphens and underscores and cannot contain more than 64 characters. If you do not specify this property, + // the Batch service assigns a default value of 'jobrelease'. No other Task in the Job can have the same ID as the Job Release + // Task. If you try to submit a Task with the same id, the Batch service rejects the request with error code TaskIdSameAsJobReleaseTask; + // if you are calling the REST API directly, the HTTP status code is 409 (Conflict). + ID *string + + // The maximum elapsed time that the Job Release Task may run on a given Compute Node, measured from the time the Task starts. + // If the Task does not complete within the time limit, the Batch service terminates it. The default value is 15 minutes. + // You may not specify a timeout longer than 15 minutes. If you do, the Batch service rejects it with an error; if you are + // calling the REST API directly, the HTTP status code is 400 (Bad Request). + MaxWallClockTime *string + + // A list of files that the Batch service will download to the Compute Node before running the command line. There is a maximum + // size for the list of resource files. When the max size is exceeded, the request will fail and the response error code will + // be RequestEntityTooLarge. If this occurs, the collection of ResourceFiles must be reduced in size. This can be achieved + // using .zip files, Application Packages, or Docker Containers. Files listed under this element are located in the Task's + // working directory. + ResourceFiles []ResourceFile + + // The minimum time to retain the Task directory for the Job Release Task on the Compute Node. After this time, the Batch + // service may delete the Task directory and all its contents. The default is 7 days, i.e. the Task directory will be retained + // for 7 days unless the Compute Node is removed or the Job is deleted. + RetentionTime *string + + // The user identity under which the Job Release Task runs. If omitted, the Task runs as a non-administrative user unique + // to the Task. + UserIdentity *UserIdentity +} + +// JobReleaseTaskExecutionInfo - Contains information about the execution of a Job Release Task on a Compute +// Node. +type JobReleaseTaskExecutionInfo struct { + // REQUIRED; The time at which the Task started running. If the Task has been restarted or retried, this is the most recent + // time at which the Task started running. + StartTime *time.Time + + // REQUIRED; The current state of the Job Release Task on the Compute Node. + State *JobReleaseTaskState + + // Information about the container under which the Task is executing. This property is set only if the Task runs in a container + // context. + ContainerInfo *TaskContainerExecutionInfo + + // The time at which the Job Release Task completed. This property is set only if the Task is in the Completed state. + EndTime *time.Time + + // The exit code of the program specified on the Task command line. This parameter is returned only if the Task is in the + // completed state. The exit code for a process reflects the specific convention implemented by the application developer + // for that process. If you use the exit code value to make decisions in your code, be sure that you know the exit code convention + // used by the application process. Note that the exit code may also be generated by the Compute Node operating system, such + // as when a process is forcibly terminated. + ExitCode *int32 + + // Information describing the Task failure, if any. This property is set only if the Task is in the completed state and encountered + // a failure. + FailureInfo *TaskFailureInfo + + // The result of the Task execution. If the value is 'failed', then the details of the failure can be found in the failureInfo + // property. + Result *TaskExecutionResult + + // The root directory of the Job Release Task on the Compute Node. You can use this path to retrieve files created by the + // Task, such as log files. + TaskRootDirectory *string + + // The URL to the root directory of the Job Release Task on the Compute Node. + TaskRootDirectoryURL *string +} + +// JobSchedule - A Job Schedule that allows recurring Jobs by specifying when to run Jobs and a +// specification used to create each Job. +type JobSchedule struct { + // REQUIRED; The details of the Jobs to be created on this schedule. + JobSpecification *JobSpecification + + // A list of name-value pairs associated with the schedule as metadata. The Batch service does not assign any meaning to metadata; + // it is solely for the use of user code. + Metadata []MetadataItem + + // The schedule according to which Jobs will be created. All times are fixed respective to UTC and are not impacted by daylight + // saving time. + Schedule *JobScheduleConfiguration + + // READ-ONLY; The creation time of the Job Schedule. + CreationTime *time.Time + + // READ-ONLY; The display name for the schedule. + DisplayName *string + + // READ-ONLY; The ETag of the Job Schedule. This is an opaque string. You can use it to detect whether the Job Schedule has + // changed between requests. In particular, you can be pass the ETag with an Update Job Schedule request to specify that your + // changes should take effect only if nobody else has modified the schedule in the meantime. + ETag *string + + // READ-ONLY; Information about Jobs that have been and will be run under this schedule. + ExecutionInfo *JobScheduleExecutionInfo + + // READ-ONLY; A string that uniquely identifies the schedule within the Account. + ID *string + + // READ-ONLY; The last modified time of the Job Schedule. This is the last time at which the schedule level data, such as + // the Job specification or recurrence information, changed. It does not factor in job-level changes such as new Jobs being + // created or Jobs changing state. + LastModified *time.Time + + // READ-ONLY; The previous state of the Job Schedule. This property is not present if the Job Schedule is in its initial active + // state. + PreviousState *JobScheduleState + + // READ-ONLY; The time at which the Job Schedule entered its previous state. This property is not present if the Job Schedule + // is in its initial active state. + PreviousStateTransitionTime *time.Time + + // READ-ONLY; The current state of the Job Schedule. + State *JobScheduleState + + // READ-ONLY; The time at which the Job Schedule entered the current state. + StateTransitionTime *time.Time + + // READ-ONLY; The lifetime resource usage statistics for the Job Schedule. The statistics may not be immediately available. + // The Batch service performs periodic roll-up of statistics. The typical delay is about 30 minutes. + Stats *JobScheduleStatistics + + // READ-ONLY; The URL of the Job Schedule. + URL *string +} + +// JobScheduleConfiguration - The schedule according to which Jobs will be created. All times are fixed +// respective to UTC and are not impacted by daylight saving time. +type JobScheduleConfiguration struct { + // A time after which no Job will be created under this Job Schedule. The schedule will move to the completed state as soon + // as this deadline is past and there is no active Job under this Job Schedule. If you do not specify a doNotRunAfter time, + // and you are creating a recurring Job Schedule, the Job Schedule will remain active until you explicitly terminate it. + DoNotRunAfter *time.Time + + // The earliest time at which any Job may be created under this Job Schedule. If you do not specify a doNotRunUntil time, + // the schedule becomes ready to create Jobs immediately. + DoNotRunUntil *time.Time + + // The time interval between the start times of two successive Jobs under the Job Schedule. A Job Schedule can have at most + // one active Job under it at any given time. Because a Job Schedule can have at most one active Job under it at any given + // time, if it is time to create a new Job under a Job Schedule, but the previous Job is still running, the Batch service + // will not create the new Job until the previous Job finishes. If the previous Job does not finish within the startWindow + // period of the new recurrenceInterval, then no new Job will be scheduled for that interval. For recurring Jobs, you should + // normally specify a jobManagerTask in the jobSpecification. If you do not use jobManagerTask, you will need an external + // process to monitor when Jobs are created, add Tasks to the Jobs and terminate the Jobs ready for the next recurrence. The + // default is that the schedule does not recur: one Job is created, within the startWindow after the doNotRunUntil time, and + // the schedule is complete as soon as that Job finishes. The minimum value is 1 minute. If you specify a lower value, the + // Batch service rejects the schedule with an error; if you are calling the REST API directly, the HTTP status code is 400 + // (Bad Request). + RecurrenceInterval *string + + // The time interval, starting from the time at which the schedule indicates a Job should be created, within which a Job must + // be created. If a Job is not created within the startWindow interval, then the 'opportunity' is lost; no Job will be created + // until the next recurrence of the schedule. If the schedule is recurring, and the startWindow is longer than the recurrence + // interval, then this is equivalent to an infinite startWindow, because the Job that is 'due' in one recurrenceInterval is + // not carried forward into the next recurrence interval. The default is infinite. The minimum value is 1 minute. If you specify + // a lower value, the Batch service rejects the schedule with an error; if you are calling the REST API directly, the HTTP + // status code is 400 (Bad Request). + StartWindow *string +} + +// JobScheduleExecutionInfo - Contains information about Jobs that have been and will be run under a Job +// Schedule. +type JobScheduleExecutionInfo struct { + // The time at which the schedule ended. This property is set only if the Job Schedule is in the completed state. + EndTime *time.Time + + // The next time at which a Job will be created under this schedule. This property is meaningful only if the schedule is in + // the active state when the time comes around. For example, if the schedule is disabled, no Job will be created at nextRunTime + // unless the Job is enabled before then. + NextRunTime *time.Time + + // Information about the most recent Job under the Job Schedule. This property is present only if the at least one Job has + // run under the schedule. + RecentJob *RecentJob +} + +// JobScheduleListResult - The result of listing the Job Schedules in an Account. +type JobScheduleListResult struct { + // The URL to get the next set of results. + NextLink *string + + // The list of Job Schedules. + Value []JobSchedule +} + +// JobScheduleStatistics - Resource usage statistics for a Job Schedule. +type JobScheduleStatistics struct { + // REQUIRED; The total kernel mode CPU time (summed across all cores and all Compute Nodes) consumed by all Tasks in all Jobs + // created under the schedule. + KernelCPUTime *string + + // REQUIRED; The time at which the statistics were last updated. All statistics are limited to the range between startTime + // and lastUpdateTime. + LastUpdateTime *time.Time + + // REQUIRED; The total number of Tasks that failed during the given time range in Jobs created under the schedule. A Task + // fails if it exhausts its maximum retry count without returning exit code 0. + NumFailedTasks *int64 + + // REQUIRED; The total number of Tasks successfully completed during the given time range in Jobs created under the schedule. + // A Task completes successfully if it returns exit code 0. + NumSucceededTasks *int64 + + // REQUIRED; The total number of retries during the given time range on all Tasks in all Jobs created under the schedule. + NumTaskRetries *int64 + + // REQUIRED; The total gibibytes read from disk by all Tasks in all Jobs created under the schedule. + ReadIOGiB *float32 + + // REQUIRED; The total number of disk read operations made by all Tasks in all Jobs created under the schedule. + ReadIOPS *int64 + + // REQUIRED; The start time of the time range covered by the statistics. + StartTime *time.Time + + // REQUIRED; The URL of the statistics. + URL *string + + // REQUIRED; The total user mode CPU time (summed across all cores and all Compute Nodes) consumed by all Tasks in all Jobs + // created under the schedule. + UserCPUTime *string + + // REQUIRED; The total wait time of all Tasks in all Jobs created under the schedule. The wait time for a Task is defined + // as the elapsed time between the creation of the Task and the start of Task execution. (If the Task is retried due to failures, + // the wait time is the time to the most recent Task execution.). This value is only reported in the Account lifetime statistics; + // it is not included in the Job statistics. + WaitTime *string + + // REQUIRED; The total wall clock time of all the Tasks in all the Jobs created under the schedule. The wall clock time is + // the elapsed time from when the Task started running on a Compute Node to when it finished (or to the last time the statistics + // were updated, if the Task had not finished by then). If a Task was retried, this includes the wall clock time of all the + // Task retries. + WallClockTime *string + + // REQUIRED; The total gibibytes written to disk by all Tasks in all Jobs created under the schedule. + WriteIOGiB *float32 + + // REQUIRED; The total number of disk write operations made by all Tasks in all Jobs created under the schedule. + WriteIOPS *int64 +} + +// JobSchedulingError - An error encountered by the Batch service when scheduling a Job. +type JobSchedulingError struct { + // REQUIRED; The category of the Job scheduling error. + Category *ErrorCategory + + // An identifier for the Job scheduling error. Codes are invariant and are intended to be consumed programmatically. + Code *string + + // A list of additional error details related to the scheduling error. + Details []NameValuePair + + // A message describing the Job scheduling error, intended to be suitable for display in a user interface. + Message *string +} + +// JobSpecification - Specifies details of the Jobs to be created on a schedule. +type JobSpecification struct { + // REQUIRED; The Pool on which the Batch service runs the Tasks of Jobs created under this schedule. + PoolInfo *PoolInfo + + // Whether Tasks in this job can be preempted by other high priority jobs. If the value is set to True, other high priority + // jobs submitted to the system will take precedence and will be able requeue tasks from this job. You can update a job's + // allowTaskPreemption after it has been created using the update job API. + AllowTaskPreemption *bool + + // A list of common environment variable settings. These environment variables are set for all Tasks in Jobs created under + // this schedule (including the Job Manager, Job Preparation and Job Release Tasks). Individual Tasks can override an environment + // setting specified here by specifying the same setting name with a different value. + CommonEnvironmentSettings []EnvironmentSetting + + // The execution constraints for Jobs created under this schedule. + Constraints *JobConstraints + + // The display name for Jobs created under this schedule. The name need not be unique and can contain any Unicode characters + // up to a maximum length of 1024. + DisplayName *string + + // The details of a Job Manager Task to be launched when a Job is started under this schedule. If the Job does not specify + // a Job Manager Task, the user must explicitly add Tasks to the Job using the Task API. If the Job does specify a Job Manager + // Task, the Batch service creates the Job Manager Task when the Job is created, and will try to schedule the Job Manager + // Task before scheduling other Tasks in the Job. + JobManagerTask *JobManagerTask + + // The Job Preparation Task for Jobs created under this schedule. If a Job has a Job Preparation Task, the Batch service will + // run the Job Preparation Task on a Node before starting any Tasks of that Job on that Compute Node. + JobPreparationTask *JobPreparationTask + + // The Job Release Task for Jobs created under this schedule. The primary purpose of the Job Release Task is to undo changes + // to Nodes made by the Job Preparation Task. Example activities include deleting local files, or shutting down services that + // were started as part of Job preparation. A Job Release Task cannot be specified without also specifying a Job Preparation + // Task for the Job. The Batch service runs the Job Release Task on the Compute Nodes that have run the Job Preparation Task. + JobReleaseTask *JobReleaseTask + + // The maximum number of tasks that can be executed in parallel for the job. The value of maxParallelTasks must be -1 or greater + // than 0 if specified. If not specified, the default value is -1, which means there's no limit to the number of tasks that + // can be run at once. You can update a job's maxParallelTasks after it has been created using the update job API. + MaxParallelTasks *int32 + + // A list of name-value pairs associated with each Job created under this schedule as metadata. The Batch service does not + // assign any meaning to metadata; it is solely for the use of user code. + Metadata []MetadataItem + + // The network configuration for the Job. + NetworkConfiguration *JobNetworkConfiguration + + // The action the Batch service should take when all Tasks in a Job created under this schedule are in the completed state. + // Note that if a Job contains no Tasks, then all Tasks are considered complete. This option is therefore most commonly used + // with a Job Manager task; if you want to use automatic Job termination without a Job Manager, you should initially set onAllTasksComplete + // to noaction and update the Job properties to set onAllTasksComplete to terminatejob once you have finished adding Tasks. + // The default is noaction. + OnAllTasksComplete *OnAllTasksComplete + + // The action the Batch service should take when any Task fails in a Job created under this schedule. A Task is considered + // to have failed if it have failed if has a failureInfo. A failureInfo is set if the Task completes with a non-zero exit + // code after exhausting its retry count, or if there was an error starting the Task, for example due to a resource file download + // error. The default is noaction. + OnTaskFailure *OnTaskFailure + + // The priority of Jobs created under this schedule. Priority values can range from -1000 to 1000, with -1000 being the lowest + // priority and 1000 being the highest priority. The default value is 0. This priority is used as the default for all Jobs + // under the Job Schedule. You can update a Job's priority after it has been created using by using the update Job API. + Priority *int32 + + // Whether Tasks in the Job can define dependencies on each other. The default is false. + UsesTaskDependencies *bool +} + +// JobStatistics - Resource usage statistics for a Job. +type JobStatistics struct { + // REQUIRED; The total kernel mode CPU time (summed across all cores and all Compute Nodes) consumed by all Tasks in the Job. + KernelCPUTime *string + + // REQUIRED; The time at which the statistics were last updated. All statistics are limited to the range between startTime + // and lastUpdateTime. + LastUpdateTime *time.Time + + // REQUIRED; The total number of Tasks in the Job that failed during the given time range. A Task fails if it exhausts its + // maximum retry count without returning exit code 0. + NumFailedTasks *int64 + + // REQUIRED; The total number of Tasks successfully completed in the Job during the given time range. A Task completes successfully + // if it returns exit code 0. + NumSucceededTasks *int64 + + // REQUIRED; The total number of retries on all the Tasks in the Job during the given time range. + NumTaskRetries *int64 + + // REQUIRED; The total amount of data in GiB read from disk by all Tasks in the Job. + ReadIOGiB *float32 + + // REQUIRED; The total number of disk read operations made by all Tasks in the Job. + ReadIOps *int64 + + // REQUIRED; The start time of the time range covered by the statistics. + StartTime *time.Time + + // REQUIRED; The URL of the statistics. + URL *string + + // REQUIRED; The total user mode CPU time (summed across all cores and all Compute Nodes) consumed by all Tasks in the Job. + UserCPUTime *string + + // REQUIRED; The total wait time of all Tasks in the Job. The wait time for a Task is defined as the elapsed time between + // the creation of the Task and the start of Task execution. (If the Task is retried due to failures, the wait time is the + // time to the most recent Task execution.) This value is only reported in the Account lifetime statistics; it is not included + // in the Job statistics. + WaitTime *string + + // REQUIRED; The total wall clock time of all Tasks in the Job. The wall clock time is the elapsed time from when the Task + // started running on a Compute Node to when it finished (or to the last time the statistics were updated, if the Task had + // not finished by then). If a Task was retried, this includes the wall clock time of all the Task retries. + WallClockTime *string + + // REQUIRED; The total amount of data in GiB written to disk by all Tasks in the Job. + WriteIOGiB *float32 + + // REQUIRED; The total number of disk write operations made by all Tasks in the Job. + WriteIOps *int64 +} + +// LinuxUserConfiguration - Properties used to create a user Account on a Linux Compute Node. +type LinuxUserConfiguration struct { + // The group ID for the user Account. The uid and gid properties must be specified together or not at all. If not specified + // the underlying operating system picks the gid. + GID *int32 + + // The SSH private key for the user Account. The private key must not be password protected. The private key is used to automatically + // configure asymmetric-key based authentication for SSH between Compute Nodes in a Linux Pool when the Pool's enableInterNodeCommunication + // property is true (it is ignored if enableInterNodeCommunication is false). It does this by placing the key pair into the + // user's .ssh directory. If not specified, password-less SSH is not configured between Compute Nodes (no modification of + // the user's .ssh directory is done). + SSHPrivateKey *string + + // The user ID of the user Account. The uid and gid properties must be specified together or not at all. If not specified + // the underlying operating system picks the uid. + UID *int32 +} + +// ListPoolNodeCountsResult - The result of listing the Compute Node counts in the Account. +type ListPoolNodeCountsResult struct { + // The URL to get the next set of results. + NextLink *string + + // A list of Compute Node counts by Pool. + Value []PoolNodeCounts +} + +// ManagedDisk - The managed disk parameters. +type ManagedDisk struct { + // Specifies the security profile settings for the managed disk. + SecurityProfile *VMDiskSecurityProfile + + // The storage account type for managed disk. + StorageAccountType *StorageAccountType +} + +// MetadataItem - The Batch service does not assign any meaning to this metadata; it is solely +// for the use of user code. +type MetadataItem struct { + // REQUIRED; The name of the metadata item. + Name *string + + // REQUIRED; The value of the metadata item. + Value *string +} + +// MountConfiguration - The file system to mount on each node. +type MountConfiguration struct { + // The Azure Storage Container to mount using blob FUSE on each node. This property is mutually exclusive with all other properties. + AzureBlobFileSystemConfiguration *AzureBlobFileSystemConfiguration + + // The Azure File Share to mount on each node. This property is mutually exclusive with all other properties. + AzureFileShareConfiguration *AzureFileShareConfiguration + + // The CIFS/SMB file system to mount on each node. This property is mutually exclusive with all other properties. + CifsMountConfiguration *CIFSMountConfiguration + + // The NFS file system to mount on each node. This property is mutually exclusive with all other properties. + NfsMountConfiguration *NFSMountConfiguration +} + +// MultiInstanceSettings - Multi-instance Tasks are commonly used to support MPI Tasks. In the MPI case, +// if any of the subtasks fail (for example due to exiting with a non-zero exit +// code) the entire multi-instance Task fails. The multi-instance Task is then +// terminated and retried, up to its retry limit. +type MultiInstanceSettings struct { + // REQUIRED; The command line to run on all the Compute Nodes to enable them to coordinate when the primary runs the main + // Task command. A typical coordination command line launches a background service and verifies that the service is ready + // to process inter-node messages. + CoordinationCommandLine *string + + // A list of files that the Batch service will download before running the coordination command line. The difference between + // common resource files and Task resource files is that common resource files are downloaded for all subtasks including the + // primary, whereas Task resource files are downloaded only for the primary. Also note that these resource files are not downloaded + // to the Task working directory, but instead are downloaded to the Task root directory (one directory above the working directory). + // There is a maximum size for the list of resource files. When the max size is exceeded, the request will fail and the response + // error code will be RequestEntityTooLarge. If this occurs, the collection of ResourceFiles must be reduced in size. This + // can be achieved using .zip files, Application Packages, or Docker Containers. + CommonResourceFiles []ResourceFile + + // The number of Compute Nodes required by the Task. If omitted, the default is 1. + NumberOfInstances *int32 +} + +// NFSMountConfiguration - Information used to connect to an NFS file system. +type NFSMountConfiguration struct { + // REQUIRED; The relative path on the compute node where the file system will be mounted. All file systems are mounted relative + // to the Batch mounts directory, accessible via the AZ_BATCH_NODE_MOUNTS_DIR environment variable. + RelativeMountPath *string + + // REQUIRED; The URI of the file system to mount. + Source *string + + // Additional command line options to pass to the mount command. These are 'net use' options in Windows and 'mount' options + // in Linux. + MountOptions *string +} + +// NameValuePair - Represents a name-value pair. +type NameValuePair struct { + // The name in the name-value pair. + Name *string + + // The value in the name-value pair. + Value *string +} + +// NetworkConfiguration - The network configuration for a Pool. +type NetworkConfiguration struct { + // The scope of dynamic vnet assignment. + DynamicVNetAssignmentScope *DynamicVNetAssignmentScope + + // Whether this pool should enable accelerated networking. Accelerated networking enables single root I/O virtualization (SR-IOV) + // to a VM, which may lead to improved networking performance. For more details, see: https://learn.microsoft.com/azure/virtual-network/accelerated-networking-overview. + EnableAcceleratedNetworking *bool + + // The configuration for endpoints on Compute Nodes in the Batch Pool. + EndpointConfiguration *PoolEndpointConfiguration + + // The Public IPAddress configuration for Compute Nodes in the Batch Pool. + PublicIPAddressConfiguration *PublicIPAddressConfiguration + + // The ARM resource identifier of the virtual network subnet which the Compute Nodes of the Pool will join. This is of the + // form /subscriptions/{subscription}/resourceGroups/{group}/providers/{provider}/virtualNetworks/{network}/subnets/{subnet}. + // The virtual network must be in the same region and subscription as the Azure Batch Account. The specified subnet should + // have enough free IP addresses to accommodate the number of Compute Nodes in the Pool. If the subnet doesn't have enough + // free IP addresses, the Pool will partially allocate Nodes and a resize error will occur. The 'MicrosoftAzureBatch' service + // principal must have the 'Classic Virtual Machine Contributor' Role-Based Access Control (RBAC) role for the specified VNet. + // The specified subnet must allow communication from the Azure Batch service to be able to schedule Tasks on the Nodes. This + // can be verified by checking if the specified VNet has any associated Network Security Groups (NSG). If communication to + // the Nodes in the specified subnet is denied by an NSG, then the Batch service will set the state of the Compute Nodes to + // unusable. Only ARM virtual networks ('Microsoft.Network/virtualNetworks') are supported. If the specified VNet has any + // associated Network Security Groups (NSG), then a few reserved system ports must be enabled for inbound communication, including + // ports 29876 and 29877. Also enable outbound connections to Azure Storage on port 443. For more details see: https://learn.microsoft.com/azure/batch/nodes-and-pools#virtual-network-vnet-and-firewall-configuration + SubnetID *string +} + +// NetworkSecurityGroupRule - A network security group rule to apply to an inbound endpoint. +type NetworkSecurityGroupRule struct { + // REQUIRED; The action that should be taken for a specified IP address, subnet range or tag. + Access *NetworkSecurityGroupRuleAccess + + // REQUIRED; The priority for this rule. Priorities within a Pool must be unique and are evaluated in order of priority. The + // lower the number the higher the priority. For example, rules could be specified with order numbers of 150, 250, and 350. + // The rule with the order number of 150 takes precedence over the rule that has an order of 250. Allowed priorities are 150 + // to 4096. If any reserved or duplicate values are provided the request fails with HTTP status code 400. + Priority *int32 + + // REQUIRED; The source address prefix or tag to match for the rule. Valid values are a single IP address (i.e. 10.10.10.10), + // IP subnet (i.e. 192.168.1.0/24), default tag, or * (for all addresses). If any other values are provided the request fails + // with HTTP status code 400. + SourceAddressPrefix *string + + // The source port ranges to match for the rule. Valid values are '*' (for all ports 0 - 65535), a specific port (i.e. 22), + // or a port range (i.e. 100-200). The ports must be in the range of 0 to 65535. Each entry in this collection must not overlap + // any other entry (either a range or an individual port). If any other values are provided the request fails with HTTP status + // code 400. The default value is '*'. + SourcePortRanges []string +} + +// Node - A Compute Node in the Batch service. +type Node struct { + // An identifier which can be passed when adding a Task to request that the Task be scheduled on this Compute Node. Note that + // this is just a soft affinity. If the target Compute Node is busy or unavailable at the time the Task is scheduled, then + // the Task will be scheduled elsewhere. + AffinityID *string + + // The time at which this Compute Node was allocated to the Pool. This is the time when the Compute Node was initially allocated + // and doesn't change once set. It is not updated when the Compute Node is service healed or preempted. + AllocationTime *time.Time + + // For Windows Nodes, the Batch service installs the Certificates to the specified Certificate store and location. + // For Linux Compute Nodes, the Certificates are stored in a directory inside the Task working directory and an environment + // variable AZ_BATCH_CERTIFICATES_DIR is supplied to the Task to query for this location. + // For Certificates with visibility of 'remoteUser', a 'certs' directory is created in the user's home directory (e.g., /home/{user-name}/certs) + // and Certificates are placed in that directory. + // Warning: This property is deprecated and will be removed after February, 2024. Please use the [Azure KeyVault Extension](https://learn.microsoft.com/azure/batch/batch-certificate-migration-guide) + // instead. + CertificateReferences []CertificateReference + + // The endpoint configuration for the Compute Node. + EndpointConfiguration *NodeEndpointConfiguration + + // The list of errors that are currently being encountered by the Compute Node. + Errors []NodeError + + // The ID of the Compute Node. Every Compute Node that is added to a Pool is assigned a unique ID. Whenever a Compute Node + // is removed from a Pool, all of its local files are deleted, and the ID is reclaimed and could be reused for new Compute + // Nodes. + ID *string + + // The IP address that other Nodes can use to communicate with this Compute Node. Every Compute Node that is added to a Pool + // is assigned a unique IP address. Whenever a Compute Node is removed from a Pool, all of its local files are deleted, and + // the IP address is reclaimed and could be reused for new Compute Nodes. + IPAddress *string + + // Whether this Compute Node is a dedicated Compute Node. If false, the Compute Node is a Spot/Low-priority Compute Node. + IsDedicated *bool + + // The last time at which the Compute Node was started. This property may not be present if the Compute Node state is unusable. + LastBootTime *time.Time + + // Information about the Compute Node agent version and the time the Compute Node upgraded to a new version. + NodeAgentInfo *NodeAgentInfo + + // A list of Tasks whose state has recently changed. This property is present only if at least one Task has run on this Compute + // Node since it was assigned to the Pool. + RecentTasks []TaskInfo + + // The total number of scheduling slots used by currently running Job Tasks on the Compute Node. This includes Job Manager + // Tasks and normal Tasks, but not Job Preparation, Job Release or Start Tasks. + RunningTaskSlotsCount *int32 + + // The total number of currently running Job Tasks on the Compute Node. This includes Job Manager Tasks and normal Tasks, + // but not Job Preparation, Job Release or Start Tasks. + RunningTasksCount *int32 + + // Whether the Compute Node is available for Task scheduling. + SchedulingState *SchedulingState + + // The Task specified to run on the Compute Node as it joins the Pool. + StartTask *StartTask + + // Runtime information about the execution of the StartTask on the Compute Node. + StartTaskInfo *StartTaskInfo + + // The current state of the Compute Node. The Spot/Low-priority Compute Node has been preempted. Tasks which were running + // on the Compute Node when it was preempted will be rescheduled when another Compute Node becomes available. + State *NodeState + + // The time at which the Compute Node entered its current state. + StateTransitionTime *time.Time + + // The total number of Job Tasks completed on the Compute Node. This includes Job Manager Tasks and normal Tasks, but not + // Job Preparation, Job Release or Start Tasks. + TotalTasksRun *int32 + + // The total number of Job Tasks which completed successfully (with exitCode 0) on the Compute Node. This includes Job Manager + // Tasks and normal Tasks, but not Job Preparation, Job Release or Start Tasks. + TotalTasksSucceeded *int32 + + // The URL of the Compute Node. + URL *string + + // The size of the virtual machine hosting the Compute Node. For information about available sizes of virtual machines in + // Pools, see Choose a VM size for Compute Nodes in an Azure Batch Pool (https://learn.microsoft.com/azure/batch/batch-pool-vm-sizes). + VMSize *string + + // Info about the current state of the virtual machine. + VirtualMachineInfo *VirtualMachineInfo +} + +// NodeAgentInfo - The Batch Compute Node agent is a program that runs on each Compute Node in the +// Pool and provides Batch capability on the Compute Node. +type NodeAgentInfo struct { + // REQUIRED; The time when the Compute Node agent was updated on the Compute Node. This is the most recent time that the Compute + // Node agent was updated to a new version. + LastUpdateTime *time.Time + + // REQUIRED; The version of the Batch Compute Node agent running on the Compute Node. This version number can be checked against + // the Compute Node agent release notes located at https://github.com/Azure/Batch/blob/master/changelogs/nodeagent/CHANGELOG.md. + Version *string +} + +// NodeCounts - The number of Compute Nodes in each Compute Node state. +type NodeCounts struct { + // REQUIRED; The number of Compute Nodes in the creating state. + Creating *int32 + + // REQUIRED; The number of Compute Nodes in the deallocated state. + Deallocated *int32 + + // REQUIRED; The number of Compute Nodes in the deallocating state. + Deallocating *int32 + + // REQUIRED; The number of Compute Nodes in the idle state. + Idle *int32 + + // REQUIRED; The number of Compute Nodes in the leavingPool state. + LeavingPool *int32 + + // REQUIRED; The number of Compute Nodes in the offline state. + Offline *int32 + + // REQUIRED; The number of Compute Nodes in the preempted state. + Preempted *int32 + + // REQUIRED; The count of Compute Nodes in the rebooting state. + Rebooting *int32 + + // REQUIRED; The number of Compute Nodes in the reimaging state. + Reimaging *int32 + + // REQUIRED; The number of Compute Nodes in the running state. + Running *int32 + + // REQUIRED; The number of Compute Nodes in the startTaskFailed state. + StartTaskFailed *int32 + + // REQUIRED; The number of Compute Nodes in the starting state. + Starting *int32 + + // REQUIRED; The total number of Compute Nodes. + Total *int32 + + // REQUIRED; The number of Compute Nodes in the unknown state. + Unknown *int32 + + // REQUIRED; The number of Compute Nodes in the unusable state. + Unusable *int32 + + // REQUIRED; The number of Compute Nodes in the upgradingOS state. + UpgradingOS *int32 + + // REQUIRED; The number of Compute Nodes in the waitingForStartTask state. + WaitingForStartTask *int32 +} + +// NodeEndpointConfiguration - The endpoint configuration for the Compute Node. +type NodeEndpointConfiguration struct { + // REQUIRED; The list of inbound endpoints that are accessible on the Compute Node. + InboundEndpoints []InboundEndpoint +} + +// NodeError - An error encountered by a Compute Node. +type NodeError struct { + // An identifier for the Compute Node error. Codes are invariant and are intended to be consumed programmatically. + Code *string + + // The list of additional error details related to the Compute Node error. + ErrorDetails []NameValuePair + + // A message describing the Compute Node error, intended to be suitable for display in a user interface. + Message *string +} + +// NodeFile - Information about a file or directory on a Compute Node. +type NodeFile struct { + // Whether the object represents a directory. + IsDirectory *bool + + // The file path. + Name *string + + // The file properties. + Properties *FileProperties + + // The URL of the file. + URL *string +} + +// NodeFileListResult - The result of listing the files on a Compute Node, or the files associated with +// a Task on a Compute Node. +type NodeFileListResult struct { + // The URL to get the next set of results. + NextLink *string + + // The list of files. + Value []NodeFile +} + +// NodeIdentityReference - The reference to a user assigned identity associated with the Batch pool which +// a compute node will use. +type NodeIdentityReference struct { + // The ARM resource id of the user assigned identity. + ResourceID *string +} + +// NodeInfo - Information about the Compute Node on which a Task ran. +type NodeInfo struct { + // An identifier for the Node on which the Task ran, which can be passed when adding a Task to request that the Task be scheduled + // on this Compute Node. + AffinityID *string + + // The ID of the Compute Node on which the Task ran. + NodeID *string + + // The URL of the Compute Node on which the Task ran. + NodeURL *string + + // The ID of the Pool on which the Task ran. + PoolID *string + + // The root directory of the Task on the Compute Node. + TaskRootDirectory *string + + // The URL to the root directory of the Task on the Compute Node. + TaskRootDirectoryURL *string +} + +// NodeListResult - The result of listing the Compute Nodes in a Pool. +type NodeListResult struct { + // The URL to get the next set of results. + NextLink *string + + // The list of Compute Nodes. + Value []Node +} + +// NodePlacementConfiguration - For regional placement, nodes in the pool will be allocated in the same region. +// For zonal placement, nodes in the pool will be spread across different zones +// with best effort balancing. +type NodePlacementConfiguration struct { + // Node placement Policy type on Batch Pools. Allocation policy used by Batch Service to provision the nodes. If not specified, + // Batch will use the regional policy. + Policy *NodePlacementPolicyType +} + +// NodeRemoteLoginSettings - The remote login settings for a Compute Node. +type NodeRemoteLoginSettings struct { + // REQUIRED; The IP address used for remote login to the Compute Node. + RemoteLoginIPAddress *string + + // REQUIRED; The port used for remote login to the Compute Node. + RemoteLoginPort *int32 +} + +// NodeVMExtension - The configuration for virtual machine extension instance view. +type NodeVMExtension struct { + // The vm extension instance view. + InstanceView *VMExtensionInstanceView + + // The provisioning state of the virtual machine extension. + ProvisioningState *string + + // The virtual machine extension. + VMExtension *VMExtension +} + +// NodeVMExtensionListResult - The result of listing the Compute Node extensions in a Node. +type NodeVMExtensionListResult struct { + // The URL to get the next set of results. + NextLink *string + + // The list of Compute Node extensions. + Value []NodeVMExtension +} + +// OSDisk - Settings for the operating system disk of the compute node (VM). +type OSDisk struct { + // Specifies the caching requirements. Possible values are: None, ReadOnly, ReadWrite. The default values are: None for Standard + // storage. ReadOnly for Premium storage. + Caching *CachingType + + // The initial disk size in GB when creating new OS disk. + DiskSizeGB *int32 + + // Specifies the ephemeral Disk Settings for the operating system disk used by the compute node (VM). + EphemeralOSDiskSettings *DiffDiskSettings + + // The managed disk parameters. + ManagedDisk *ManagedDisk + + // Specifies whether writeAccelerator should be enabled or disabled on the disk. + WriteAcceleratorEnabled *bool +} + +// OutputFile - On every file uploads, Batch service writes two log files to the compute node, 'fileuploadout.txt' and 'fileuploaderr.txt'. +// These log files are used to learn more about a specific failure. +type OutputFile struct { + // REQUIRED; The destination for the output file(s). + Destination *OutputFileDestination + + // REQUIRED; A pattern indicating which file(s) to upload. Both relative and absolute paths are supported. Relative paths + // are relative to the Task working directory. The following wildcards are supported: * matches 0 or more characters (for + // example pattern abc* would match abc or abcdef), ** matches any directory, ? matches any single character, [abc] matches + // one character in the brackets, and [a-c] matches one character in the range. Brackets can include a negation to match any + // character not specified (for example [!abc] matches any character but a, b, or c). If a file name starts with "." it is + // ignored by default but may be matched by specifying it explicitly (for example *.gif will not match .a.gif, but .*.gif + // will). A simple example: **\*.txt matches any file that does not start in '.' and ends with .txt in the Task working directory + // or any subdirectory. If the filename contains a wildcard character it can be escaped using brackets (for example abc[*] + // would match a file named abc*). Note that both \ and / are treated as directory separators on Windows, but only / is on + // Linux. Environment variables (%var% on Windows or $var on Linux) are expanded prior to the pattern being applied. + FilePattern *string + + // REQUIRED; Additional options for the upload operation, including under what conditions to perform the upload. + UploadOptions *OutputFileUploadConfig +} + +// OutputFileBlobContainerDestination - Specifies a file upload destination within an Azure blob storage container. +type OutputFileBlobContainerDestination struct { + // REQUIRED; The URL of the container within Azure Blob Storage to which to upload the file(s). If not using a managed identity, + // the URL must include a Shared Access Signature (SAS) granting write permissions to the container. + ContainerURL *string + + // The reference to the user assigned identity to use to access Azure Blob Storage specified by containerUrl. The identity + // must have write access to the Azure Blob Storage container. + IdentityReference *NodeIdentityReference + + // The destination blob or virtual directory within the Azure Storage container. If filePattern refers to a specific file + // (i.e. contains no wildcards), then path is the name of the blob to which to upload that file. If filePattern contains one + // or more wildcards (and therefore may match multiple files), then path is the name of the blob virtual directory (which + // is prepended to each blob name) to which to upload the file(s). If omitted, file(s) are uploaded to the root of the container + // with a blob name matching their file name. + Path *string + + // A list of name-value pairs for headers to be used in uploading output files. These headers will be specified when uploading + // files to Azure Storage. Official document on allowed headers when uploading blobs: https://learn.microsoft.com/rest/api/storageservices/put-blob#request-headers-all-blob-types. + UploadHeaders []HTTPHeader +} + +// OutputFileDestination - The destination to which a file should be uploaded. +type OutputFileDestination struct { + // A location in Azure blob storage to which files are uploaded. + Container *OutputFileBlobContainerDestination +} + +// OutputFileUploadConfig - Options for an output file upload operation, including under what conditions +// to perform the upload. +type OutputFileUploadConfig struct { + // REQUIRED; The conditions under which the Task output file or set of files should be uploaded. The default is taskcompletion. + UploadCondition *OutputFileUploadCondition +} + +// Pool - A Pool in the Azure Batch service. +type Pool struct { + // A Task specified to run on each Compute Node as it joins the Pool. + StartTask *StartTask + + // The desired node communication mode for the pool. If omitted, the default value is Default. + TargetNodeCommunicationMode *NodeCommunicationMode + + // The upgrade policy for the Pool. Describes an upgrade policy - automatic, manual, or rolling. + UpgradePolicy *UpgradePolicy + + // READ-ONLY; Whether the Pool is resizing. + AllocationState *AllocationState + + // READ-ONLY; The time at which the Pool entered its current allocation state. + AllocationStateTransitionTime *time.Time + + // READ-ONLY; The list of Packages to be installed on each Compute Node in the Pool. Changes to Package references affect + // all new Nodes joining the Pool, but do not affect Compute Nodes that are already in the Pool until they are rebooted or + // reimaged. There is a maximum of 10 Package references on any given Pool. + ApplicationPackageReferences []ApplicationPackageReference + + // READ-ONLY; The time interval at which to automatically adjust the Pool size according to the autoscale formula. This property + // is set only if the Pool automatically scales, i.e. enableAutoScale is true. + AutoScaleEvaluationInterval *string + + // READ-ONLY; A formula for the desired number of Compute Nodes in the Pool. This property is set only if the Pool automatically + // scales, i.e. enableAutoScale is true. + AutoScaleFormula *string + + // READ-ONLY; The results and errors from the last execution of the autoscale formula. This property is set only if the Pool + // automatically scales, i.e. enableAutoScale is true. + AutoScaleRun *AutoScaleRun + + // READ-ONLY; For Windows Nodes, the Batch service installs the Certificates to the specified Certificate store and location. + // For Linux Compute Nodes, the Certificates are stored in a directory inside the Task working directory and an environment + // variable AZ_BATCH_CERTIFICATES_DIR is supplied to the Task to query for this location. + // For Certificates with visibility of 'remoteUser', a 'certs' directory is created in the user's home directory (e.g., /home/{user-name}/certs) + // and Certificates are placed in that directory. + // Warning: This property is deprecated and will be removed after February, 2024. Please use the [Azure KeyVault Extension](https://learn.microsoft.com/azure/batch/batch-certificate-migration-guide) + // instead. + CertificateReferences []CertificateReference + + // READ-ONLY; The creation time of the Pool. + CreationTime *time.Time + + // READ-ONLY; The number of dedicated Compute Nodes currently in the Pool. + CurrentDedicatedNodes *int32 + + // READ-ONLY; The number of Spot/Low-priority Compute Nodes currently in the Pool. Spot/Low-priority Compute Nodes which have + // been preempted are included in this count. + CurrentLowPriorityNodes *int32 + + // READ-ONLY; The current state of the pool communication mode. + CurrentNodeCommunicationMode *NodeCommunicationMode + + // READ-ONLY; The display name for the Pool. The display name need not be unique and can contain any Unicode characters up + // to a maximum length of 1024. + DisplayName *string + + // READ-ONLY; The ETag of the Pool. This is an opaque string. You can use it to detect whether the Pool has changed between + // requests. In particular, you can be pass the ETag when updating a Pool to specify that your changes should take effect + // only if nobody else has modified the Pool in the meantime. + ETag *string + + // READ-ONLY; Whether the Pool size should automatically adjust over time. If false, at least one of targetDedicatedNodes + // and targetLowPriorityNodes must be specified. If true, the autoScaleFormula property is required and the Pool automatically + // resizes according to the formula. The default value is false. + EnableAutoScale *bool + + // READ-ONLY; Whether the Pool permits direct communication between Compute Nodes. This imposes restrictions on which Compute + // Nodes can be assigned to the Pool. Specifying this value can reduce the chance of the requested number of Compute Nodes + // to be allocated in the Pool. + EnableInterNodeCommunication *bool + + // READ-ONLY; A string that uniquely identifies the Pool within the Account. The ID can contain any combination of alphanumeric + // characters including hyphens and underscores, and cannot contain more than 64 characters. The ID is case-preserving and + // case-insensitive (that is, you may not have two IDs within an Account that differ only by case). + ID *string + + // READ-ONLY; The identity of the Batch pool, if configured. The list of user identities associated with the Batch pool. The + // user identity dictionary key references will be ARM resource ids in the form: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}'. + Identity *PoolIdentity + + // READ-ONLY; The last modified time of the Pool. This is the last time at which the Pool level data, such as the targetDedicatedNodes + // or enableAutoscale settings, changed. It does not factor in node-level changes such as a Compute Node changing state. + LastModified *time.Time + + // READ-ONLY; A list of name-value pairs associated with the Pool as metadata. + Metadata []MetadataItem + + // READ-ONLY; A list of file systems to mount on each node in the pool. This supports Azure Files, NFS, CIFS/SMB, and Blobfuse. + MountConfiguration []MountConfiguration + + // READ-ONLY; The network configuration for the Pool. + NetworkConfiguration *NetworkConfiguration + + // READ-ONLY; A list of errors encountered while performing the last resize on the Pool. This property is set only if one + // or more errors occurred during the last Pool resize, and only when the Pool allocationState is Steady. + ResizeErrors []ResizeError + + // READ-ONLY; The timeout for allocation of Compute Nodes to the Pool. This is the timeout for the most recent resize operation. + // (The initial sizing when the Pool is created counts as a resize.) The default value is 15 minutes. + ResizeTimeout *string + + // READ-ONLY; The user-specified tags associated with the pool. The user-defined tags to be associated with the Azure Batch + // Pool. When specified, these tags are propagated to the backing Azure resources associated with the pool. This property + // can only be specified when the Batch account was created with the poolAllocationMode property set to 'UserSubscription'. + ResourceTags map[string]*string + + // READ-ONLY; The current state of the Pool. + State *PoolState + + // READ-ONLY; The time at which the Pool entered its current state. + StateTransitionTime *time.Time + + // READ-ONLY; Utilization and resource usage statistics for the entire lifetime of the Pool. This property is populated only + // if the BatchPool was retrieved with an expand clause including the 'stats' attribute; otherwise it is null. The statistics + // may not be immediately available. The Batch service performs periodic roll-up of statistics. The typical delay is about + // 30 minutes. + Stats *PoolStatistics + + // READ-ONLY; The desired number of dedicated Compute Nodes in the Pool. + TargetDedicatedNodes *int32 + + // READ-ONLY; The desired number of Spot/Low-priority Compute Nodes in the Pool. + TargetLowPriorityNodes *int32 + + // READ-ONLY; How Tasks are distributed across Compute Nodes in a Pool. If not specified, the default is spread. + TaskSchedulingPolicy *TaskSchedulingPolicy + + // READ-ONLY; The number of task slots that can be used to run concurrent tasks on a single compute node in the pool. The + // default value is 1. The maximum value is the smaller of 4 times the number of cores of the vmSize of the pool or 256. + TaskSlotsPerNode *int32 + + // READ-ONLY; The URL of the Pool. + URL *string + + // READ-ONLY; The list of user Accounts to be created on each Compute Node in the Pool. + UserAccounts []UserAccount + + // READ-ONLY; The size of virtual machines in the Pool. All virtual machines in a Pool are the same size. For information + // about available VM sizes, see Sizes for Virtual Machines in Azure (https://learn.microsoft.com/azure/virtual-machines/sizes/overview). + // Batch supports all Azure VM sizes except STANDARD_A0 and those with premium storage (STANDARD_GS, STANDARD_DS, and STANDARD_DSV2 + // series). + VMSize *string + + // READ-ONLY; The virtual machine configuration for the Pool. This property must be specified. + VirtualMachineConfiguration *VirtualMachineConfiguration +} + +// PoolEndpointConfiguration - The endpoint configuration for a Pool. +type PoolEndpointConfiguration struct { + // REQUIRED; A list of inbound NAT Pools that can be used to address specific ports on an individual Compute Node externally. + // The maximum number of inbound NAT Pools per Batch Pool is 5. If the maximum number of inbound NAT Pools is exceeded the + // request fails with HTTP status code 400. This cannot be specified if the IPAddressProvisioningType is NoPublicIPAddresses. + InboundNATPools []InboundNATPool +} + +// PoolIdentity - The identity of the Batch pool, if configured. +type PoolIdentity struct { + // REQUIRED; The identity of the Batch pool, if configured. The list of user identities associated with the Batch pool. The + // user identity dictionary key references will be ARM resource ids in the form: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}'. + Type *PoolIdentityType + + // The list of user identities associated with the Batch account. The user identity dictionary key references will be ARM + // resource ids in the form: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}'. + UserAssignedIdentities []UserAssignedIdentity +} + +// PoolInfo - Specifies how a Job should be assigned to a Pool. +type PoolInfo struct { + // Characteristics for a temporary 'auto pool'. The Batch service will create this auto Pool when the Job is submitted. If + // auto Pool creation fails, the Batch service moves the Job to a completed state, and the Pool creation error is set in the + // Job's scheduling error property. The Batch service manages the lifetime (both creation and, unless keepAlive is specified, + // deletion) of the auto Pool. Any user actions that affect the lifetime of the auto Pool while the Job is active will result + // in unexpected behavior. You must specify either the Pool ID or the auto Pool specification, but not both. + AutoPoolSpecification *AutoPoolSpecification + + // The ID of an existing Pool. All the Tasks of the Job will run on the specified Pool. You must ensure that the Pool referenced + // by this property exists. If the Pool does not exist at the time the Batch service tries to schedule a Job, no Tasks for + // the Job will run until you create a Pool with that id. Note that the Batch service will not reject the Job request; it + // will simply not run Tasks until the Pool exists. You must specify either the Pool ID or the auto Pool specification, but + // not both. + PoolID *string +} + +// PoolListResult - The result of listing the Pools in an Account. +type PoolListResult struct { + // The URL to get the next set of results. + NextLink *string + + // The list of Pools. + Value []Pool +} + +// PoolNodeCounts - The number of Compute Nodes in each state for a Pool. +type PoolNodeCounts struct { + // REQUIRED; The ID of the Pool. + PoolID *string + + // The number of dedicated Compute Nodes in each state. + Dedicated *NodeCounts + + // The number of Spot/Low-priority Compute Nodes in each state. + LowPriority *NodeCounts +} + +// PoolResourceStatistics - Statistics related to resource consumption by Compute Nodes in a Pool. +type PoolResourceStatistics struct { + // REQUIRED; The average CPU usage across all Compute Nodes in the Pool (percentage per node). + AvgCPUPercentage *float32 + + // REQUIRED; The average used disk space in GiB across all Compute Nodes in the Pool. + AvgDiskGiB *float32 + + // REQUIRED; The average memory usage in GiB across all Compute Nodes in the Pool. + AvgMemoryGiB *float32 + + // REQUIRED; The total amount of data in GiB of disk reads across all Compute Nodes in the Pool. + DiskReadGiB *float32 + + // REQUIRED; The total number of disk read operations across all Compute Nodes in the Pool. + DiskReadIOPS *int64 + + // REQUIRED; The total amount of data in GiB of disk writes across all Compute Nodes in the Pool. + DiskWriteGiB *float32 + + // REQUIRED; The total number of disk write operations across all Compute Nodes in the Pool. + DiskWriteIOPS *int64 + + // REQUIRED; The time at which the statistics were last updated. All statistics are limited to the range between startTime + // and lastUpdateTime. + LastUpdateTime *time.Time + + // REQUIRED; The total amount of data in GiB of network reads across all Compute Nodes in the Pool. + NetworkReadGiB *float32 + + // REQUIRED; The total amount of data in GiB of network writes across all Compute Nodes in the Pool. + NetworkWriteGiB *float32 + + // REQUIRED; The peak used disk space in GiB across all Compute Nodes in the Pool. + PeakDiskGiB *float32 + + // REQUIRED; The peak memory usage in GiB across all Compute Nodes in the Pool. + PeakMemoryGiB *float32 + + // REQUIRED; The start time of the time range covered by the statistics. + StartTime *time.Time +} + +// PoolSpecification - Specification for creating a new Pool. +type PoolSpecification struct { + // REQUIRED; The size of the virtual machines in the Pool. All virtual machines in a Pool are the same size. For information + // about available sizes of virtual machines in Pools, see Choose a VM size for Compute Nodes in an Azure Batch Pool (https://learn.microsoft.com/azure/batch/batch-pool-vm-sizes). + VMSize *string + + // The list of Packages to be installed on each Compute Node in the Pool. When creating a pool, the package's application + // ID must be fully qualified (/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationName}). + // Changes to Package references affect all new Nodes joining the Pool, but do not affect Compute Nodes that are already in + // the Pool until they are rebooted or reimaged. There is a maximum of 10 Package references on any given Pool. + ApplicationPackageReferences []ApplicationPackageReference + + // The time interval at which to automatically adjust the Pool size according to the autoscale formula. The default value + // is 15 minutes. The minimum and maximum value are 5 minutes and 168 hours respectively. If you specify a value less than + // 5 minutes or greater than 168 hours, the Batch service rejects the request with an invalid property value error; if you + // are calling the REST API directly, the HTTP status code is 400 (Bad Request). + AutoScaleEvaluationInterval *string + + // The formula for the desired number of Compute Nodes in the Pool. This property must not be specified if enableAutoScale + // is set to false. It is required if enableAutoScale is set to true. The formula is checked for validity before the Pool + // is created. If the formula is not valid, the Batch service rejects the request with detailed error information. + AutoScaleFormula *string + + // For Windows Nodes, the Batch service installs the Certificates to the specified Certificate store and location. For Linux + // Compute Nodes, the Certificates are stored in a directory inside the Task working directory and an environment variable + // AZ_BATCH_CERTIFICATES_DIR is supplied to the Task to query for this location. For Certificates with visibility of 'remoteUser', + // a 'certs' directory is created in the user's home directory (e.g., /home/{user-name}/certs) and Certificates are placed + // in that directory. + // Warning: This property is deprecated and will be removed after February, 2024. + // Please use the [Azure KeyVault Extension](https://learn.microsoft.com/azure/batch/batch-certificate-migration-guide) instead. + CertificateReferences []CertificateReference + + // The display name for the Pool. The display name need not be unique and can contain any Unicode characters up to a maximum + // length of 1024. + DisplayName *string + + // Whether the Pool size should automatically adjust over time. If false, at least one of targetDedicatedNodes and targetLowPriorityNodes + // must be specified. If true, the autoScaleFormula element is required. The Pool automatically resizes according to the formula. + // The default value is false. + EnableAutoScale *bool + + // Whether the Pool permits direct communication between Compute Nodes. Enabling inter-node communication limits the maximum + // size of the Pool due to deployment restrictions on the Compute Nodes of the Pool. This may result in the Pool not reaching + // its desired size. The default value is false. + EnableInterNodeCommunication *bool + + // A list of name-value pairs associated with the Pool as metadata. The Batch service does not assign any meaning to metadata; + // it is solely for the use of user code. + Metadata []MetadataItem + + // A list of file systems to mount on each node in the pool. This supports Azure Files, NFS, CIFS/SMB, and Blobfuse. + MountConfiguration []MountConfiguration + + // The network configuration for the Pool. + NetworkConfiguration *NetworkConfiguration + + // The timeout for allocation of Compute Nodes to the Pool. This timeout applies only to manual scaling; it has no effect + // when enableAutoScale is set to true. The default value is 15 minutes. The minimum value is 5 minutes. If you specify a + // value less than 5 minutes, the Batch service rejects the request with an error; if you are calling the REST API directly, + // the HTTP status code is 400 (Bad Request). + ResizeTimeout *string + + // The user-specified tags associated with the pool.The user-defined tags to be associated with the Azure Batch Pool. When + // specified, these tags are propagated to the backing Azure resources associated with the pool. This property can only be + // specified when the Batch account was created with the poolAllocationMode property set to 'UserSubscription'. + ResourceTags *string + + // A Task to run on each Compute Node as it joins the Pool. The Task runs when the Compute Node is added to the Pool or when + // the Compute Node is restarted. + StartTask *StartTask + + // The desired number of dedicated Compute Nodes in the Pool. This property must not be specified if enableAutoScale is set + // to true. If enableAutoScale is set to false, then you must set either targetDedicatedNodes, targetLowPriorityNodes, or + // both. + TargetDedicatedNodes *int32 + + // The desired number of Spot/Low-priority Compute Nodes in the Pool. This property must not be specified if enableAutoScale + // is set to true. If enableAutoScale is set to false, then you must set either targetDedicatedNodes, targetLowPriorityNodes, + // or both. + TargetLowPriorityNodes *int32 + + // The desired node communication mode for the pool. If omitted, the default value is Default. + TargetNodeCommunicationMode *NodeCommunicationMode + + // How Tasks are distributed across Compute Nodes in a Pool. If not specified, the default is spread. + TaskSchedulingPolicy *TaskSchedulingPolicy + + // The number of task slots that can be used to run concurrent tasks on a single compute node in the pool. The default value + // is 1. The maximum value is the smaller of 4 times the number of cores of the vmSize of the pool or 256. + TaskSlotsPerNode *int32 + + // The upgrade policy for the Pool. Describes an upgrade policy - automatic, manual, or rolling. + UpgradePolicy *UpgradePolicy + + // The list of user Accounts to be created on each Compute Node in the Pool. + UserAccounts []UserAccount + + // The virtual machine configuration for the Pool. This property must be specified. + VirtualMachineConfiguration *VirtualMachineConfiguration +} + +// PoolStatistics - Contains utilization and resource usage statistics for the lifetime of a Pool. +type PoolStatistics struct { + // REQUIRED; The time at which the statistics were last updated. All statistics are limited to the range between startTime + // and lastUpdateTime. + LastUpdateTime *time.Time + + // REQUIRED; The start time of the time range covered by the statistics. + StartTime *time.Time + + // REQUIRED; The URL for the statistics. + URL *string + + // Statistics related to resource consumption by Compute Nodes in the Pool. + ResourceStats *PoolResourceStatistics + + // Statistics related to Pool usage, such as the amount of core-time used. + UsageStats *PoolUsageStatistics +} + +// PoolUsageStatistics - Statistics related to Pool usage information. +type PoolUsageStatistics struct { + // REQUIRED; The aggregated wall-clock time of the dedicated Compute Node cores being part of the Pool. + DedicatedCoreTime *string + + // REQUIRED; The time at which the statistics were last updated. All statistics are limited to the range between startTime + // and lastUpdateTime. + LastUpdateTime *time.Time + + // REQUIRED; The start time of the time range covered by the statistics. + StartTime *time.Time +} + +// PublicIPAddressConfiguration - The public IP Address configuration of the networking configuration of a Pool. +type PublicIPAddressConfiguration struct { + // The list of public IPs which the Batch service will use when provisioning Compute Nodes. The number of IPs specified here + // limits the maximum size of the Pool - 100 dedicated nodes or 100 Spot/Low-priority nodes can be allocated for each public + // IP. For example, a pool needing 250 dedicated VMs would need at least 3 public IPs specified. Each element of this collection + // is of the form: /subscriptions/{subscription}/resourceGroups/{group}/providers/Microsoft.Network/publicIPAddresses/{ip}. + IPAddressIDs []string + + // The provisioning type for Public IP Addresses for the Pool. The default value is BatchManaged. + IPAddressProvisioningType *IPAddressProvisioningType +} + +// RebootNodeContent - Parameters for rebooting an Azure Batch Compute Node. +type RebootNodeContent struct { + // When to reboot the Compute Node and what to do with currently running Tasks. The default value is requeue. + NodeRebootOption *NodeRebootOption +} + +// RecentJob - Information about the most recent Job to run under the Job Schedule. +type RecentJob struct { + // The ID of the Job. + ID *string + + // The URL of the Job. + URL *string +} + +// ReimageNodeContent - Parameters for reimaging an Azure Batch Compute Node. +type ReimageNodeContent struct { + // When to reimage the Compute Node and what to do with currently running Tasks. The default value is requeue. + NodeReimageOption *NodeReimageOption +} + +// RemoveNodeContent - Parameters for removing nodes from an Azure Batch Pool. +type RemoveNodeContent struct { + // REQUIRED; A list containing the IDs of the Compute Nodes to be removed from the specified Pool. A maximum of 100 nodes + // may be removed per request. + NodeList []string + + // Determines what to do with a Compute Node and its running task(s) after it has been selected for deallocation. The default + // value is requeue. + NodeDeallocationOption *NodeDeallocationOption + + // The timeout for removal of Compute Nodes to the Pool. The default value is 15 minutes. The minimum value is 5 minutes. + // If you specify a value less than 5 minutes, the Batch service returns an error; if you are calling the REST API directly, + // the HTTP status code is 400 (Bad Request). + ResizeTimeout *string +} + +// ReplacePoolContent - Parameters for replacing properties on an Azure Batch Pool. +type ReplacePoolContent struct { + // REQUIRED; The list of Application Packages to be installed on each Compute Node in the Pool. The list replaces any existing + // Application Package references on the Pool. Changes to Application Package references affect all new Compute Nodes joining + // the Pool, but do not affect Compute Nodes that are already in the Pool until they are rebooted or reimaged. There is a + // maximum of 10 Application Package references on any given Pool. If omitted, or if you specify an empty collection, any + // existing Application Packages references are removed from the Pool. A maximum of 10 references may be specified on a given + // Pool. + ApplicationPackageReferences []ApplicationPackageReference + + // REQUIRED; This list replaces any existing Certificate references configured on the Pool. + // If you specify an empty collection, any existing Certificate references are removed from the Pool. + // For Windows Nodes, the Batch service installs the Certificates to the specified Certificate store and location. + // For Linux Compute Nodes, the Certificates are stored in a directory inside the Task working directory and an environment + // variable AZ_BATCH_CERTIFICATES_DIR is supplied to the Task to query for this location. + // For Certificates with visibility of 'remoteUser', a 'certs' directory is created in the user's home directory (e.g., /home/{user-name}/certs) + // and Certificates are placed in that directory. + // Warning: This property is deprecated and will be removed after February, 2024. Please use the [Azure KeyVault Extension](https://learn.microsoft.com/azure/batch/batch-certificate-migration-guide) + // instead. + CertificateReferences []CertificateReference + + // REQUIRED; A list of name-value pairs associated with the Pool as metadata. This list replaces any existing metadata configured + // on the Pool. If omitted, or if you specify an empty collection, any existing metadata is removed from the Pool. + Metadata []MetadataItem + + // A Task to run on each Compute Node as it joins the Pool. The Task runs when the Compute Node is added to the Pool or when + // the Compute Node is restarted. If this element is present, it overwrites any existing StartTask. If omitted, any existing + // StartTask is removed from the Pool. + StartTask *StartTask + + // The desired node communication mode for the pool. This setting replaces any existing targetNodeCommunication setting on + // the Pool. If omitted, the existing setting is default. + TargetNodeCommunicationMode *NodeCommunicationMode +} + +// ResizeError - An error that occurred when resizing a Pool. +type ResizeError struct { + // An identifier for the Pool resize error. Codes are invariant and are intended to be consumed programmatically. + Code *string + + // A message describing the Pool resize error, intended to be suitable for display in a user interface. + Message *string + + // A list of additional error details related to the Pool resize error. + Values []NameValuePair +} + +// ResizePoolContent - Parameters for changing the size of an Azure Batch Pool. +type ResizePoolContent struct { + // Determines what to do with a Compute Node and its running task(s) if the Pool size is decreasing. The default value is + // requeue. + NodeDeallocationOption *NodeDeallocationOption + + // The timeout for allocation of Nodes to the Pool or removal of Compute Nodes from the Pool. The default value is 15 minutes. + // The minimum value is 5 minutes. If you specify a value less than 5 minutes, the Batch service returns an error; if you + // are calling the REST API directly, the HTTP status code is 400 (Bad Request). + ResizeTimeout *string + + // The desired number of dedicated Compute Nodes in the Pool. + TargetDedicatedNodes *int32 + + // The desired number of Spot/Low-priority Compute Nodes in the Pool. + TargetLowPriorityNodes *int32 +} + +// ResourceFile - A single file or multiple files to be downloaded to a Compute Node. +type ResourceFile struct { + // The storage container name in the auto storage Account. The autoStorageContainerName, storageContainerUrl and httpUrl properties + // are mutually exclusive and one of them must be specified. + AutoStorageContainerName *string + + // The blob prefix to use when downloading blobs from an Azure Storage container. Only the blobs whose names begin with the + // specified prefix will be downloaded. The property is valid only when autoStorageContainerName or storageContainerUrl is + // used. This prefix can be a partial filename or a subdirectory. If a prefix is not specified, all the files in the container + // will be downloaded. + BlobPrefix *string + + // The file permission mode attribute in octal format. This property applies only to files being downloaded to Linux Compute + // Nodes. It will be ignored if it is specified for a resourceFile which will be downloaded to a Windows Compute Node. If + // this property is not specified for a Linux Compute Node, then a default value of 0770 is applied to the file. + FileMode *string + + // The location on the Compute Node to which to download the file(s), relative to the Task's working directory. If the httpUrl + // property is specified, the filePath is required and describes the path which the file will be downloaded to, including + // the filename. Otherwise, if the autoStorageContainerName or storageContainerUrl property is specified, filePath is optional + // and is the directory to download the files to. In the case where filePath is used as a directory, any directory structure + // already associated with the input data will be retained in full and appended to the specified filePath directory. The specified + // relative path cannot break out of the Task's working directory (for example by using '..'). + FilePath *string + + // The URL of the file to download. The autoStorageContainerName, storageContainerUrl and httpUrl properties are mutually + // exclusive and one of them must be specified. If the URL points to Azure Blob Storage, it must be readable from compute + // nodes. There are three ways to get such a URL for a blob in Azure storage: include a Shared Access Signature (SAS) granting + // read permissions on the blob, use a managed identity with read permission, or set the ACL for the blob or its container + // to allow public access. + HTTPURL *string + + // The reference to the user assigned identity to use to access Azure Blob Storage specified by storageContainerUrl or httpUrl. + IdentityReference *NodeIdentityReference + + // The URL of the blob container within Azure Blob Storage. The autoStorageContainerName, storageContainerUrl and httpUrl + // properties are mutually exclusive and one of them must be specified. This URL must be readable and listable from compute + // nodes. There are three ways to get such a URL for a container in Azure storage: include a Shared Access Signature (SAS) + // granting read and list permissions on the container, use a managed identity with read and list permissions, or set the + // ACL for the container to allow public access. + StorageContainerURL *string +} + +// RollingUpgradePolicy - The configuration parameters used while performing a rolling upgrade. +type RollingUpgradePolicy struct { + // Allow VMSS to ignore AZ boundaries when constructing upgrade batches. Take into consideration the Update Domain and maxBatchInstancePercent + // to determine the batch size. This field is able to be set to true or false only when using NodePlacementConfiguration as + // Zonal. + EnableCrossZoneUpgrade *bool + + // The maximum percent of total virtual machine instances that will be upgraded simultaneously by the rolling upgrade in one + // batch. As this is a maximum, unhealthy instances in previous or future batches can cause the percentage of instances in + // a batch to decrease to ensure higher reliability. The value of this field should be between 5 and 100, inclusive. If both + // maxBatchInstancePercent and maxUnhealthyInstancePercent are assigned with value, the value of maxBatchInstancePercent should + // not be more than maxUnhealthyInstancePercent. + MaxBatchInstancePercent *int32 + + // The maximum percentage of the total virtual machine instances in the scale set that can be simultaneously unhealthy, either + // as a result of being upgraded, or by being found in an unhealthy state by the virtual machine health checks before the + // rolling upgrade aborts. This constraint will be checked prior to starting any batch. The value of this field should be + // between 5 and 100, inclusive. If both maxBatchInstancePercent and maxUnhealthyInstancePercent are assigned with value, + // the value of maxBatchInstancePercent should not be more than maxUnhealthyInstancePercent. + MaxUnhealthyInstancePercent *int32 + + // The maximum percentage of upgraded virtual machine instances that can be found to be in an unhealthy state. This check + // will happen after each batch is upgraded. If this percentage is ever exceeded, the rolling update aborts. The value of + // this field should be between 0 and 100, inclusive. + MaxUnhealthyUpgradedInstancePercent *int32 + + // The wait time between completing the update for all virtual machines in one batch and starting the next batch. The time + // duration should be specified in ISO 8601 format.. + PauseTimeBetweenBatches *string + + // Upgrade all unhealthy instances in a scale set before any healthy instances. + PrioritizeUnhealthyInstances *bool + + // Rollback failed instances to previous model if the Rolling Upgrade policy is violated. + RollbackFailedInstancesOnPolicyBreach *bool +} + +// SecurityProfile - Specifies the security profile settings for the virtual machine or virtual machine scale set. +type SecurityProfile struct { + // REQUIRED; This property can be used by user in the request to enable or disable the Host Encryption for the virtual machine + // or virtual machine scale set. This will enable the encryption for all the disks including Resource/Temp disk at host itself. + // For more information on encryption at host requirements, please refer to https://learn.microsoft.com/azure/virtual-machines/disk-encryption#supported-vm-sizes. + EncryptionAtHost *bool + + // REQUIRED; Specifies the SecurityType of the virtual machine. It has to be set to any specified value to enable UefiSettings. + SecurityType *SecurityTypes + + // REQUIRED; Specifies the security settings like secure boot and vTPM used while creating the virtual machine. Specifies + // the security settings like secure boot and vTPM used while creating the virtual machine. + UefiSettings *UEFISettings +} + +// ServiceArtifactReference - Specifies the service artifact reference id used to set same image version +// for all virtual machines in the scale set when using 'latest' image version. +type ServiceArtifactReference struct { + // REQUIRED; The service artifact reference id of ServiceArtifactReference. The service artifact reference id in the form + // of /subscriptions/{subscriptionId}/resourceGroups/{resourceGroup}/providers/Microsoft.Compute/galleries/{galleryName}/serviceArtifacts/{serviceArtifactName}/vmArtifactsProfiles/{vmArtifactsProfilesName} + ID *string +} + +// StartTask - Batch will retry Tasks when a recovery operation is triggered on a Node. +// Examples of recovery operations include (but are not limited to) when an +// unhealthy Node is rebooted or a Compute Node disappeared due to host failure. +// Retries due to recovery operations are independent of and are not counted +// against the maxTaskRetryCount. Even if the maxTaskRetryCount is 0, an internal +// retry due to a recovery operation may occur. Because of this, all Tasks should +// be idempotent. This means Tasks need to tolerate being interrupted and +// restarted without causing any corruption or duplicate data. The best practice +// for long running Tasks is to use some form of checkpointing. In some cases the +// StartTask may be re-run even though the Compute Node was not rebooted. Special +// care should be taken to avoid StartTasks which create breakaway process or +// install/launch services from the StartTask working directory, as this will +// block Batch from being able to re-run the StartTask. +type StartTask struct { + // REQUIRED; The command line of the StartTask. The command line does not run under a shell, and therefore cannot take advantage + // of shell features such as environment variable expansion. If you want to take advantage of such features, you should invoke + // the shell in the command line, for example using "cmd /c MyCommand" in Windows or "/bin/sh -c MyCommand" in Linux. If the + // command line refers to file paths, it should use a relative path (relative to the Task working directory), or use the Batch + // provided environment variable (https://learn.microsoft.com/azure/batch/batch-compute-node-environment-variables). + CommandLine *string + + // The settings for the container under which the StartTask runs. When this is specified, all directories recursively below + // the AZ_BATCH_NODE_ROOT_DIR (the root of Azure Batch directories on the node) are mapped into the container, all Task environment + // variables are mapped into the container, and the Task command line is executed in the container. Files produced in the + // container outside of AZ_BATCH_NODE_ROOT_DIR might not be reflected to the host disk, meaning that Batch file APIs will + // not be able to access those files. + ContainerSettings *TaskContainerSettings + + // A list of environment variable settings for the StartTask. + EnvironmentSettings []EnvironmentSetting + + // The maximum number of times the Task may be retried. The Batch service retries a Task if its exit code is nonzero. Note + // that this value specifically controls the number of retries. The Batch service will try the Task once, and may then retry + // up to this limit. For example, if the maximum retry count is 3, Batch tries the Task up to 4 times (one initial try and + // 3 retries). If the maximum retry count is 0, the Batch service does not retry the Task. If the maximum retry count is -1, + // the Batch service retries the Task without limit, however this is not recommended for a start task or any task. The default + // value is 0 (no retries). + MaxTaskRetryCount *int32 + + // A list of files that the Batch service will download to the Compute Node before running the command line. There is a maximum + // size for the list of resource files. When the max size is exceeded, the request will fail and the response error code will + // be RequestEntityTooLarge. If this occurs, the collection of ResourceFiles must be reduced in size. This can be achieved + // using .zip files, Application Packages, or Docker Containers. Files listed under this element are located in the Task's + // working directory. + ResourceFiles []ResourceFile + + // The user identity under which the StartTask runs. If omitted, the Task runs as a non-administrative user unique to the + // Task. + UserIdentity *UserIdentity + + // Whether the Batch service should wait for the StartTask to complete successfully (that is, to exit with exit code 0) before + // scheduling any Tasks on the Compute Node. If true and the StartTask fails on a Node, the Batch service retries the StartTask + // up to its maximum retry count (maxTaskRetryCount). If the Task has still not completed successfully after all retries, + // then the Batch service marks the Node unusable, and will not schedule Tasks to it. This condition can be detected via the + // Compute Node state and failure info details. If false, the Batch service will not wait for the StartTask to complete. In + // this case, other Tasks can start executing on the Compute Node while the StartTask is still running; and even if the StartTask + // fails, new Tasks will continue to be scheduled on the Compute Node. The default is true. + WaitForSuccess *bool +} + +// StartTaskInfo - Information about a StartTask running on a Compute Node. +type StartTaskInfo struct { + // REQUIRED; The number of times the Task has been retried by the Batch service. Task application failures (non-zero exit + // code) are retried, pre-processing errors (the Task could not be run) and file upload errors are not retried. The Batch + // service will retry the Task up to the limit specified by the constraints. + RetryCount *int32 + + // REQUIRED; The time at which the StartTask started running. This value is reset every time the Task is restarted or retried + // (that is, this is the most recent time at which the StartTask started running). + StartTime *time.Time + + // REQUIRED; The state of the StartTask on the Compute Node. + State *StartTaskState + + // Information about the container under which the Task is executing. This property is set only if the Task runs in a container + // context. + ContainerInfo *TaskContainerExecutionInfo + + // The time at which the StartTask stopped running. This is the end time of the most recent run of the StartTask, if that + // run has completed (even if that run failed and a retry is pending). This element is not present if the StartTask is currently + // running. + EndTime *time.Time + + // The exit code of the program specified on the StartTask command line. This property is set only if the StartTask is in + // the completed state. In general, the exit code for a process reflects the specific convention implemented by the application + // developer for that process. If you use the exit code value to make decisions in your code, be sure that you know the exit + // code convention used by the application process. However, if the Batch service terminates the StartTask (due to timeout, + // or user termination via the API) you may see an operating system-defined exit code. + ExitCode *int32 + + // Information describing the Task failure, if any. This property is set only if the Task is in the completed state and encountered + // a failure. + FailureInfo *TaskFailureInfo + + // The most recent time at which a retry of the Task started running. This element is present only if the Task was retried + // (i.e. retryCount is nonzero). If present, this is typically the same as startTime, but may be different if the Task has + // been restarted for reasons other than retry; for example, if the Compute Node was rebooted during a retry, then the startTime + // is updated but the lastRetryTime is not. + LastRetryTime *time.Time + + // The result of the Task execution. If the value is 'failed', then the details of the failure can be found in the failureInfo + // property. + Result *TaskExecutionResult +} + +// Subtask - Information about an Azure Batch subtask. +type Subtask struct { + // Information about the container under which the Task is executing. This property is set only if the Task runs in a container + // context. + ContainerInfo *TaskContainerExecutionInfo + + // The time at which the subtask completed. This property is set only if the subtask is in the Completed state. + EndTime *time.Time + + // The exit code of the program specified on the subtask command line. This property is set only if the subtask is in the + // completed state. In general, the exit code for a process reflects the specific convention implemented by the application + // developer for that process. If you use the exit code value to make decisions in your code, be sure that you know the exit + // code convention used by the application process. However, if the Batch service terminates the subtask (due to timeout, + // or user termination via the API) you may see an operating system-defined exit code. + ExitCode *int32 + + // Information describing the Task failure, if any. This property is set only if the Task is in the completed state and encountered + // a failure. + FailureInfo *TaskFailureInfo + + // The ID of the subtask. + ID *int32 + + // Information about the Compute Node on which the subtask ran. + NodeInfo *NodeInfo + + // The previous state of the subtask. This property is not set if the subtask is in its initial running state. + PreviousState *SubtaskState + + // The time at which the subtask entered its previous state. This property is not set if the subtask is in its initial running + // state. + PreviousStateTransitionTime *time.Time + + // The result of the Task execution. If the value is 'failed', then the details of the failure can be found in the failureInfo + // property. + Result *TaskExecutionResult + + // The time at which the subtask started running. If the subtask has been restarted or retried, this is the most recent time + // at which the subtask started running. + StartTime *time.Time + + // The current state of the subtask. + State *SubtaskState + + // The time at which the subtask entered its current state. + StateTransitionTime *time.Time +} + +// SupportedImage - A reference to the Azure Virtual Machines Marketplace Image and additional +// information about the Image. +type SupportedImage struct { + // REQUIRED; The reference to the Azure Virtual Machine's Marketplace Image. + ImageReference *ImageReference + + // REQUIRED; The ID of the Compute Node agent SKU which the Image supports. + NodeAgentSKUID *string + + // REQUIRED; The type of operating system (e.g. Windows or Linux) of the Image. + OSType *OSType + + // REQUIRED; Whether the Azure Batch service actively verifies that the Image is compatible with the associated Compute Node + // agent SKU. + VerificationType *ImageVerificationType + + // The time when the Azure Batch service will stop accepting create Pool requests for the Image. + BatchSupportEndOfLife *time.Time + + // The capabilities or features which the Image supports. Not every capability of the Image is listed. Capabilities in this + // list are considered of special interest and are generally related to integration with other features in the Azure Batch + // service. + Capabilities []string +} + +// Task - Batch will retry Tasks when a recovery operation is triggered on a Node. +// Examples of recovery operations include (but are not limited to) when an +// unhealthy Node is rebooted or a Compute Node disappeared due to host failure. +// Retries due to recovery operations are independent of and are not counted +// against the maxTaskRetryCount. Even if the maxTaskRetryCount is 0, an internal +// retry due to a recovery operation may occur. Because of this, all Tasks should +// be idempotent. This means Tasks need to tolerate being interrupted and +// restarted without causing any corruption or duplicate data. The best practice +// for long running Tasks is to use some form of checkpointing. +type Task struct { + // The execution constraints that apply to this Task. + Constraints *TaskConstraints + + // READ-ONLY; A locality hint that can be used by the Batch service to select a Compute Node on which to start the new Task. + AffinityInfo *AffinityInfo + + // READ-ONLY; A list of Packages that the Batch service will deploy to the Compute Node before running the command line. Application + // packages are downloaded and deployed to a shared directory, not the Task working directory. Therefore, if a referenced + // package is already on the Node, and is up to date, then it is not re-downloaded; the existing copy on the Compute Node + // is used. If a referenced Package cannot be installed, for example because the package has been deleted or because download + // failed, the Task fails. + ApplicationPackageReferences []ApplicationPackageReference + + // READ-ONLY; The settings for an authentication token that the Task can use to perform Batch service operations. If this + // property is set, the Batch service provides the Task with an authentication token which can be used to authenticate Batch + // service operations without requiring an Account access key. The token is provided via the AZ_BATCH_AUTHENTICATION_TOKEN + // environment variable. The operations that the Task can carry out using the token depend on the settings. For example, a + // Task can request Job permissions in order to add other Tasks to the Job, or check the status of the Job or of other Tasks + // under the Job. + AuthenticationTokenSettings *AuthenticationTokenSettings + + // READ-ONLY; The command line of the Task. For multi-instance Tasks, the command line is executed as the primary Task, after + // the primary Task and all subtasks have finished executing the coordination command line. The command line does not run + // under a shell, and therefore cannot take advantage of shell features such as environment variable expansion. If you want + // to take advantage of such features, you should invoke the shell in the command line, for example using "cmd /c MyCommand" + // in Windows or "/bin/sh -c MyCommand" in Linux. If the command line refers to file paths, it should use a relative path + // (relative to the Task working directory), or use the Batch provided environment variable (https://learn.microsoft.com/azure/batch/batch-compute-node-environment-variables). + CommandLine *string + + // READ-ONLY; The settings for the container under which the Task runs. If the Pool that will run this Task has containerConfiguration + // set, this must be set as well. If the Pool that will run this Task doesn't have containerConfiguration set, this must not + // be set. When this is specified, all directories recursively below the AZ_BATCH_NODE_ROOT_DIR (the root of Azure Batch directories + // on the node) are mapped into the container, all Task environment variables are mapped into the container, and the Task + // command line is executed in the container. Files produced in the container outside of AZ_BATCH_NODE_ROOT_DIR might not + // be reflected to the host disk, meaning that Batch file APIs will not be able to access those files. + ContainerSettings *TaskContainerSettings + + // READ-ONLY; The creation time of the Task. + CreationTime *time.Time + + // READ-ONLY; The Tasks that this Task depends on. This Task will not be scheduled until all Tasks that it depends on have + // completed successfully. If any of those Tasks fail and exhaust their retry counts, this Task will never be scheduled. + DependsOn *TaskDependencies + + // READ-ONLY; A display name for the Task. The display name need not be unique and can contain any Unicode characters up to + // a maximum length of 1024. + DisplayName *string + + // READ-ONLY; The ETag of the Task. This is an opaque string. You can use it to detect whether the Task has changed between + // requests. In particular, you can be pass the ETag when updating a Task to specify that your changes should take effect + // only if nobody else has modified the Task in the meantime. + ETag *string + + // READ-ONLY; A list of environment variable settings for the Task. + EnvironmentSettings []EnvironmentSetting + + // READ-ONLY; Information about the execution of the Task. + ExecutionInfo *TaskExecutionInfo + + // READ-ONLY; How the Batch service should respond when the Task completes. + ExitConditions *ExitConditions + + // READ-ONLY; A string that uniquely identifies the Task within the Job. The ID can contain any combination of alphanumeric + // characters including hyphens and underscores, and cannot contain more than 64 characters. + ID *string + + // READ-ONLY; The last modified time of the Task. + LastModified *time.Time + + // READ-ONLY; An object that indicates that the Task is a multi-instance Task, and contains information about how to run the + // multi-instance Task. + MultiInstanceSettings *MultiInstanceSettings + + // READ-ONLY; Information about the Compute Node on which the Task ran. + NodeInfo *NodeInfo + + // READ-ONLY; A list of files that the Batch service will upload from the Compute Node after running the command line. For + // multi-instance Tasks, the files will only be uploaded from the Compute Node on which the primary Task is executed. + OutputFiles []OutputFile + + // READ-ONLY; The previous state of the Task. This property is not set if the Task is in its initial Active state. + PreviousState *TaskState + + // READ-ONLY; The time at which the Task entered its previous state. This property is not set if the Task is in its initial + // Active state. + PreviousStateTransitionTime *time.Time + + // READ-ONLY; The number of scheduling slots that the Task requires to run. The default is 1. A Task can only be scheduled + // to run on a compute node if the node has enough free scheduling slots available. For multi-instance Tasks, this must be + // 1. + RequiredSlots *int32 + + // READ-ONLY; A list of files that the Batch service will download to the Compute Node before running the command line. For + // multi-instance Tasks, the resource files will only be downloaded to the Compute Node on which the primary Task is executed. + // There is a maximum size for the list of resource files. When the max size is exceeded, the request will fail and the response + // error code will be RequestEntityTooLarge. If this occurs, the collection of ResourceFiles must be reduced in size. This + // can be achieved using .zip files, Application Packages, or Docker Containers. + ResourceFiles []ResourceFile + + // READ-ONLY; The current state of the Task. + State *TaskState + + // READ-ONLY; The time at which the Task entered its current state. + StateTransitionTime *time.Time + + // READ-ONLY; Resource usage statistics for the Task. + Stats *TaskStatistics + + // READ-ONLY; The URL of the Task. + URL *string + + // READ-ONLY; The user identity under which the Task runs. If omitted, the Task runs as a non-administrative user unique to + // the Task. + UserIdentity *UserIdentity +} + +// TaskAddResult - Result for a single Task added as part of an add Task collection operation. +type TaskAddResult struct { + // REQUIRED; The status of the add Task request. + Status *TaskAddStatus + + // REQUIRED; The ID of the Task for which this is the result. + TaskID *string + + // The ETag of the Task, if the Task was successfully added. You can use this to detect whether the Task has changed between + // requests. In particular, you can be pass the ETag with an Update Task request to specify that your changes should take + // effect only if nobody else has modified the Job in the meantime. + ETag *string + + // The error encountered while attempting to add the Task. + Error *Error + + // The last modified time of the Task. + LastModified *time.Time + + // The URL of the Task, if the Task was successfully added. + Location *string +} + +// TaskConstraints - Execution constraints to apply to a Task. +type TaskConstraints struct { + // The maximum number of times the Task may be retried. The Batch service retries a Task if its exit code is nonzero. Note + // that this value specifically controls the number of retries for the Task executable due to a nonzero exit code. The Batch + // service will try the Task once, and may then retry up to this limit. For example, if the maximum retry count is 3, Batch + // tries the Task up to 4 times (one initial try and 3 retries). If the maximum retry count is 0, the Batch service does not + // retry the Task after the first attempt. If the maximum retry count is -1, the Batch service retries the Task without limit, + // however this is not recommended for a start task or any task. The default value is 0 (no retries). + MaxTaskRetryCount *int32 + + // The maximum elapsed time that the Task may run, measured from the time the Task starts. If the Task does not complete within + // the time limit, the Batch service terminates it. If this is not specified, there is no time limit on how long the Task + // may run. + MaxWallClockTime *string + + // The minimum time to retain the Task directory on the Compute Node where it ran, from the time it completes execution. After + // this time, the Batch service may delete the Task directory and all its contents. The default is 7 days, i.e. the Task directory + // will be retained for 7 days unless the Compute Node is removed or the Job is deleted. + RetentionTime *string +} + +// TaskContainerExecutionInfo - Contains information about the container which a Task is executing. +type TaskContainerExecutionInfo struct { + // The ID of the container. + ContainerID *string + + // Detailed error information about the container. This is the detailed error string from the Docker service, if available. + // It is equivalent to the error field returned by "docker inspect". + Error *string + + // The state of the container. This is the state of the container according to the Docker service. It is equivalent to the + // status field returned by "docker inspect". + State *string +} + +// TaskContainerSettings - The container settings for a Task. +type TaskContainerSettings struct { + // REQUIRED; The Image to use to create the container in which the Task will run. This is the full Image reference, as would + // be specified to "docker pull". If no tag is provided as part of the Image name, the tag ":latest" is used as a default. + ImageName *string + + // The paths you want to mounted to container task. If this array is null or be not present, container task will mount entire + // temporary disk drive in windows (or AZ_BATCH_NODE_ROOT_DIR in Linux). It won't' mount any data paths into container if + // this array is set as empty. + ContainerHostBatchBindMounts []ContainerHostBindMountEntry + + // Additional options to the container create command. These additional options are supplied as arguments to the "docker create" + // command, in addition to those controlled by the Batch Service. + ContainerRunOptions *string + + // The private registry which contains the container Image. This setting can be omitted if was already provided at Pool creation. + Registry *ContainerRegistryReference + + // The location of the container Task working directory. The default is 'taskWorkingDirectory'. + WorkingDirectory *ContainerWorkingDirectory +} + +// TaskCounts - The Task counts for a Job. +type TaskCounts struct { + // REQUIRED; The number of Tasks in the active state. + Active *int32 + + // REQUIRED; The number of Tasks in the completed state. + Completed *int32 + + // REQUIRED; The number of Tasks which failed. A Task fails if its result (found in the executionInfo property) is 'failure'. + Failed *int32 + + // REQUIRED; The number of Tasks in the running or preparing state. + Running *int32 + + // REQUIRED; The number of Tasks which succeeded. A Task succeeds if its result (found in the executionInfo property) is 'success'. + Succeeded *int32 +} + +// TaskCountsResult - The Task and TaskSlot counts for a Job. +type TaskCountsResult struct { + // REQUIRED; The number of Tasks per state. + TaskCounts *TaskCounts + + // REQUIRED; The number of TaskSlots required by Tasks per state. + TaskSlotCounts *TaskSlotCounts +} + +// TaskDependencies - Specifies any dependencies of a Task. Any Task that is explicitly specified or +// within a dependency range must complete before the dependant Task will be +// scheduled. +type TaskDependencies struct { + // The list of Task ID ranges that this Task depends on. All Tasks in all ranges must complete successfully before the dependent + // Task can be scheduled. + TaskIDRanges []TaskIDRange + + // The list of Task IDs that this Task depends on. All Tasks in this list must complete successfully before the dependent + // Task can be scheduled. The taskIds collection is limited to 64000 characters total (i.e. the combined length of all Task + // IDs). If the taskIds collection exceeds the maximum length, the Add Task request fails with error code TaskDependencyListTooLong. + // In this case consider using Task ID ranges instead. + TaskIDs []string +} + +// TaskExecutionInfo - Information about the execution of a Task. +type TaskExecutionInfo struct { + // REQUIRED; The number of times the Task has been requeued by the Batch service as the result of a user request. When the + // user removes Compute Nodes from a Pool (by resizing/shrinking the pool) or when the Job is being disabled, the user can + // specify that running Tasks on the Compute Nodes be requeued for execution. This count tracks how many times the Task has + // been requeued for these reasons. + RequeueCount *int32 + + // REQUIRED; The number of times the Task has been retried by the Batch service. Task application failures (non-zero exit + // code) are retried, pre-processing errors (the Task could not be run) and file upload errors are not retried. The Batch + // service will retry the Task up to the limit specified by the constraints. + RetryCount *int32 + + // Information about the container under which the Task is executing. This property is set only if the Task runs in a container + // context. + ContainerInfo *TaskContainerExecutionInfo + + // The time at which the Task completed. This property is set only if the Task is in the Completed state. + EndTime *time.Time + + // The exit code of the program specified on the Task command line. This property is set only if the Task is in the completed + // state. In general, the exit code for a process reflects the specific convention implemented by the application developer + // for that process. If you use the exit code value to make decisions in your code, be sure that you know the exit code convention + // used by the application process. However, if the Batch service terminates the Task (due to timeout, or user termination + // via the API) you may see an operating system-defined exit code. + ExitCode *int32 + + // Information describing the Task failure, if any. This property is set only if the Task is in the completed state and encountered + // a failure. + FailureInfo *TaskFailureInfo + + // The most recent time at which the Task has been requeued by the Batch service as the result of a user request. This property + // is set only if the requeueCount is nonzero. + LastRequeueTime *time.Time + + // The most recent time at which a retry of the Task started running. This element is present only if the Task was retried + // (i.e. retryCount is nonzero). If present, this is typically the same as startTime, but may be different if the Task has + // been restarted for reasons other than retry; for example, if the Compute Node was rebooted during a retry, then the startTime + // is updated but the lastRetryTime is not. + LastRetryTime *time.Time + + // The result of the Task execution. If the value is 'failed', then the details of the failure can be found in the failureInfo + // property. + Result *TaskExecutionResult + + // The time at which the Task started running. 'Running' corresponds to the running state, so if the Task specifies resource + // files or Packages, then the start time reflects the time at which the Task started downloading or deploying these. If the + // Task has been restarted or retried, this is the most recent time at which the Task started running. This property is present + // only for Tasks that are in the running or completed state. + StartTime *time.Time +} + +// TaskFailureInfo - Information about a Task failure. +type TaskFailureInfo struct { + // REQUIRED; The category of the Task error. + Category *ErrorCategory + + // An identifier for the Task error. Codes are invariant and are intended to be consumed programmatically. + Code *string + + // A list of additional details related to the error. + Details []NameValuePair + + // A message describing the Task error, intended to be suitable for display in a user interface. + Message *string +} + +// TaskGroup - A collection of Azure Batch Tasks to add. +type TaskGroup struct { + // REQUIRED; The collection of Tasks to add. The maximum count of Tasks is 100. The total serialized size of this collection + // must be less than 1MB. If it is greater than 1MB (for example if each Task has 100's of resource files or environment variables), + // the request will fail with code 'RequestBodyTooLarge' and should be retried again with fewer Tasks. + Value []CreateTaskContent +} + +// TaskIDRange - The start and end of the range are inclusive. For example, if a range has start +// 9 and end 12, then it represents Tasks '9', '10', '11' and '12'. +type TaskIDRange struct { + // REQUIRED; The last Task ID in the range. + End *int32 + + // REQUIRED; The first Task ID in the range. + Start *int32 +} + +// TaskInfo - Information about a Task running on a Compute Node. +type TaskInfo struct { + // REQUIRED; The current state of the Task. + TaskState *TaskState + + // Information about the execution of the Task. + ExecutionInfo *TaskExecutionInfo + + // The ID of the Job to which the Task belongs. + JobID *string + + // The ID of the subtask if the Task is a multi-instance Task. + SubtaskID *int32 + + // The ID of the Task. + TaskID *string + + // The URL of the Task. + TaskURL *string +} + +// TaskListResult - The result of listing the Tasks in a Job. +type TaskListResult struct { + // The URL to get the next set of results. + NextLink *string + + // The list of Tasks. + Value []Task +} + +// TaskListSubtasksResult - The result of listing the subtasks of a Task. +type TaskListSubtasksResult struct { + // The URL to get the next set of results. + NextLink *string + + // The list of subtasks. + Value []Subtask +} + +// TaskSchedulingPolicy - Specifies how Tasks should be distributed across Compute Nodes. +type TaskSchedulingPolicy struct { + // REQUIRED; How Tasks are distributed across Compute Nodes in a Pool. If not specified, the default is spread. + NodeFillType *NodeFillType +} + +// TaskSlotCounts - The TaskSlot counts for a Job. +type TaskSlotCounts struct { + // REQUIRED; The number of TaskSlots for active Tasks. + Active *int32 + + // REQUIRED; The number of TaskSlots for completed Tasks. + Completed *int32 + + // REQUIRED; The number of TaskSlots for failed Tasks. + Failed *int32 + + // REQUIRED; The number of TaskSlots for running Tasks. + Running *int32 + + // REQUIRED; The number of TaskSlots for succeeded Tasks. + Succeeded *int32 +} + +// TaskStatistics - Resource usage statistics for a Task. +type TaskStatistics struct { + // REQUIRED; The total kernel mode CPU time (summed across all cores and all Compute Nodes) consumed by the Task. + KernelCPUTime *string + + // REQUIRED; The time at which the statistics were last updated. All statistics are limited to the range between startTime + // and lastUpdateTime. + LastUpdateTime *time.Time + + // REQUIRED; The total gibibytes read from disk by the Task. + ReadIOGiB *float32 + + // REQUIRED; The total number of disk read operations made by the Task. + ReadIOPS *int64 + + // REQUIRED; The start time of the time range covered by the statistics. + StartTime *time.Time + + // REQUIRED; The URL of the statistics. + URL *string + + // REQUIRED; The total user mode CPU time (summed across all cores and all Compute Nodes) consumed by the Task. + UserCPUTime *string + + // REQUIRED; The total wait time of the Task. The wait time for a Task is defined as the elapsed time between the creation + // of the Task and the start of Task execution. (If the Task is retried due to failures, the wait time is the time to the + // most recent Task execution.). + WaitTime *string + + // REQUIRED; The total wall clock time of the Task. The wall clock time is the elapsed time from when the Task started running + // on a Compute Node to when it finished (or to the last time the statistics were updated, if the Task had not finished by + // then). If the Task was retried, this includes the wall clock time of all the Task retries. + WallClockTime *string + + // REQUIRED; The total gibibytes written to disk by the Task. + WriteIOGiB *float32 + + // REQUIRED; The total number of disk write operations made by the Task. + WriteIOPS *int64 +} + +// TerminateJobContent - Parameters for terminating an Azure Batch Job. +type TerminateJobContent struct { + // The text you want to appear as the Job's TerminationReason. The default is 'UserTerminate'. + TerminationReason *string +} + +// UEFISettings - Specifies the security settings like secure boot and vTPM used while creating the virtual machine. +type UEFISettings struct { + // Specifies whether secure boot should be enabled on the virtual machine. + SecureBootEnabled *bool + + // Specifies whether vTPM should be enabled on the virtual machine. + VTPMEnabled *bool +} + +// UpdateJobContent - Parameters for updating an Azure Batch Job. +type UpdateJobContent struct { + // Whether Tasks in this job can be preempted by other high priority jobs. If the value is set to True, other high priority + // jobs submitted to the system will take precedence and will be able requeue tasks from this job. You can update a job's + // allowTaskPreemption after it has been created using the update job API. + AllowTaskPreemption *bool + + // The execution constraints for the Job. If omitted, the existing execution constraints are left unchanged. + Constraints *JobConstraints + + // The maximum number of tasks that can be executed in parallel for the job. The value of maxParallelTasks must be -1 or greater + // than 0 if specified. If not specified, the default value is -1, which means there's no limit to the number of tasks that + // can be run at once. You can update a job's maxParallelTasks after it has been created using the update job API. + MaxParallelTasks *int32 + + // A list of name-value pairs associated with the Job as metadata. If omitted, the existing Job metadata is left unchanged. + Metadata []MetadataItem + + // The network configuration for the Job. + NetworkConfiguration *JobNetworkConfiguration + + // The action the Batch service should take when all Tasks in the Job are in the completed state. If omitted, the completion + // behavior is left unchanged. You may not change the value from terminatejob to noaction - that is, once you have engaged + // automatic Job termination, you cannot turn it off again. If you try to do this, the request fails with an 'invalid property + // value' error response; if you are calling the REST API directly, the HTTP status code is 400 (Bad Request). + OnAllTasksComplete *OnAllTasksComplete + + // The Pool on which the Batch service runs the Job's Tasks. You may change the Pool for a Job only when the Job is disabled. + // The Patch Job call will fail if you include the poolInfo element and the Job is not disabled. If you specify an autoPoolSpecification + // in the poolInfo, only the keepAlive property of the autoPoolSpecification can be updated, and then only if the autoPoolSpecification + // has a poolLifetimeOption of Job (other job properties can be updated as normal). If omitted, the Job continues to run on + // its current Pool. + PoolInfo *PoolInfo + + // The priority of the Job. Priority values can range from -1000 to 1000, with -1000 being the lowest priority and 1000 being + // the highest priority. If omitted, the priority of the Job is left unchanged. + Priority *int32 +} + +// UpdateJobScheduleContent - Parameters for updating an Azure Batch Job Schedule. +type UpdateJobScheduleContent struct { + // The details of the Jobs to be created on this schedule. Updates affect only Jobs that are started after the update has + // taken place. Any currently active Job continues with the older specification. + JobSpecification *JobSpecification + + // A list of name-value pairs associated with the Job Schedule as metadata. If you do not specify this element, existing metadata + // is left unchanged. + Metadata []MetadataItem + + // The schedule according to which Jobs will be created. All times are fixed respective to UTC and are not impacted by daylight + // saving time. If you do not specify this element, the existing schedule is left unchanged. + Schedule *JobScheduleConfiguration +} + +// UpdateNodeUserContent - Parameters for updating a user account for RDP or SSH access on an Azure Batch Compute Node. +type UpdateNodeUserContent struct { + // The time at which the Account should expire. If omitted, the default is 1 day from the current time. For Linux Compute + // Nodes, the expiryTime has a precision up to a day. + ExpiryTime *time.Time + + // The password of the Account. The password is required for Windows Compute Nodes. For Linux Compute Nodes, the password + // can optionally be specified along with the sshPublicKey property. If omitted, any existing password is removed. + Password *string + + // The SSH public key that can be used for remote login to the Compute Node. The public key should be compatible with OpenSSH + // encoding and should be base 64 encoded. This property can be specified only for Linux Compute Nodes. If this is specified + // for a Windows Compute Node, then the Batch service rejects the request; if you are calling the REST API directly, the HTTP + // status code is 400 (Bad Request). If omitted, any existing SSH public key is removed. + SSHPublicKey *string +} + +// UpdatePoolContent - Parameters for updating an Azure Batch Pool. +type UpdatePoolContent struct { + // A list of Packages to be installed on each Compute Node in the Pool. Changes to Package references affect all new Nodes + // joining the Pool, but do not affect Compute Nodes that are already in the Pool until they are rebooted or reimaged. If + // this element is present, it replaces any existing Package references. If you specify an empty collection, then all Package + // references are removed from the Pool. If omitted, any existing Package references are left unchanged. + ApplicationPackageReferences []ApplicationPackageReference + + // If this element is present, it replaces any existing Certificate references configured on the Pool. + // If omitted, any existing Certificate references are left unchanged. + // For Windows Nodes, the Batch service installs the Certificates to the specified Certificate store and location. + // For Linux Compute Nodes, the Certificates are stored in a directory inside the Task working directory and an environment + // variable AZ_BATCH_CERTIFICATES_DIR is supplied to the Task to query for this location. + // For Certificates with visibility of 'remoteUser', a 'certs' directory is created in the user's home directory (e.g., /home/{user-name}/certs) + // and Certificates are placed in that directory. + // Warning: This property is deprecated and will be removed after February, 2024. Please use the [Azure KeyVault Extension](https://learn.microsoft.com/azure/batch/batch-certificate-migration-guide) + // instead. + CertificateReferences []CertificateReference + + // The display name for the Pool. The display name need not be unique and can contain any Unicode characters up to a maximum + // length of 1024. This field can be updated only when the pool is empty. + DisplayName *string + + // Whether the Pool permits direct communication between Compute Nodes. Enabling inter-node communication limits the maximum + // size of the Pool due to deployment restrictions on the Compute Nodes of the Pool. This may result in the Pool not reaching + // its desired size. The default value is false.

This field can be updated only when the pool is empty. + EnableInterNodeCommunication *bool + + // A list of name-value pairs associated with the Pool as metadata. If this element is present, it replaces any existing metadata + // configured on the Pool. If you specify an empty collection, any metadata is removed from the Pool. If omitted, any existing + // metadata is left unchanged. + Metadata []MetadataItem + + // Mount storage using specified file system for the entire lifetime of the pool. Mount the storage using Azure fileshare, + // NFS, CIFS or Blobfuse based file system.

This field can be updated only when the pool is empty. + MountConfiguration []MountConfiguration + + // The network configuration for the Pool. This field can be updated only when the pool is empty. + NetworkConfiguration *NetworkConfiguration + + // The user-specified tags associated with the pool. The user-defined tags to be associated with the Azure Batch Pool. When + // specified, these tags are propagated to the backing Azure resources associated with the pool. This property can only be + // specified when the Batch account was created with the poolAllocationMode property set to 'UserSubscription'.

This + // field can be updated only when the pool is empty. + ResourceTags map[string]*string + + // A Task to run on each Compute Node as it joins the Pool. The Task runs when the Compute Node is added to the Pool or when + // the Compute Node is restarted. If this element is present, it overwrites any existing StartTask. If omitted, any existing + // StartTask is left unchanged. + StartTask *StartTask + + // The desired node communication mode for the pool. If this element is present, it replaces the existing targetNodeCommunicationMode + // configured on the Pool. If omitted, any existing metadata is left unchanged. + TargetNodeCommunicationMode *NodeCommunicationMode + + // How Tasks are distributed across Compute Nodes in a Pool. If not specified, the default is spread.

This field + // can be updated only when the pool is empty. + TaskSchedulingPolicy *TaskSchedulingPolicy + + // The number of task slots that can be used to run concurrent tasks on a single compute node in the pool. The default value + // is 1. The maximum value is the smaller of 4 times the number of cores of the vmSize of the pool or 256.

This + // field can be updated only when the pool is empty. + TaskSlotsPerNode *int32 + + // The upgrade policy for the Pool. Describes an upgrade policy - automatic, manual, or rolling.

This field can + // be updated only when the pool is empty. + UpgradePolicy *UpgradePolicy + + // The list of user Accounts to be created on each Compute Node in the Pool. This field can be updated only when the pool + // is empty. + UserAccounts []UserAccount + + // The size of virtual machines in the Pool. For information about available sizes of virtual machines in Pools, see Choose + // a VM size for Compute Nodes in an Azure Batch Pool (https://learn.microsoft.com/azure/batch/batch-pool-vm-sizes).

This field can be updated only when the pool is empty. + VMSize *string + + // The virtual machine configuration for the Pool. This property must be specified.

This field can be updated only + // when the pool is empty. + VirtualMachineConfiguration *VirtualMachineConfiguration +} + +// UpgradePolicy - Describes an upgrade policy - automatic, manual, or rolling. +type UpgradePolicy struct { + // REQUIRED; Specifies the mode of an upgrade to virtual machines in the scale set.

Possible values are:

**Manual** - You control the application of updates to virtual machines in the scale set. You do this by using the manualUpgrade + // action.

**Automatic** - All virtual machines in the scale set are automatically updated at the same time.

**Rolling** - Scale set performs updates in batches with an optional pause time in between. + Mode *UpgradeMode + + // Configuration parameters used for performing automatic OS Upgrade. The configuration parameters used for performing automatic + // OS upgrade. + AutomaticOsUpgradePolicy *AutomaticOSUpgradePolicy + + // The configuration parameters used while performing a rolling upgrade. + RollingUpgradePolicy *RollingUpgradePolicy +} + +// UploadNodeLogsContent - The Azure Batch service log files upload parameters for a Compute Node. +type UploadNodeLogsContent struct { + // REQUIRED; The URL of the container within Azure Blob Storage to which to upload the Batch Service log file(s). If a user + // assigned managed identity is not being used, the URL must include a Shared Access Signature (SAS) granting write permissions + // to the container. The SAS duration must allow enough time for the upload to finish. The start time for SAS is optional + // and recommended to not be specified. + ContainerURL *string + + // REQUIRED; The start of the time range from which to upload Batch Service log file(s). Any log file containing a log message + // in the time range will be uploaded. This means that the operation might retrieve more logs than have been requested since + // the entire log file is always uploaded, but the operation should not retrieve fewer logs than have been requested. + StartTime *time.Time + + // The end of the time range from which to upload Batch Service log file(s). Any log file containing a log message in the + // time range will be uploaded. This means that the operation might retrieve more logs than have been requested since the + // entire log file is always uploaded, but the operation should not retrieve fewer logs than have been requested. If omitted, + // the default is to upload all logs available after the startTime. + EndTime *time.Time + + // The reference to the user assigned identity to use to access Azure Blob Storage specified by containerUrl. The identity + // must have write access to the Azure Blob Storage container. + IdentityReference *NodeIdentityReference +} + +// UploadNodeLogsResult - The result of uploading Batch service log files from a specific Compute Node. +type UploadNodeLogsResult struct { + // REQUIRED; The number of log files which will be uploaded. + NumberOfFilesUploaded *int32 + + // REQUIRED; The virtual directory within Azure Blob Storage container to which the Batch Service log file(s) will be uploaded. + // The virtual directory name is part of the blob name for each log file uploaded, and it is built based poolId, nodeId and + // a unique identifier. + VirtualDirectoryName *string +} + +// UserAccount - Properties used to create a user used to execute Tasks on an Azure Batch +// Compute Node. +type UserAccount struct { + // REQUIRED; The name of the user Account. Names can contain any Unicode characters up to a maximum length of 20. + Name *string + + // REQUIRED; The password for the user Account. + Password *string + + // The elevation level of the user Account. The default value is nonAdmin. + ElevationLevel *ElevationLevel + + // The Linux-specific user configuration for the user Account. This property is ignored if specified on a Windows Pool. If + // not specified, the user is created with the default options. + LinuxUserConfiguration *LinuxUserConfiguration + + // The Windows-specific user configuration for the user Account. This property can only be specified if the user is on a Windows + // Pool. If not specified and on a Windows Pool, the user is created with the default options. + WindowsUserConfiguration *WindowsUserConfiguration +} + +// UserAssignedIdentity - The user assigned Identity +type UserAssignedIdentity struct { + // REQUIRED; The ARM resource id of the user assigned identity. + ResourceID *string + + // READ-ONLY; The client id of the user assigned identity. + ClientID *string + + // READ-ONLY; The principal id of the user assigned identity. + PrincipalID *string +} + +// UserIdentity - The definition of the user identity under which the Task is run. Specify either the userName or autoUser +// property, but not both. +type UserIdentity struct { + // The auto user under which the Task is run. The userName and autoUser properties are mutually exclusive; you must specify + // one but not both. + AutoUser *AutoUserSpecification + + // The name of the user identity under which the Task is run. The userName and autoUser properties are mutually exclusive; + // you must specify one but not both. + Username *string +} + +// VMDiskSecurityProfile - Specifies the security profile settings for the managed disk. **Note**: It can only be set for +// Confidential VMs and required when using Confidential VMs. +type VMDiskSecurityProfile struct { + // Specifies the EncryptionType of the managed disk. It is set to VMGuestStateOnly for encryption of just the VMGuestState + // blob, and NonPersistedTPM for not persisting firmware state in the VMGuestState blob. **Note**: It can be set for only + // Confidential VMs and is required when using Confidential VMs. + SecurityEncryptionType *SecurityEncryptionTypes +} + +// VMExtension - The configuration for virtual machine extensions. +type VMExtension struct { + // REQUIRED; The name of the virtual machine extension. + Name *string + + // REQUIRED; The name of the extension handler publisher. + Publisher *string + + // REQUIRED; The type of the extension. + Type *string + + // Indicates whether the extension should use a newer minor version if one is available at deployment time. Once deployed, + // however, the extension will not upgrade minor versions unless redeployed, even with this property set to true. + AutoUpgradeMinorVersion *bool + + // Indicates whether the extension should be automatically upgraded by the platform if there is a newer version of the extension + // available. + EnableAutomaticUpgrade *bool + + // The extension can contain either protectedSettings or protectedSettingsFromKeyVault or no protected settings at all. + ProtectedSettings map[string]*string + + // The collection of extension names. Collection of extension names after which this extension needs to be provisioned. + ProvisionAfterExtensions []string + + // JSON formatted public settings for the extension. + Settings map[string]*string + + // The version of script handler. + TypeHandlerVersion *string +} + +// VMExtensionInstanceView - The vm extension instance view. +type VMExtensionInstanceView struct { + // The name of the vm extension instance view. + Name *string + + // The resource status information. + Statuses []InstanceViewStatus + + // The resource status information. + SubStatuses []InstanceViewStatus +} + +// VirtualMachineConfiguration - The configuration for Compute Nodes in a Pool based on the Azure Virtual +// Machines infrastructure. +type VirtualMachineConfiguration struct { + // REQUIRED; A reference to the Azure Virtual Machines Marketplace Image or the custom Virtual Machine Image to use. + ImageReference *ImageReference + + // REQUIRED; The SKU of the Batch Compute Node agent to be provisioned on Compute Nodes in the Pool. The Batch Compute Node + // agent is a program that runs on each Compute Node in the Pool, and provides the command-and-control interface between the + // Compute Node and the Batch service. There are different implementations of the Compute Node agent, known as SKUs, for different + // operating systems. You must specify a Compute Node agent SKU which matches the selected Image reference. To get the list + // of supported Compute Node agent SKUs along with their list of verified Image references, see the 'List supported Compute + // Node agent SKUs' operation. + NodeAgentSKUID *string + + // The container configuration for the Pool. If specified, setup is performed on each Compute Node in the Pool to allow Tasks + // to run in containers. All regular Tasks and Job manager Tasks run on this Pool must specify the containerSettings property, + // and all other Tasks may specify it. + ContainerConfiguration *ContainerConfiguration + + // The configuration for data disks attached to the Compute Nodes in the Pool. This property must be specified if the Compute + // Nodes in the Pool need to have empty data disks attached to them. This cannot be updated. Each Compute Node gets its own + // disk (the disk is not a file share). Existing disks cannot be attached, each attached disk is empty. When the Compute Node + // is removed from the Pool, the disk and all data associated with it is also deleted. The disk is not formatted after being + // attached, it must be formatted before use - for more information see https://learn.microsoft.com/azure/virtual-machines/linux/classic/attach-disk#initialize-a-new-data-disk-in-linux + // and https://learn.microsoft.com/azure/virtual-machines/windows/attach-disk-ps#add-an-empty-data-disk-to-a-virtual-machine. + DataDisks []DataDisk + + // The disk encryption configuration for the pool. If specified, encryption is performed on each node in the pool during node + // provisioning. + DiskEncryptionConfiguration *DiskEncryptionConfiguration + + // The virtual machine extension for the pool. If specified, the extensions mentioned in this configuration will be installed + // on each node. + Extensions []VMExtension + + // This only applies to Images that contain the Windows operating system, and + // should only be used when you hold valid on-premises licenses for the Compute + // Nodes which will be deployed. If omitted, no on-premises licensing discount is + // applied. Values are: + // Windows_Server - The on-premises license is for Windows + // Server. + // Windows_Client - The on-premises license is for Windows Client. + LicenseType *string + + // The node placement configuration for the pool. This configuration will specify rules on how nodes in the pool will be physically + // allocated. + NodePlacementConfiguration *NodePlacementConfiguration + + // Settings for the operating system disk of the Virtual Machine. + OSDisk *OSDisk + + // Specifies the security profile settings for the virtual machine or virtual machine scale set. + SecurityProfile *SecurityProfile + + // Specifies the service artifact reference id used to set same image version for all virtual machines in the scale set when + // using 'latest' image version. The service artifact reference id in the form of /subscriptions/{subscriptionId}/resourceGroups/{resourceGroup}/providers/Microsoft.Compute/galleries/{galleryName}/serviceArtifacts/{serviceArtifactName}/vmArtifactsProfiles/{vmArtifactsProfilesName} + ServiceArtifactReference *ServiceArtifactReference + + // Windows operating system settings on the virtual machine. This property must not be specified if the imageReference property + // specifies a Linux OS Image. + WindowsConfiguration *WindowsConfiguration +} + +// VirtualMachineInfo - Info about the current state of the virtual machine. +type VirtualMachineInfo struct { + // The reference to the Azure Virtual Machine's Marketplace Image. + ImageReference *ImageReference + + // The resource ID of the Compute Node's current Virtual Machine Scale Set VM. Only defined if the Batch Account was created + // with its poolAllocationMode property set to 'UserSubscription'. + ScaleSetVMResourceID *string +} + +// WindowsConfiguration - Windows operating system settings to apply to the virtual machine. +type WindowsConfiguration struct { + // Whether automatic updates are enabled on the virtual machine. If omitted, the default value is true. + EnableAutomaticUpdates *bool +} + +// WindowsUserConfiguration - Properties used to create a user Account on a Windows Compute Node. +type WindowsUserConfiguration struct { + // The login mode for the user. The default is 'batch'. + LoginMode *LoginMode +} + +// listPoolUsageMetricsResult - The result of a listing the usage metrics for an Account. +type listPoolUsageMetricsResult struct { + // The URL to get the next set of results. + NextLink *string + + // The Pool usage metrics data. + Value []poolUsageMetrics +} + +// poolUsageMetrics - Usage metrics for a Pool across an aggregation interval. +type poolUsageMetrics struct { + // REQUIRED; The end time of the aggregation interval covered by this entry. + EndTime *time.Time + + // REQUIRED; The ID of the Pool whose metrics are aggregated in this entry. + PoolID *string + + // REQUIRED; The start time of the aggregation interval covered by this entry. + StartTime *time.Time + + // REQUIRED; The total core hours used in the Pool during this aggregation interval. + TotalCoreHours *float32 + + // REQUIRED; The size of virtual machines in the Pool. All VMs in a Pool are the same size. For information about available + // sizes of virtual machines in Pools, see Choose a VM size for Compute Nodes in an Azure Batch Pool (https://learn.microsoft.com/azure/batch/batch-pool-vm-sizes). + VMSize *string +} diff --git a/sdk/batch/azbatch/models_serde.go b/sdk/batch/azbatch/models_serde.go new file mode 100644 index 000000000000..ff1835461e85 --- /dev/null +++ b/sdk/batch/azbatch/models_serde.go @@ -0,0 +1,7243 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package azbatch + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "reflect" + "strconv" +) + +// MarshalJSON implements the json.Marshaller interface for type AccountListSupportedImagesResult. +func (a AccountListSupportedImagesResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "odata.nextLink", a.NextLink) + populate(objectMap, "value", a.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AccountListSupportedImagesResult. +func (a *AccountListSupportedImagesResult) 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 "odata.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 AddTaskCollectionResult. +func (a AddTaskCollectionResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "value", a.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AddTaskCollectionResult. +func (a *AddTaskCollectionResult) 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 "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 AffinityInfo. +func (a AffinityInfo) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "affinityId", a.AffinityID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AffinityInfo. +func (a *AffinityInfo) 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 "affinityId": + err = unpopulate(val, "AffinityID", &a.AffinityID) + 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 Application. +func (a Application) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "displayName", a.DisplayName) + populate(objectMap, "id", a.ID) + populate(objectMap, "versions", a.Versions) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Application. +func (a *Application) 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 "displayName": + err = unpopulate(val, "DisplayName", &a.DisplayName) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &a.ID) + delete(rawMsg, key) + case "versions": + err = unpopulate(val, "Versions", &a.Versions) + 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 ApplicationListResult. +func (a ApplicationListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "odata.nextLink", a.NextLink) + populate(objectMap, "value", a.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ApplicationListResult. +func (a *ApplicationListResult) 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 "odata.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 ApplicationPackageReference. +func (a ApplicationPackageReference) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "applicationId", a.ApplicationID) + populate(objectMap, "version", a.Version) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ApplicationPackageReference. +func (a *ApplicationPackageReference) 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 "applicationId": + err = unpopulate(val, "ApplicationID", &a.ApplicationID) + delete(rawMsg, key) + case "version": + err = unpopulate(val, "Version", &a.Version) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AuthenticationTokenSettings. +func (a AuthenticationTokenSettings) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "access", a.Access) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AuthenticationTokenSettings. +func (a *AuthenticationTokenSettings) 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 "access": + err = unpopulate(val, "Access", &a.Access) + 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 AutoPoolSpecification. +func (a AutoPoolSpecification) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "autoPoolIdPrefix", a.AutoPoolIDPrefix) + populate(objectMap, "keepAlive", a.KeepAlive) + populate(objectMap, "pool", a.Pool) + populate(objectMap, "poolLifetimeOption", a.PoolLifetimeOption) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AutoPoolSpecification. +func (a *AutoPoolSpecification) 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 "autoPoolIdPrefix": + err = unpopulate(val, "AutoPoolIDPrefix", &a.AutoPoolIDPrefix) + delete(rawMsg, key) + case "keepAlive": + err = unpopulate(val, "KeepAlive", &a.KeepAlive) + delete(rawMsg, key) + case "pool": + err = unpopulate(val, "Pool", &a.Pool) + delete(rawMsg, key) + case "poolLifetimeOption": + err = unpopulate(val, "PoolLifetimeOption", &a.PoolLifetimeOption) + 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 AutoScaleRun. +func (a AutoScaleRun) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "error", a.Error) + populate(objectMap, "results", a.Results) + populateDateTimeRFC3339(objectMap, "timestamp", a.Timestamp) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AutoScaleRun. +func (a *AutoScaleRun) 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 "error": + err = unpopulate(val, "Error", &a.Error) + delete(rawMsg, key) + case "results": + err = unpopulate(val, "Results", &a.Results) + delete(rawMsg, key) + case "timestamp": + err = unpopulateDateTimeRFC3339(val, "Timestamp", &a.Timestamp) + 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 AutoScaleRunError. +func (a AutoScaleRunError) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "code", a.Code) + populate(objectMap, "message", a.Message) + populate(objectMap, "values", a.Values) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AutoScaleRunError. +func (a *AutoScaleRunError) 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 "code": + err = unpopulate(val, "Code", &a.Code) + delete(rawMsg, key) + case "message": + err = unpopulate(val, "Message", &a.Message) + delete(rawMsg, key) + case "values": + err = unpopulate(val, "Values", &a.Values) + 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 AutoUserSpecification. +func (a AutoUserSpecification) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "elevationLevel", a.ElevationLevel) + populate(objectMap, "scope", a.Scope) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AutoUserSpecification. +func (a *AutoUserSpecification) 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 "elevationLevel": + err = unpopulate(val, "ElevationLevel", &a.ElevationLevel) + delete(rawMsg, key) + case "scope": + err = unpopulate(val, "Scope", &a.Scope) + 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 AutomaticOSUpgradePolicy. +func (a AutomaticOSUpgradePolicy) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "disableAutomaticRollback", a.DisableAutomaticRollback) + populate(objectMap, "enableAutomaticOSUpgrade", a.EnableAutomaticOsUpgrade) + populate(objectMap, "osRollingUpgradeDeferral", a.OSRollingUpgradeDeferral) + populate(objectMap, "useRollingUpgradePolicy", a.UseRollingUpgradePolicy) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AutomaticOSUpgradePolicy. +func (a *AutomaticOSUpgradePolicy) 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 "disableAutomaticRollback": + err = unpopulate(val, "DisableAutomaticRollback", &a.DisableAutomaticRollback) + delete(rawMsg, key) + case "enableAutomaticOSUpgrade": + err = unpopulate(val, "EnableAutomaticOsUpgrade", &a.EnableAutomaticOsUpgrade) + delete(rawMsg, key) + case "osRollingUpgradeDeferral": + err = unpopulate(val, "OSRollingUpgradeDeferral", &a.OSRollingUpgradeDeferral) + delete(rawMsg, key) + case "useRollingUpgradePolicy": + err = unpopulate(val, "UseRollingUpgradePolicy", &a.UseRollingUpgradePolicy) + 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 AzureBlobFileSystemConfiguration. +func (a AzureBlobFileSystemConfiguration) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "accountKey", a.AccountKey) + populate(objectMap, "accountName", a.AccountName) + populate(objectMap, "blobfuseOptions", a.BlobfuseOptions) + populate(objectMap, "containerName", a.ContainerName) + populate(objectMap, "identityReference", a.IdentityReference) + populate(objectMap, "relativeMountPath", a.RelativeMountPath) + populate(objectMap, "sasKey", a.SASKey) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AzureBlobFileSystemConfiguration. +func (a *AzureBlobFileSystemConfiguration) 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 "accountKey": + err = unpopulate(val, "AccountKey", &a.AccountKey) + delete(rawMsg, key) + case "accountName": + err = unpopulate(val, "AccountName", &a.AccountName) + delete(rawMsg, key) + case "blobfuseOptions": + err = unpopulate(val, "BlobfuseOptions", &a.BlobfuseOptions) + delete(rawMsg, key) + case "containerName": + err = unpopulate(val, "ContainerName", &a.ContainerName) + delete(rawMsg, key) + case "identityReference": + err = unpopulate(val, "IdentityReference", &a.IdentityReference) + delete(rawMsg, key) + case "relativeMountPath": + err = unpopulate(val, "RelativeMountPath", &a.RelativeMountPath) + delete(rawMsg, key) + case "sasKey": + err = unpopulate(val, "SASKey", &a.SASKey) + 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 AzureFileShareConfiguration. +func (a AzureFileShareConfiguration) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "accountKey", a.AccountKey) + populate(objectMap, "accountName", a.AccountName) + populate(objectMap, "azureFileUrl", a.AzureFileURL) + populate(objectMap, "mountOptions", a.MountOptions) + populate(objectMap, "relativeMountPath", a.RelativeMountPath) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AzureFileShareConfiguration. +func (a *AzureFileShareConfiguration) 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 "accountKey": + err = unpopulate(val, "AccountKey", &a.AccountKey) + delete(rawMsg, key) + case "accountName": + err = unpopulate(val, "AccountName", &a.AccountName) + delete(rawMsg, key) + case "azureFileUrl": + err = unpopulate(val, "AzureFileURL", &a.AzureFileURL) + delete(rawMsg, key) + case "mountOptions": + err = unpopulate(val, "MountOptions", &a.MountOptions) + delete(rawMsg, key) + case "relativeMountPath": + err = unpopulate(val, "RelativeMountPath", &a.RelativeMountPath) + 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 CIFSMountConfiguration. +func (c CIFSMountConfiguration) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "mountOptions", c.MountOptions) + populate(objectMap, "password", c.Password) + populate(objectMap, "relativeMountPath", c.RelativeMountPath) + populate(objectMap, "source", c.Source) + populate(objectMap, "username", c.Username) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CIFSMountConfiguration. +func (c *CIFSMountConfiguration) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "mountOptions": + err = unpopulate(val, "MountOptions", &c.MountOptions) + delete(rawMsg, key) + case "password": + err = unpopulate(val, "Password", &c.Password) + delete(rawMsg, key) + case "relativeMountPath": + err = unpopulate(val, "RelativeMountPath", &c.RelativeMountPath) + delete(rawMsg, key) + case "source": + err = unpopulate(val, "Source", &c.Source) + delete(rawMsg, key) + case "username": + err = unpopulate(val, "Username", &c.Username) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Certificate. +func (c Certificate) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "data", c.Data) + populate(objectMap, "deleteCertificateError", c.DeleteCertificateError) + populate(objectMap, "certificateFormat", c.Format) + populate(objectMap, "password", c.Password) + populate(objectMap, "previousState", c.PreviousState) + populateDateTimeRFC3339(objectMap, "previousStateTransitionTime", c.PreviousStateTransitionTime) + populate(objectMap, "publicData", c.PublicData) + populate(objectMap, "state", c.State) + populateDateTimeRFC3339(objectMap, "stateTransitionTime", c.StateTransitionTime) + populate(objectMap, "thumbprint", c.Thumbprint) + populate(objectMap, "thumbprintAlgorithm", c.ThumbprintAlgorithm) + populate(objectMap, "url", c.URL) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Certificate. +func (c *Certificate) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "data": + err = unpopulate(val, "Data", &c.Data) + delete(rawMsg, key) + case "deleteCertificateError": + err = unpopulate(val, "DeleteCertificateError", &c.DeleteCertificateError) + delete(rawMsg, key) + case "certificateFormat": + err = unpopulate(val, "Format", &c.Format) + delete(rawMsg, key) + case "password": + err = unpopulate(val, "Password", &c.Password) + delete(rawMsg, key) + case "previousState": + err = unpopulate(val, "PreviousState", &c.PreviousState) + delete(rawMsg, key) + case "previousStateTransitionTime": + err = unpopulateDateTimeRFC3339(val, "PreviousStateTransitionTime", &c.PreviousStateTransitionTime) + delete(rawMsg, key) + case "publicData": + err = unpopulate(val, "PublicData", &c.PublicData) + delete(rawMsg, key) + case "state": + err = unpopulate(val, "State", &c.State) + delete(rawMsg, key) + case "stateTransitionTime": + err = unpopulateDateTimeRFC3339(val, "StateTransitionTime", &c.StateTransitionTime) + delete(rawMsg, key) + case "thumbprint": + err = unpopulate(val, "Thumbprint", &c.Thumbprint) + delete(rawMsg, key) + case "thumbprintAlgorithm": + err = unpopulate(val, "ThumbprintAlgorithm", &c.ThumbprintAlgorithm) + delete(rawMsg, key) + case "url": + err = unpopulate(val, "URL", &c.URL) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CertificateListResult. +func (c CertificateListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "odata.nextLink", c.NextLink) + populate(objectMap, "value", c.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CertificateListResult. +func (c *CertificateListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "odata.nextLink": + err = unpopulate(val, "NextLink", &c.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &c.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CertificateReference. +func (c CertificateReference) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "storeLocation", c.StoreLocation) + populate(objectMap, "storeName", c.StoreName) + populate(objectMap, "thumbprint", c.Thumbprint) + populate(objectMap, "thumbprintAlgorithm", c.ThumbprintAlgorithm) + populate(objectMap, "visibility", c.Visibility) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CertificateReference. +func (c *CertificateReference) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "storeLocation": + err = unpopulate(val, "StoreLocation", &c.StoreLocation) + delete(rawMsg, key) + case "storeName": + err = unpopulate(val, "StoreName", &c.StoreName) + delete(rawMsg, key) + case "thumbprint": + err = unpopulate(val, "Thumbprint", &c.Thumbprint) + delete(rawMsg, key) + case "thumbprintAlgorithm": + err = unpopulate(val, "ThumbprintAlgorithm", &c.ThumbprintAlgorithm) + delete(rawMsg, key) + case "visibility": + err = unpopulate(val, "Visibility", &c.Visibility) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ContainerConfiguration. +func (c ContainerConfiguration) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "containerImageNames", c.ContainerImageNames) + populate(objectMap, "containerRegistries", c.ContainerRegistries) + populate(objectMap, "type", c.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ContainerConfiguration. +func (c *ContainerConfiguration) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "containerImageNames": + err = unpopulate(val, "ContainerImageNames", &c.ContainerImageNames) + delete(rawMsg, key) + case "containerRegistries": + err = unpopulate(val, "ContainerRegistries", &c.ContainerRegistries) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &c.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ContainerHostBindMountEntry. +func (c ContainerHostBindMountEntry) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "isReadOnly", c.IsReadOnly) + populate(objectMap, "source", c.Source) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ContainerHostBindMountEntry. +func (c *ContainerHostBindMountEntry) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "isReadOnly": + err = unpopulate(val, "IsReadOnly", &c.IsReadOnly) + delete(rawMsg, key) + case "source": + err = unpopulate(val, "Source", &c.Source) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ContainerRegistryReference. +func (c ContainerRegistryReference) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "identityReference", c.IdentityReference) + populate(objectMap, "password", c.Password) + populate(objectMap, "registryServer", c.RegistryServer) + populate(objectMap, "username", c.Username) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ContainerRegistryReference. +func (c *ContainerRegistryReference) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "identityReference": + err = unpopulate(val, "IdentityReference", &c.IdentityReference) + delete(rawMsg, key) + case "password": + err = unpopulate(val, "Password", &c.Password) + delete(rawMsg, key) + case "registryServer": + err = unpopulate(val, "RegistryServer", &c.RegistryServer) + delete(rawMsg, key) + case "username": + err = unpopulate(val, "Username", &c.Username) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CreateJobContent. +func (c CreateJobContent) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "allowTaskPreemption", c.AllowTaskPreemption) + populate(objectMap, "commonEnvironmentSettings", c.CommonEnvironmentSettings) + populate(objectMap, "constraints", c.Constraints) + populate(objectMap, "displayName", c.DisplayName) + populate(objectMap, "id", c.ID) + populate(objectMap, "jobManagerTask", c.JobManagerTask) + populate(objectMap, "jobPreparationTask", c.JobPreparationTask) + populate(objectMap, "jobReleaseTask", c.JobReleaseTask) + populate(objectMap, "maxParallelTasks", c.MaxParallelTasks) + populate(objectMap, "metadata", c.Metadata) + populate(objectMap, "networkConfiguration", c.NetworkConfiguration) + populate(objectMap, "onAllTasksComplete", c.OnAllTasksComplete) + populate(objectMap, "onTaskFailure", c.OnTaskFailure) + populate(objectMap, "poolInfo", c.PoolInfo) + populate(objectMap, "priority", c.Priority) + populate(objectMap, "usesTaskDependencies", c.UsesTaskDependencies) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CreateJobContent. +func (c *CreateJobContent) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "allowTaskPreemption": + err = unpopulate(val, "AllowTaskPreemption", &c.AllowTaskPreemption) + delete(rawMsg, key) + case "commonEnvironmentSettings": + err = unpopulate(val, "CommonEnvironmentSettings", &c.CommonEnvironmentSettings) + delete(rawMsg, key) + case "constraints": + err = unpopulate(val, "Constraints", &c.Constraints) + delete(rawMsg, key) + case "displayName": + err = unpopulate(val, "DisplayName", &c.DisplayName) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &c.ID) + delete(rawMsg, key) + case "jobManagerTask": + err = unpopulate(val, "JobManagerTask", &c.JobManagerTask) + delete(rawMsg, key) + case "jobPreparationTask": + err = unpopulate(val, "JobPreparationTask", &c.JobPreparationTask) + delete(rawMsg, key) + case "jobReleaseTask": + err = unpopulate(val, "JobReleaseTask", &c.JobReleaseTask) + delete(rawMsg, key) + case "maxParallelTasks": + err = unpopulate(val, "MaxParallelTasks", &c.MaxParallelTasks) + delete(rawMsg, key) + case "metadata": + err = unpopulate(val, "Metadata", &c.Metadata) + delete(rawMsg, key) + case "networkConfiguration": + err = unpopulate(val, "NetworkConfiguration", &c.NetworkConfiguration) + delete(rawMsg, key) + case "onAllTasksComplete": + err = unpopulate(val, "OnAllTasksComplete", &c.OnAllTasksComplete) + delete(rawMsg, key) + case "onTaskFailure": + err = unpopulate(val, "OnTaskFailure", &c.OnTaskFailure) + delete(rawMsg, key) + case "poolInfo": + err = unpopulate(val, "PoolInfo", &c.PoolInfo) + delete(rawMsg, key) + case "priority": + err = unpopulate(val, "Priority", &c.Priority) + delete(rawMsg, key) + case "usesTaskDependencies": + err = unpopulate(val, "UsesTaskDependencies", &c.UsesTaskDependencies) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CreateJobScheduleContent. +func (c CreateJobScheduleContent) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "displayName", c.DisplayName) + populate(objectMap, "id", c.ID) + populate(objectMap, "jobSpecification", c.JobSpecification) + populate(objectMap, "metadata", c.Metadata) + populate(objectMap, "schedule", c.Schedule) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CreateJobScheduleContent. +func (c *CreateJobScheduleContent) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "displayName": + err = unpopulate(val, "DisplayName", &c.DisplayName) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &c.ID) + delete(rawMsg, key) + case "jobSpecification": + err = unpopulate(val, "JobSpecification", &c.JobSpecification) + delete(rawMsg, key) + case "metadata": + err = unpopulate(val, "Metadata", &c.Metadata) + delete(rawMsg, key) + case "schedule": + err = unpopulate(val, "Schedule", &c.Schedule) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CreateNodeUserContent. +func (c CreateNodeUserContent) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateDateTimeRFC3339(objectMap, "expiryTime", c.ExpiryTime) + populate(objectMap, "isAdmin", c.IsAdmin) + populate(objectMap, "name", c.Name) + populate(objectMap, "password", c.Password) + populate(objectMap, "sshPublicKey", c.SSHPublicKey) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CreateNodeUserContent. +func (c *CreateNodeUserContent) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "expiryTime": + err = unpopulateDateTimeRFC3339(val, "ExpiryTime", &c.ExpiryTime) + delete(rawMsg, key) + case "isAdmin": + err = unpopulate(val, "IsAdmin", &c.IsAdmin) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &c.Name) + delete(rawMsg, key) + case "password": + err = unpopulate(val, "Password", &c.Password) + delete(rawMsg, key) + case "sshPublicKey": + err = unpopulate(val, "SSHPublicKey", &c.SSHPublicKey) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CreatePoolContent. +func (c CreatePoolContent) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "applicationPackageReferences", c.ApplicationPackageReferences) + populate(objectMap, "autoScaleEvaluationInterval", c.AutoScaleEvaluationInterval) + populate(objectMap, "autoScaleFormula", c.AutoScaleFormula) + populate(objectMap, "certificateReferences", c.CertificateReferences) + populate(objectMap, "displayName", c.DisplayName) + populate(objectMap, "enableAutoScale", c.EnableAutoScale) + populate(objectMap, "enableInterNodeCommunication", c.EnableInterNodeCommunication) + populate(objectMap, "id", c.ID) + populate(objectMap, "metadata", c.Metadata) + populate(objectMap, "mountConfiguration", c.MountConfiguration) + populate(objectMap, "networkConfiguration", c.NetworkConfiguration) + populate(objectMap, "resizeTimeout", c.ResizeTimeout) + populate(objectMap, "resourceTags", c.ResourceTags) + populate(objectMap, "startTask", c.StartTask) + populate(objectMap, "targetDedicatedNodes", c.TargetDedicatedNodes) + populate(objectMap, "targetLowPriorityNodes", c.TargetLowPriorityNodes) + populate(objectMap, "targetNodeCommunicationMode", c.TargetNodeCommunicationMode) + populate(objectMap, "taskSchedulingPolicy", c.TaskSchedulingPolicy) + populate(objectMap, "taskSlotsPerNode", c.TaskSlotsPerNode) + populate(objectMap, "upgradePolicy", c.UpgradePolicy) + populate(objectMap, "userAccounts", c.UserAccounts) + populate(objectMap, "vmSize", c.VMSize) + populate(objectMap, "virtualMachineConfiguration", c.VirtualMachineConfiguration) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CreatePoolContent. +func (c *CreatePoolContent) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "applicationPackageReferences": + err = unpopulate(val, "ApplicationPackageReferences", &c.ApplicationPackageReferences) + delete(rawMsg, key) + case "autoScaleEvaluationInterval": + err = unpopulate(val, "AutoScaleEvaluationInterval", &c.AutoScaleEvaluationInterval) + delete(rawMsg, key) + case "autoScaleFormula": + err = unpopulate(val, "AutoScaleFormula", &c.AutoScaleFormula) + delete(rawMsg, key) + case "certificateReferences": + err = unpopulate(val, "CertificateReferences", &c.CertificateReferences) + delete(rawMsg, key) + case "displayName": + err = unpopulate(val, "DisplayName", &c.DisplayName) + delete(rawMsg, key) + case "enableAutoScale": + err = unpopulate(val, "EnableAutoScale", &c.EnableAutoScale) + delete(rawMsg, key) + case "enableInterNodeCommunication": + err = unpopulate(val, "EnableInterNodeCommunication", &c.EnableInterNodeCommunication) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &c.ID) + delete(rawMsg, key) + case "metadata": + err = unpopulate(val, "Metadata", &c.Metadata) + delete(rawMsg, key) + case "mountConfiguration": + err = unpopulate(val, "MountConfiguration", &c.MountConfiguration) + delete(rawMsg, key) + case "networkConfiguration": + err = unpopulate(val, "NetworkConfiguration", &c.NetworkConfiguration) + delete(rawMsg, key) + case "resizeTimeout": + err = unpopulate(val, "ResizeTimeout", &c.ResizeTimeout) + delete(rawMsg, key) + case "resourceTags": + err = unpopulate(val, "ResourceTags", &c.ResourceTags) + delete(rawMsg, key) + case "startTask": + err = unpopulate(val, "StartTask", &c.StartTask) + delete(rawMsg, key) + case "targetDedicatedNodes": + err = unpopulate(val, "TargetDedicatedNodes", &c.TargetDedicatedNodes) + delete(rawMsg, key) + case "targetLowPriorityNodes": + err = unpopulate(val, "TargetLowPriorityNodes", &c.TargetLowPriorityNodes) + delete(rawMsg, key) + case "targetNodeCommunicationMode": + err = unpopulate(val, "TargetNodeCommunicationMode", &c.TargetNodeCommunicationMode) + delete(rawMsg, key) + case "taskSchedulingPolicy": + err = unpopulate(val, "TaskSchedulingPolicy", &c.TaskSchedulingPolicy) + delete(rawMsg, key) + case "taskSlotsPerNode": + err = unpopulate(val, "TaskSlotsPerNode", &c.TaskSlotsPerNode) + delete(rawMsg, key) + case "upgradePolicy": + err = unpopulate(val, "UpgradePolicy", &c.UpgradePolicy) + delete(rawMsg, key) + case "userAccounts": + err = unpopulate(val, "UserAccounts", &c.UserAccounts) + delete(rawMsg, key) + case "vmSize": + err = unpopulate(val, "VMSize", &c.VMSize) + delete(rawMsg, key) + case "virtualMachineConfiguration": + err = unpopulate(val, "VirtualMachineConfiguration", &c.VirtualMachineConfiguration) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CreateTaskContent. +func (c CreateTaskContent) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "affinityInfo", c.AffinityInfo) + populate(objectMap, "applicationPackageReferences", c.ApplicationPackageReferences) + populate(objectMap, "authenticationTokenSettings", c.AuthenticationTokenSettings) + populate(objectMap, "commandLine", c.CommandLine) + populate(objectMap, "constraints", c.Constraints) + populate(objectMap, "containerSettings", c.ContainerSettings) + populate(objectMap, "dependsOn", c.DependsOn) + populate(objectMap, "displayName", c.DisplayName) + populate(objectMap, "environmentSettings", c.EnvironmentSettings) + populate(objectMap, "exitConditions", c.ExitConditions) + populate(objectMap, "id", c.ID) + populate(objectMap, "multiInstanceSettings", c.MultiInstanceSettings) + populate(objectMap, "outputFiles", c.OutputFiles) + populate(objectMap, "requiredSlots", c.RequiredSlots) + populate(objectMap, "resourceFiles", c.ResourceFiles) + populate(objectMap, "userIdentity", c.UserIdentity) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CreateTaskContent. +func (c *CreateTaskContent) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "affinityInfo": + err = unpopulate(val, "AffinityInfo", &c.AffinityInfo) + delete(rawMsg, key) + case "applicationPackageReferences": + err = unpopulate(val, "ApplicationPackageReferences", &c.ApplicationPackageReferences) + delete(rawMsg, key) + case "authenticationTokenSettings": + err = unpopulate(val, "AuthenticationTokenSettings", &c.AuthenticationTokenSettings) + delete(rawMsg, key) + case "commandLine": + err = unpopulate(val, "CommandLine", &c.CommandLine) + delete(rawMsg, key) + case "constraints": + err = unpopulate(val, "Constraints", &c.Constraints) + delete(rawMsg, key) + case "containerSettings": + err = unpopulate(val, "ContainerSettings", &c.ContainerSettings) + delete(rawMsg, key) + case "dependsOn": + err = unpopulate(val, "DependsOn", &c.DependsOn) + delete(rawMsg, key) + case "displayName": + err = unpopulate(val, "DisplayName", &c.DisplayName) + delete(rawMsg, key) + case "environmentSettings": + err = unpopulate(val, "EnvironmentSettings", &c.EnvironmentSettings) + delete(rawMsg, key) + case "exitConditions": + err = unpopulate(val, "ExitConditions", &c.ExitConditions) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &c.ID) + delete(rawMsg, key) + case "multiInstanceSettings": + err = unpopulate(val, "MultiInstanceSettings", &c.MultiInstanceSettings) + delete(rawMsg, key) + case "outputFiles": + err = unpopulate(val, "OutputFiles", &c.OutputFiles) + delete(rawMsg, key) + case "requiredSlots": + err = unpopulate(val, "RequiredSlots", &c.RequiredSlots) + delete(rawMsg, key) + case "resourceFiles": + err = unpopulate(val, "ResourceFiles", &c.ResourceFiles) + delete(rawMsg, key) + case "userIdentity": + err = unpopulate(val, "UserIdentity", &c.UserIdentity) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DataDisk. +func (d DataDisk) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "caching", d.Caching) + populate(objectMap, "diskSizeGB", d.DiskSizeGB) + populate(objectMap, "lun", d.LogicalUnitNumber) + populate(objectMap, "storageAccountType", d.StorageAccountType) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DataDisk. +func (d *DataDisk) 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 "caching": + err = unpopulate(val, "Caching", &d.Caching) + delete(rawMsg, key) + case "diskSizeGB": + err = unpopulate(val, "DiskSizeGB", &d.DiskSizeGB) + delete(rawMsg, key) + case "lun": + err = unpopulate(val, "LogicalUnitNumber", &d.LogicalUnitNumber) + delete(rawMsg, key) + case "storageAccountType": + err = unpopulate(val, "StorageAccountType", &d.StorageAccountType) + 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 DeallocateNodeContent. +func (d DeallocateNodeContent) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nodeDeallocateOption", d.NodeDeallocateOption) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DeallocateNodeContent. +func (d *DeallocateNodeContent) 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 "nodeDeallocateOption": + err = unpopulate(val, "NodeDeallocateOption", &d.NodeDeallocateOption) + 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 DeleteCertificateError. +func (d DeleteCertificateError) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "code", d.Code) + populate(objectMap, "message", d.Message) + populate(objectMap, "values", d.Values) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DeleteCertificateError. +func (d *DeleteCertificateError) 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 "code": + err = unpopulate(val, "Code", &d.Code) + delete(rawMsg, key) + case "message": + err = unpopulate(val, "Message", &d.Message) + delete(rawMsg, key) + case "values": + err = unpopulate(val, "Values", &d.Values) + 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 DiffDiskSettings. +func (d DiffDiskSettings) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "placement", d.Placement) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DiffDiskSettings. +func (d *DiffDiskSettings) 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 "placement": + err = unpopulate(val, "Placement", &d.Placement) + 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 DisableJobContent. +func (d DisableJobContent) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "disableTasks", d.DisableTasks) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DisableJobContent. +func (d *DisableJobContent) 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 "disableTasks": + err = unpopulate(val, "DisableTasks", &d.DisableTasks) + 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 DisableNodeSchedulingContent. +func (d DisableNodeSchedulingContent) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nodeDisableSchedulingOption", d.NodeDisableSchedulingOption) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DisableNodeSchedulingContent. +func (d *DisableNodeSchedulingContent) 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 "nodeDisableSchedulingOption": + err = unpopulate(val, "NodeDisableSchedulingOption", &d.NodeDisableSchedulingOption) + 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 DiskEncryptionConfiguration. +func (d DiskEncryptionConfiguration) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "targets", d.Targets) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DiskEncryptionConfiguration. +func (d *DiskEncryptionConfiguration) 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 "targets": + err = unpopulate(val, "Targets", &d.Targets) + 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 EnablePoolAutoScaleContent. +func (e EnablePoolAutoScaleContent) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "autoScaleEvaluationInterval", e.AutoScaleEvaluationInterval) + populate(objectMap, "autoScaleFormula", e.AutoScaleFormula) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type EnablePoolAutoScaleContent. +func (e *EnablePoolAutoScaleContent) 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 "autoScaleEvaluationInterval": + err = unpopulate(val, "AutoScaleEvaluationInterval", &e.AutoScaleEvaluationInterval) + delete(rawMsg, key) + case "autoScaleFormula": + err = unpopulate(val, "AutoScaleFormula", &e.AutoScaleFormula) + 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 EnvironmentSetting. +func (e EnvironmentSetting) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", e.Name) + populate(objectMap, "value", e.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type EnvironmentSetting. +func (e *EnvironmentSetting) 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 "name": + err = unpopulate(val, "Name", &e.Name) + 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 Error. +func (e Error) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "code", e.Code) + populate(objectMap, "message", e.Message) + populate(objectMap, "values", e.Values) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Error. +func (e *Error) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "code": + err = unpopulate(val, "Code", &e.Code) + delete(rawMsg, key) + case "message": + err = unpopulate(val, "Message", &e.Message) + delete(rawMsg, key) + case "values": + err = unpopulate(val, "Values", &e.Values) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ErrorDetail. +func (e ErrorDetail) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "key", e.Key) + populate(objectMap, "value", e.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ErrorDetail. +func (e *ErrorDetail) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "key": + err = unpopulate(val, "Key", &e.Key) + 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 ErrorMessage. +func (e ErrorMessage) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "lang", e.Lang) + populate(objectMap, "value", e.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ErrorMessage. +func (e *ErrorMessage) 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 "lang": + err = unpopulate(val, "Lang", &e.Lang) + 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 EvaluatePoolAutoScaleContent. +func (e EvaluatePoolAutoScaleContent) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "autoScaleFormula", e.AutoScaleFormula) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type EvaluatePoolAutoScaleContent. +func (e *EvaluatePoolAutoScaleContent) 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 "autoScaleFormula": + err = unpopulate(val, "AutoScaleFormula", &e.AutoScaleFormula) + 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 ExitCodeMapping. +func (e ExitCodeMapping) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "code", e.Code) + populate(objectMap, "exitOptions", e.ExitOptions) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ExitCodeMapping. +func (e *ExitCodeMapping) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "code": + err = unpopulate(val, "Code", &e.Code) + delete(rawMsg, key) + case "exitOptions": + err = unpopulate(val, "ExitOptions", &e.ExitOptions) + 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 ExitCodeRangeMapping. +func (e ExitCodeRangeMapping) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "end", e.End) + populate(objectMap, "exitOptions", e.ExitOptions) + populate(objectMap, "start", e.Start) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ExitCodeRangeMapping. +func (e *ExitCodeRangeMapping) 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 "end": + err = unpopulate(val, "End", &e.End) + delete(rawMsg, key) + case "exitOptions": + err = unpopulate(val, "ExitOptions", &e.ExitOptions) + delete(rawMsg, key) + case "start": + err = unpopulate(val, "Start", &e.Start) + 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 ExitConditions. +func (e ExitConditions) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "default", e.Default) + populate(objectMap, "exitCodeRanges", e.ExitCodeRanges) + populate(objectMap, "exitCodes", e.ExitCodes) + populate(objectMap, "fileUploadError", e.FileUploadError) + populate(objectMap, "preProcessingError", e.PreProcessingError) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ExitConditions. +func (e *ExitConditions) 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 "default": + err = unpopulate(val, "Default", &e.Default) + delete(rawMsg, key) + case "exitCodeRanges": + err = unpopulate(val, "ExitCodeRanges", &e.ExitCodeRanges) + delete(rawMsg, key) + case "exitCodes": + err = unpopulate(val, "ExitCodes", &e.ExitCodes) + delete(rawMsg, key) + case "fileUploadError": + err = unpopulate(val, "FileUploadError", &e.FileUploadError) + delete(rawMsg, key) + case "preProcessingError": + err = unpopulate(val, "PreProcessingError", &e.PreProcessingError) + 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 ExitOptions. +func (e ExitOptions) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "dependencyAction", e.DependencyAction) + populate(objectMap, "jobAction", e.JobAction) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ExitOptions. +func (e *ExitOptions) 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 "dependencyAction": + err = unpopulate(val, "DependencyAction", &e.DependencyAction) + delete(rawMsg, key) + case "jobAction": + err = unpopulate(val, "JobAction", &e.JobAction) + 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 FileProperties. +func (f FileProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "contentLength", to.Ptr(strconv.FormatInt(*f.ContentLength, 10))) + populate(objectMap, "contentType", f.ContentType) + populateDateTimeRFC3339(objectMap, "creationTime", f.CreationTime) + populate(objectMap, "fileMode", f.FileMode) + populateDateTimeRFC3339(objectMap, "lastModified", f.LastModified) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type FileProperties. +func (f *FileProperties) 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", f, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "contentLength": + var aux string + err = unpopulate(val, "ContentLength", &aux) + if err == nil { + var v int64 + v, err = strconv.ParseInt(aux, 10, 0) + if err == nil { + f.ContentLength = to.Ptr(v) + } + } + delete(rawMsg, key) + case "contentType": + err = unpopulate(val, "ContentType", &f.ContentType) + delete(rawMsg, key) + case "creationTime": + err = unpopulateDateTimeRFC3339(val, "CreationTime", &f.CreationTime) + delete(rawMsg, key) + case "fileMode": + err = unpopulate(val, "FileMode", &f.FileMode) + delete(rawMsg, key) + case "lastModified": + err = unpopulateDateTimeRFC3339(val, "LastModified", &f.LastModified) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type HTTPHeader. +func (h HTTPHeader) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", h.Name) + populate(objectMap, "value", h.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type HTTPHeader. +func (h *HTTPHeader) 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 "name": + err = unpopulate(val, "Name", &h.Name) + 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 ImageReference. +func (i ImageReference) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "communityGalleryImageId", i.CommunityGalleryImageID) + populate(objectMap, "exactVersion", i.ExactVersion) + populate(objectMap, "offer", i.Offer) + populate(objectMap, "publisher", i.Publisher) + populate(objectMap, "sku", i.SKU) + populate(objectMap, "sharedGalleryImageId", i.SharedGalleryImageID) + populate(objectMap, "version", i.Version) + populate(objectMap, "virtualMachineImageId", i.VirtualMachineImageID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ImageReference. +func (i *ImageReference) 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 "communityGalleryImageId": + err = unpopulate(val, "CommunityGalleryImageID", &i.CommunityGalleryImageID) + delete(rawMsg, key) + case "exactVersion": + err = unpopulate(val, "ExactVersion", &i.ExactVersion) + delete(rawMsg, key) + case "offer": + err = unpopulate(val, "Offer", &i.Offer) + delete(rawMsg, key) + case "publisher": + err = unpopulate(val, "Publisher", &i.Publisher) + delete(rawMsg, key) + case "sku": + err = unpopulate(val, "SKU", &i.SKU) + delete(rawMsg, key) + case "sharedGalleryImageId": + err = unpopulate(val, "SharedGalleryImageID", &i.SharedGalleryImageID) + delete(rawMsg, key) + case "version": + err = unpopulate(val, "Version", &i.Version) + delete(rawMsg, key) + case "virtualMachineImageId": + err = unpopulate(val, "VirtualMachineImageID", &i.VirtualMachineImageID) + 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 InboundEndpoint. +func (i InboundEndpoint) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "backendPort", i.BackendPort) + populate(objectMap, "frontendPort", i.FrontendPort) + populate(objectMap, "name", i.Name) + populate(objectMap, "protocol", i.Protocol) + populate(objectMap, "publicFQDN", i.PublicFQDN) + populate(objectMap, "publicIPAddress", i.PublicIPAddress) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type InboundEndpoint. +func (i *InboundEndpoint) 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 "backendPort": + err = unpopulate(val, "BackendPort", &i.BackendPort) + delete(rawMsg, key) + case "frontendPort": + err = unpopulate(val, "FrontendPort", &i.FrontendPort) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &i.Name) + delete(rawMsg, key) + case "protocol": + err = unpopulate(val, "Protocol", &i.Protocol) + delete(rawMsg, key) + case "publicFQDN": + err = unpopulate(val, "PublicFQDN", &i.PublicFQDN) + delete(rawMsg, key) + case "publicIPAddress": + err = unpopulate(val, "PublicIPAddress", &i.PublicIPAddress) + 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 InboundNATPool. +func (i InboundNATPool) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "backendPort", i.BackendPort) + populate(objectMap, "frontendPortRangeEnd", i.FrontendPortRangeEnd) + populate(objectMap, "frontendPortRangeStart", i.FrontendPortRangeStart) + populate(objectMap, "name", i.Name) + populate(objectMap, "networkSecurityGroupRules", i.NetworkSecurityGroupRules) + populate(objectMap, "protocol", i.Protocol) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type InboundNATPool. +func (i *InboundNATPool) 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 "backendPort": + err = unpopulate(val, "BackendPort", &i.BackendPort) + delete(rawMsg, key) + case "frontendPortRangeEnd": + err = unpopulate(val, "FrontendPortRangeEnd", &i.FrontendPortRangeEnd) + delete(rawMsg, key) + case "frontendPortRangeStart": + err = unpopulate(val, "FrontendPortRangeStart", &i.FrontendPortRangeStart) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &i.Name) + delete(rawMsg, key) + case "networkSecurityGroupRules": + err = unpopulate(val, "NetworkSecurityGroupRules", &i.NetworkSecurityGroupRules) + delete(rawMsg, key) + case "protocol": + err = unpopulate(val, "Protocol", &i.Protocol) + 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 InstanceViewStatus. +func (i InstanceViewStatus) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "code", i.Code) + populate(objectMap, "displayStatus", i.DisplayStatus) + populate(objectMap, "level", i.Level) + populate(objectMap, "message", i.Message) + populateDateTimeRFC3339(objectMap, "time", i.Time) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type InstanceViewStatus. +func (i *InstanceViewStatus) 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 "code": + err = unpopulate(val, "Code", &i.Code) + delete(rawMsg, key) + case "displayStatus": + err = unpopulate(val, "DisplayStatus", &i.DisplayStatus) + delete(rawMsg, key) + case "level": + err = unpopulate(val, "Level", &i.Level) + delete(rawMsg, key) + case "message": + err = unpopulate(val, "Message", &i.Message) + delete(rawMsg, key) + case "time": + err = unpopulateDateTimeRFC3339(val, "Time", &i.Time) + 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 Job. +func (j Job) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "allowTaskPreemption", j.AllowTaskPreemption) + populate(objectMap, "commonEnvironmentSettings", j.CommonEnvironmentSettings) + populate(objectMap, "constraints", j.Constraints) + populateDateTimeRFC3339(objectMap, "creationTime", j.CreationTime) + populate(objectMap, "displayName", j.DisplayName) + populate(objectMap, "eTag", j.ETag) + populate(objectMap, "executionInfo", j.ExecutionInfo) + populate(objectMap, "id", j.ID) + populate(objectMap, "jobManagerTask", j.JobManagerTask) + populate(objectMap, "jobPreparationTask", j.JobPreparationTask) + populate(objectMap, "jobReleaseTask", j.JobReleaseTask) + populateDateTimeRFC3339(objectMap, "lastModified", j.LastModified) + populate(objectMap, "maxParallelTasks", j.MaxParallelTasks) + populate(objectMap, "metadata", j.Metadata) + populate(objectMap, "networkConfiguration", j.NetworkConfiguration) + populate(objectMap, "onAllTasksComplete", j.OnAllTasksComplete) + populate(objectMap, "onTaskFailure", j.OnTaskFailure) + populate(objectMap, "poolInfo", j.PoolInfo) + populate(objectMap, "previousState", j.PreviousState) + populateDateTimeRFC3339(objectMap, "previousStateTransitionTime", j.PreviousStateTransitionTime) + populate(objectMap, "priority", j.Priority) + populate(objectMap, "state", j.State) + populateDateTimeRFC3339(objectMap, "stateTransitionTime", j.StateTransitionTime) + populate(objectMap, "stats", j.Stats) + populate(objectMap, "url", j.URL) + populate(objectMap, "usesTaskDependencies", j.UsesTaskDependencies) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Job. +func (j *Job) 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", j, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "allowTaskPreemption": + err = unpopulate(val, "AllowTaskPreemption", &j.AllowTaskPreemption) + delete(rawMsg, key) + case "commonEnvironmentSettings": + err = unpopulate(val, "CommonEnvironmentSettings", &j.CommonEnvironmentSettings) + delete(rawMsg, key) + case "constraints": + err = unpopulate(val, "Constraints", &j.Constraints) + delete(rawMsg, key) + case "creationTime": + err = unpopulateDateTimeRFC3339(val, "CreationTime", &j.CreationTime) + delete(rawMsg, key) + case "displayName": + err = unpopulate(val, "DisplayName", &j.DisplayName) + delete(rawMsg, key) + case "eTag": + err = unpopulate(val, "ETag", &j.ETag) + delete(rawMsg, key) + case "executionInfo": + err = unpopulate(val, "ExecutionInfo", &j.ExecutionInfo) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &j.ID) + delete(rawMsg, key) + case "jobManagerTask": + err = unpopulate(val, "JobManagerTask", &j.JobManagerTask) + delete(rawMsg, key) + case "jobPreparationTask": + err = unpopulate(val, "JobPreparationTask", &j.JobPreparationTask) + delete(rawMsg, key) + case "jobReleaseTask": + err = unpopulate(val, "JobReleaseTask", &j.JobReleaseTask) + delete(rawMsg, key) + case "lastModified": + err = unpopulateDateTimeRFC3339(val, "LastModified", &j.LastModified) + delete(rawMsg, key) + case "maxParallelTasks": + err = unpopulate(val, "MaxParallelTasks", &j.MaxParallelTasks) + delete(rawMsg, key) + case "metadata": + err = unpopulate(val, "Metadata", &j.Metadata) + delete(rawMsg, key) + case "networkConfiguration": + err = unpopulate(val, "NetworkConfiguration", &j.NetworkConfiguration) + delete(rawMsg, key) + case "onAllTasksComplete": + err = unpopulate(val, "OnAllTasksComplete", &j.OnAllTasksComplete) + delete(rawMsg, key) + case "onTaskFailure": + err = unpopulate(val, "OnTaskFailure", &j.OnTaskFailure) + delete(rawMsg, key) + case "poolInfo": + err = unpopulate(val, "PoolInfo", &j.PoolInfo) + delete(rawMsg, key) + case "previousState": + err = unpopulate(val, "PreviousState", &j.PreviousState) + delete(rawMsg, key) + case "previousStateTransitionTime": + err = unpopulateDateTimeRFC3339(val, "PreviousStateTransitionTime", &j.PreviousStateTransitionTime) + delete(rawMsg, key) + case "priority": + err = unpopulate(val, "Priority", &j.Priority) + delete(rawMsg, key) + case "state": + err = unpopulate(val, "State", &j.State) + delete(rawMsg, key) + case "stateTransitionTime": + err = unpopulateDateTimeRFC3339(val, "StateTransitionTime", &j.StateTransitionTime) + delete(rawMsg, key) + case "stats": + err = unpopulate(val, "Stats", &j.Stats) + delete(rawMsg, key) + case "url": + err = unpopulate(val, "URL", &j.URL) + delete(rawMsg, key) + case "usesTaskDependencies": + err = unpopulate(val, "UsesTaskDependencies", &j.UsesTaskDependencies) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", j, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type JobConstraints. +func (j JobConstraints) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "maxTaskRetryCount", j.MaxTaskRetryCount) + populate(objectMap, "maxWallClockTime", j.MaxWallClockTime) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type JobConstraints. +func (j *JobConstraints) 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", j, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "maxTaskRetryCount": + err = unpopulate(val, "MaxTaskRetryCount", &j.MaxTaskRetryCount) + delete(rawMsg, key) + case "maxWallClockTime": + err = unpopulate(val, "MaxWallClockTime", &j.MaxWallClockTime) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", j, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type JobExecutionInfo. +func (j JobExecutionInfo) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateDateTimeRFC3339(objectMap, "endTime", j.EndTime) + populate(objectMap, "poolId", j.PoolID) + populate(objectMap, "schedulingError", j.SchedulingError) + populateDateTimeRFC3339(objectMap, "startTime", j.StartTime) + populate(objectMap, "terminateReason", j.TerminationReason) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type JobExecutionInfo. +func (j *JobExecutionInfo) 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", j, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "endTime": + err = unpopulateDateTimeRFC3339(val, "EndTime", &j.EndTime) + delete(rawMsg, key) + case "poolId": + err = unpopulate(val, "PoolID", &j.PoolID) + delete(rawMsg, key) + case "schedulingError": + err = unpopulate(val, "SchedulingError", &j.SchedulingError) + delete(rawMsg, key) + case "startTime": + err = unpopulateDateTimeRFC3339(val, "StartTime", &j.StartTime) + delete(rawMsg, key) + case "terminateReason": + err = unpopulate(val, "TerminationReason", &j.TerminationReason) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", j, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type JobListResult. +func (j JobListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "odata.nextLink", j.NextLink) + populate(objectMap, "value", j.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type JobListResult. +func (j *JobListResult) 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", j, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "odata.nextLink": + err = unpopulate(val, "NextLink", &j.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &j.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", j, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type JobManagerTask. +func (j JobManagerTask) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "allowLowPriorityNode", j.AllowLowPriorityNode) + populate(objectMap, "applicationPackageReferences", j.ApplicationPackageReferences) + populate(objectMap, "authenticationTokenSettings", j.AuthenticationTokenSettings) + populate(objectMap, "commandLine", j.CommandLine) + populate(objectMap, "constraints", j.Constraints) + populate(objectMap, "containerSettings", j.ContainerSettings) + populate(objectMap, "displayName", j.DisplayName) + populate(objectMap, "environmentSettings", j.EnvironmentSettings) + populate(objectMap, "id", j.ID) + populate(objectMap, "killJobOnCompletion", j.KillJobOnCompletion) + populate(objectMap, "outputFiles", j.OutputFiles) + populate(objectMap, "requiredSlots", j.RequiredSlots) + populate(objectMap, "resourceFiles", j.ResourceFiles) + populate(objectMap, "runExclusive", j.RunExclusive) + populate(objectMap, "userIdentity", j.UserIdentity) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type JobManagerTask. +func (j *JobManagerTask) 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", j, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "allowLowPriorityNode": + err = unpopulate(val, "AllowLowPriorityNode", &j.AllowLowPriorityNode) + delete(rawMsg, key) + case "applicationPackageReferences": + err = unpopulate(val, "ApplicationPackageReferences", &j.ApplicationPackageReferences) + delete(rawMsg, key) + case "authenticationTokenSettings": + err = unpopulate(val, "AuthenticationTokenSettings", &j.AuthenticationTokenSettings) + delete(rawMsg, key) + case "commandLine": + err = unpopulate(val, "CommandLine", &j.CommandLine) + delete(rawMsg, key) + case "constraints": + err = unpopulate(val, "Constraints", &j.Constraints) + delete(rawMsg, key) + case "containerSettings": + err = unpopulate(val, "ContainerSettings", &j.ContainerSettings) + delete(rawMsg, key) + case "displayName": + err = unpopulate(val, "DisplayName", &j.DisplayName) + delete(rawMsg, key) + case "environmentSettings": + err = unpopulate(val, "EnvironmentSettings", &j.EnvironmentSettings) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &j.ID) + delete(rawMsg, key) + case "killJobOnCompletion": + err = unpopulate(val, "KillJobOnCompletion", &j.KillJobOnCompletion) + delete(rawMsg, key) + case "outputFiles": + err = unpopulate(val, "OutputFiles", &j.OutputFiles) + delete(rawMsg, key) + case "requiredSlots": + err = unpopulate(val, "RequiredSlots", &j.RequiredSlots) + delete(rawMsg, key) + case "resourceFiles": + err = unpopulate(val, "ResourceFiles", &j.ResourceFiles) + delete(rawMsg, key) + case "runExclusive": + err = unpopulate(val, "RunExclusive", &j.RunExclusive) + delete(rawMsg, key) + case "userIdentity": + err = unpopulate(val, "UserIdentity", &j.UserIdentity) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", j, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type JobNetworkConfiguration. +func (j JobNetworkConfiguration) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "skipWithdrawFromVNet", j.SkipWithdrawFromVNet) + populate(objectMap, "subnetId", j.SubnetID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type JobNetworkConfiguration. +func (j *JobNetworkConfiguration) 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", j, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "skipWithdrawFromVNet": + err = unpopulate(val, "SkipWithdrawFromVNet", &j.SkipWithdrawFromVNet) + delete(rawMsg, key) + case "subnetId": + err = unpopulate(val, "SubnetID", &j.SubnetID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", j, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type JobPreparationAndReleaseTaskStatus. +func (j JobPreparationAndReleaseTaskStatus) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "jobPreparationTaskExecutionInfo", j.JobPreparationTaskExecutionInfo) + populate(objectMap, "jobReleaseTaskExecutionInfo", j.JobReleaseTaskExecutionInfo) + populate(objectMap, "nodeId", j.NodeID) + populate(objectMap, "nodeUrl", j.NodeURL) + populate(objectMap, "poolId", j.PoolID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type JobPreparationAndReleaseTaskStatus. +func (j *JobPreparationAndReleaseTaskStatus) 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", j, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "jobPreparationTaskExecutionInfo": + err = unpopulate(val, "JobPreparationTaskExecutionInfo", &j.JobPreparationTaskExecutionInfo) + delete(rawMsg, key) + case "jobReleaseTaskExecutionInfo": + err = unpopulate(val, "JobReleaseTaskExecutionInfo", &j.JobReleaseTaskExecutionInfo) + delete(rawMsg, key) + case "nodeId": + err = unpopulate(val, "NodeID", &j.NodeID) + delete(rawMsg, key) + case "nodeUrl": + err = unpopulate(val, "NodeURL", &j.NodeURL) + delete(rawMsg, key) + case "poolId": + err = unpopulate(val, "PoolID", &j.PoolID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", j, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type JobPreparationAndReleaseTaskStatusListResult. +func (j JobPreparationAndReleaseTaskStatusListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "odata.nextLink", j.NextLink) + populate(objectMap, "value", j.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type JobPreparationAndReleaseTaskStatusListResult. +func (j *JobPreparationAndReleaseTaskStatusListResult) 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", j, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "odata.nextLink": + err = unpopulate(val, "NextLink", &j.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &j.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", j, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type JobPreparationTask. +func (j JobPreparationTask) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "commandLine", j.CommandLine) + populate(objectMap, "constraints", j.Constraints) + populate(objectMap, "containerSettings", j.ContainerSettings) + populate(objectMap, "environmentSettings", j.EnvironmentSettings) + populate(objectMap, "id", j.ID) + populate(objectMap, "rerunOnNodeRebootAfterSuccess", j.RerunOnNodeRebootAfterSuccess) + populate(objectMap, "resourceFiles", j.ResourceFiles) + populate(objectMap, "userIdentity", j.UserIdentity) + populate(objectMap, "waitForSuccess", j.WaitForSuccess) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type JobPreparationTask. +func (j *JobPreparationTask) 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", j, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "commandLine": + err = unpopulate(val, "CommandLine", &j.CommandLine) + delete(rawMsg, key) + case "constraints": + err = unpopulate(val, "Constraints", &j.Constraints) + delete(rawMsg, key) + case "containerSettings": + err = unpopulate(val, "ContainerSettings", &j.ContainerSettings) + delete(rawMsg, key) + case "environmentSettings": + err = unpopulate(val, "EnvironmentSettings", &j.EnvironmentSettings) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &j.ID) + delete(rawMsg, key) + case "rerunOnNodeRebootAfterSuccess": + err = unpopulate(val, "RerunOnNodeRebootAfterSuccess", &j.RerunOnNodeRebootAfterSuccess) + delete(rawMsg, key) + case "resourceFiles": + err = unpopulate(val, "ResourceFiles", &j.ResourceFiles) + delete(rawMsg, key) + case "userIdentity": + err = unpopulate(val, "UserIdentity", &j.UserIdentity) + delete(rawMsg, key) + case "waitForSuccess": + err = unpopulate(val, "WaitForSuccess", &j.WaitForSuccess) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", j, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type JobPreparationTaskExecutionInfo. +func (j JobPreparationTaskExecutionInfo) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "containerInfo", j.ContainerInfo) + populateDateTimeRFC3339(objectMap, "endTime", j.EndTime) + populate(objectMap, "exitCode", j.ExitCode) + populate(objectMap, "failureInfo", j.FailureInfo) + populateDateTimeRFC3339(objectMap, "lastRetryTime", j.LastRetryTime) + populate(objectMap, "result", j.Result) + populate(objectMap, "retryCount", j.RetryCount) + populateDateTimeRFC3339(objectMap, "startTime", j.StartTime) + populate(objectMap, "state", j.State) + populate(objectMap, "taskRootDirectory", j.TaskRootDirectory) + populate(objectMap, "taskRootDirectoryUrl", j.TaskRootDirectoryURL) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type JobPreparationTaskExecutionInfo. +func (j *JobPreparationTaskExecutionInfo) 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", j, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "containerInfo": + err = unpopulate(val, "ContainerInfo", &j.ContainerInfo) + delete(rawMsg, key) + case "endTime": + err = unpopulateDateTimeRFC3339(val, "EndTime", &j.EndTime) + delete(rawMsg, key) + case "exitCode": + err = unpopulate(val, "ExitCode", &j.ExitCode) + delete(rawMsg, key) + case "failureInfo": + err = unpopulate(val, "FailureInfo", &j.FailureInfo) + delete(rawMsg, key) + case "lastRetryTime": + err = unpopulateDateTimeRFC3339(val, "LastRetryTime", &j.LastRetryTime) + delete(rawMsg, key) + case "result": + err = unpopulate(val, "Result", &j.Result) + delete(rawMsg, key) + case "retryCount": + err = unpopulate(val, "RetryCount", &j.RetryCount) + delete(rawMsg, key) + case "startTime": + err = unpopulateDateTimeRFC3339(val, "StartTime", &j.StartTime) + delete(rawMsg, key) + case "state": + err = unpopulate(val, "State", &j.State) + delete(rawMsg, key) + case "taskRootDirectory": + err = unpopulate(val, "TaskRootDirectory", &j.TaskRootDirectory) + delete(rawMsg, key) + case "taskRootDirectoryUrl": + err = unpopulate(val, "TaskRootDirectoryURL", &j.TaskRootDirectoryURL) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", j, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type JobReleaseTask. +func (j JobReleaseTask) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "commandLine", j.CommandLine) + populate(objectMap, "containerSettings", j.ContainerSettings) + populate(objectMap, "environmentSettings", j.EnvironmentSettings) + populate(objectMap, "id", j.ID) + populate(objectMap, "maxWallClockTime", j.MaxWallClockTime) + populate(objectMap, "resourceFiles", j.ResourceFiles) + populate(objectMap, "retentionTime", j.RetentionTime) + populate(objectMap, "userIdentity", j.UserIdentity) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type JobReleaseTask. +func (j *JobReleaseTask) 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", j, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "commandLine": + err = unpopulate(val, "CommandLine", &j.CommandLine) + delete(rawMsg, key) + case "containerSettings": + err = unpopulate(val, "ContainerSettings", &j.ContainerSettings) + delete(rawMsg, key) + case "environmentSettings": + err = unpopulate(val, "EnvironmentSettings", &j.EnvironmentSettings) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &j.ID) + delete(rawMsg, key) + case "maxWallClockTime": + err = unpopulate(val, "MaxWallClockTime", &j.MaxWallClockTime) + delete(rawMsg, key) + case "resourceFiles": + err = unpopulate(val, "ResourceFiles", &j.ResourceFiles) + delete(rawMsg, key) + case "retentionTime": + err = unpopulate(val, "RetentionTime", &j.RetentionTime) + delete(rawMsg, key) + case "userIdentity": + err = unpopulate(val, "UserIdentity", &j.UserIdentity) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", j, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type JobReleaseTaskExecutionInfo. +func (j JobReleaseTaskExecutionInfo) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "containerInfo", j.ContainerInfo) + populateDateTimeRFC3339(objectMap, "endTime", j.EndTime) + populate(objectMap, "exitCode", j.ExitCode) + populate(objectMap, "failureInfo", j.FailureInfo) + populate(objectMap, "result", j.Result) + populateDateTimeRFC3339(objectMap, "startTime", j.StartTime) + populate(objectMap, "state", j.State) + populate(objectMap, "taskRootDirectory", j.TaskRootDirectory) + populate(objectMap, "taskRootDirectoryUrl", j.TaskRootDirectoryURL) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type JobReleaseTaskExecutionInfo. +func (j *JobReleaseTaskExecutionInfo) 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", j, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "containerInfo": + err = unpopulate(val, "ContainerInfo", &j.ContainerInfo) + delete(rawMsg, key) + case "endTime": + err = unpopulateDateTimeRFC3339(val, "EndTime", &j.EndTime) + delete(rawMsg, key) + case "exitCode": + err = unpopulate(val, "ExitCode", &j.ExitCode) + delete(rawMsg, key) + case "failureInfo": + err = unpopulate(val, "FailureInfo", &j.FailureInfo) + delete(rawMsg, key) + case "result": + err = unpopulate(val, "Result", &j.Result) + delete(rawMsg, key) + case "startTime": + err = unpopulateDateTimeRFC3339(val, "StartTime", &j.StartTime) + delete(rawMsg, key) + case "state": + err = unpopulate(val, "State", &j.State) + delete(rawMsg, key) + case "taskRootDirectory": + err = unpopulate(val, "TaskRootDirectory", &j.TaskRootDirectory) + delete(rawMsg, key) + case "taskRootDirectoryUrl": + err = unpopulate(val, "TaskRootDirectoryURL", &j.TaskRootDirectoryURL) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", j, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type JobSchedule. +func (j JobSchedule) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateDateTimeRFC3339(objectMap, "creationTime", j.CreationTime) + populate(objectMap, "displayName", j.DisplayName) + populate(objectMap, "eTag", j.ETag) + populate(objectMap, "executionInfo", j.ExecutionInfo) + populate(objectMap, "id", j.ID) + populate(objectMap, "jobSpecification", j.JobSpecification) + populateDateTimeRFC3339(objectMap, "lastModified", j.LastModified) + populate(objectMap, "metadata", j.Metadata) + populate(objectMap, "previousState", j.PreviousState) + populateDateTimeRFC3339(objectMap, "previousStateTransitionTime", j.PreviousStateTransitionTime) + populate(objectMap, "schedule", j.Schedule) + populate(objectMap, "state", j.State) + populateDateTimeRFC3339(objectMap, "stateTransitionTime", j.StateTransitionTime) + populate(objectMap, "stats", j.Stats) + populate(objectMap, "url", j.URL) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type JobSchedule. +func (j *JobSchedule) 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", j, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "creationTime": + err = unpopulateDateTimeRFC3339(val, "CreationTime", &j.CreationTime) + delete(rawMsg, key) + case "displayName": + err = unpopulate(val, "DisplayName", &j.DisplayName) + delete(rawMsg, key) + case "eTag": + err = unpopulate(val, "ETag", &j.ETag) + delete(rawMsg, key) + case "executionInfo": + err = unpopulate(val, "ExecutionInfo", &j.ExecutionInfo) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &j.ID) + delete(rawMsg, key) + case "jobSpecification": + err = unpopulate(val, "JobSpecification", &j.JobSpecification) + delete(rawMsg, key) + case "lastModified": + err = unpopulateDateTimeRFC3339(val, "LastModified", &j.LastModified) + delete(rawMsg, key) + case "metadata": + err = unpopulate(val, "Metadata", &j.Metadata) + delete(rawMsg, key) + case "previousState": + err = unpopulate(val, "PreviousState", &j.PreviousState) + delete(rawMsg, key) + case "previousStateTransitionTime": + err = unpopulateDateTimeRFC3339(val, "PreviousStateTransitionTime", &j.PreviousStateTransitionTime) + delete(rawMsg, key) + case "schedule": + err = unpopulate(val, "Schedule", &j.Schedule) + delete(rawMsg, key) + case "state": + err = unpopulate(val, "State", &j.State) + delete(rawMsg, key) + case "stateTransitionTime": + err = unpopulateDateTimeRFC3339(val, "StateTransitionTime", &j.StateTransitionTime) + delete(rawMsg, key) + case "stats": + err = unpopulate(val, "Stats", &j.Stats) + delete(rawMsg, key) + case "url": + err = unpopulate(val, "URL", &j.URL) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", j, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type JobScheduleConfiguration. +func (j JobScheduleConfiguration) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateDateTimeRFC3339(objectMap, "doNotRunAfter", j.DoNotRunAfter) + populateDateTimeRFC3339(objectMap, "doNotRunUntil", j.DoNotRunUntil) + populate(objectMap, "recurrenceInterval", j.RecurrenceInterval) + populate(objectMap, "startWindow", j.StartWindow) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type JobScheduleConfiguration. +func (j *JobScheduleConfiguration) 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", j, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "doNotRunAfter": + err = unpopulateDateTimeRFC3339(val, "DoNotRunAfter", &j.DoNotRunAfter) + delete(rawMsg, key) + case "doNotRunUntil": + err = unpopulateDateTimeRFC3339(val, "DoNotRunUntil", &j.DoNotRunUntil) + delete(rawMsg, key) + case "recurrenceInterval": + err = unpopulate(val, "RecurrenceInterval", &j.RecurrenceInterval) + delete(rawMsg, key) + case "startWindow": + err = unpopulate(val, "StartWindow", &j.StartWindow) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", j, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type JobScheduleExecutionInfo. +func (j JobScheduleExecutionInfo) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateDateTimeRFC3339(objectMap, "endTime", j.EndTime) + populateDateTimeRFC3339(objectMap, "nextRunTime", j.NextRunTime) + populate(objectMap, "recentJob", j.RecentJob) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type JobScheduleExecutionInfo. +func (j *JobScheduleExecutionInfo) 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", j, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "endTime": + err = unpopulateDateTimeRFC3339(val, "EndTime", &j.EndTime) + delete(rawMsg, key) + case "nextRunTime": + err = unpopulateDateTimeRFC3339(val, "NextRunTime", &j.NextRunTime) + delete(rawMsg, key) + case "recentJob": + err = unpopulate(val, "RecentJob", &j.RecentJob) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", j, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type JobScheduleListResult. +func (j JobScheduleListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "odata.nextLink", j.NextLink) + populate(objectMap, "value", j.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type JobScheduleListResult. +func (j *JobScheduleListResult) 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", j, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "odata.nextLink": + err = unpopulate(val, "NextLink", &j.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &j.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", j, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type JobScheduleStatistics. +func (j JobScheduleStatistics) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "kernelCPUTime", j.KernelCPUTime) + populateDateTimeRFC3339(objectMap, "lastUpdateTime", j.LastUpdateTime) + populate(objectMap, "numFailedTasks", to.Ptr(strconv.FormatInt(*j.NumFailedTasks, 10))) + populate(objectMap, "numSucceededTasks", to.Ptr(strconv.FormatInt(*j.NumSucceededTasks, 10))) + populate(objectMap, "numTaskRetries", to.Ptr(strconv.FormatInt(*j.NumTaskRetries, 10))) + populate(objectMap, "readIOGiB", j.ReadIOGiB) + populate(objectMap, "readIOps", to.Ptr(strconv.FormatInt(*j.ReadIOPS, 10))) + populateDateTimeRFC3339(objectMap, "startTime", j.StartTime) + populate(objectMap, "url", j.URL) + populate(objectMap, "userCPUTime", j.UserCPUTime) + populate(objectMap, "waitTime", j.WaitTime) + populate(objectMap, "wallClockTime", j.WallClockTime) + populate(objectMap, "writeIOGiB", j.WriteIOGiB) + populate(objectMap, "writeIOps", to.Ptr(strconv.FormatInt(*j.WriteIOPS, 10))) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type JobScheduleStatistics. +func (j *JobScheduleStatistics) 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", j, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "kernelCPUTime": + err = unpopulate(val, "KernelCPUTime", &j.KernelCPUTime) + delete(rawMsg, key) + case "lastUpdateTime": + err = unpopulateDateTimeRFC3339(val, "LastUpdateTime", &j.LastUpdateTime) + delete(rawMsg, key) + case "numFailedTasks": + var aux string + err = unpopulate(val, "NumFailedTasks", &aux) + if err == nil { + var v int64 + v, err = strconv.ParseInt(aux, 10, 0) + if err == nil { + j.NumFailedTasks = to.Ptr(v) + } + } + delete(rawMsg, key) + case "numSucceededTasks": + var aux string + err = unpopulate(val, "NumSucceededTasks", &aux) + if err == nil { + var v int64 + v, err = strconv.ParseInt(aux, 10, 0) + if err == nil { + j.NumSucceededTasks = to.Ptr(v) + } + } + delete(rawMsg, key) + case "numTaskRetries": + var aux string + err = unpopulate(val, "NumTaskRetries", &aux) + if err == nil { + var v int64 + v, err = strconv.ParseInt(aux, 10, 0) + if err == nil { + j.NumTaskRetries = to.Ptr(v) + } + } + delete(rawMsg, key) + case "readIOGiB": + err = unpopulate(val, "ReadIOGiB", &j.ReadIOGiB) + delete(rawMsg, key) + case "readIOps": + var aux string + err = unpopulate(val, "ReadIOPS", &aux) + if err == nil { + var v int64 + v, err = strconv.ParseInt(aux, 10, 0) + if err == nil { + j.ReadIOPS = to.Ptr(v) + } + } + delete(rawMsg, key) + case "startTime": + err = unpopulateDateTimeRFC3339(val, "StartTime", &j.StartTime) + delete(rawMsg, key) + case "url": + err = unpopulate(val, "URL", &j.URL) + delete(rawMsg, key) + case "userCPUTime": + err = unpopulate(val, "UserCPUTime", &j.UserCPUTime) + delete(rawMsg, key) + case "waitTime": + err = unpopulate(val, "WaitTime", &j.WaitTime) + delete(rawMsg, key) + case "wallClockTime": + err = unpopulate(val, "WallClockTime", &j.WallClockTime) + delete(rawMsg, key) + case "writeIOGiB": + err = unpopulate(val, "WriteIOGiB", &j.WriteIOGiB) + delete(rawMsg, key) + case "writeIOps": + var aux string + err = unpopulate(val, "WriteIOPS", &aux) + if err == nil { + var v int64 + v, err = strconv.ParseInt(aux, 10, 0) + if err == nil { + j.WriteIOPS = to.Ptr(v) + } + } + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", j, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type JobSchedulingError. +func (j JobSchedulingError) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "category", j.Category) + populate(objectMap, "code", j.Code) + populate(objectMap, "details", j.Details) + populate(objectMap, "message", j.Message) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type JobSchedulingError. +func (j *JobSchedulingError) 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", j, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "category": + err = unpopulate(val, "Category", &j.Category) + delete(rawMsg, key) + case "code": + err = unpopulate(val, "Code", &j.Code) + delete(rawMsg, key) + case "details": + err = unpopulate(val, "Details", &j.Details) + delete(rawMsg, key) + case "message": + err = unpopulate(val, "Message", &j.Message) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", j, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type JobSpecification. +func (j JobSpecification) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "allowTaskPreemption", j.AllowTaskPreemption) + populate(objectMap, "commonEnvironmentSettings", j.CommonEnvironmentSettings) + populate(objectMap, "constraints", j.Constraints) + populate(objectMap, "displayName", j.DisplayName) + populate(objectMap, "jobManagerTask", j.JobManagerTask) + populate(objectMap, "jobPreparationTask", j.JobPreparationTask) + populate(objectMap, "jobReleaseTask", j.JobReleaseTask) + populate(objectMap, "maxParallelTasks", j.MaxParallelTasks) + populate(objectMap, "metadata", j.Metadata) + populate(objectMap, "networkConfiguration", j.NetworkConfiguration) + populate(objectMap, "onAllTasksComplete", j.OnAllTasksComplete) + populate(objectMap, "onTaskFailure", j.OnTaskFailure) + populate(objectMap, "poolInfo", j.PoolInfo) + populate(objectMap, "priority", j.Priority) + populate(objectMap, "usesTaskDependencies", j.UsesTaskDependencies) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type JobSpecification. +func (j *JobSpecification) 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", j, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "allowTaskPreemption": + err = unpopulate(val, "AllowTaskPreemption", &j.AllowTaskPreemption) + delete(rawMsg, key) + case "commonEnvironmentSettings": + err = unpopulate(val, "CommonEnvironmentSettings", &j.CommonEnvironmentSettings) + delete(rawMsg, key) + case "constraints": + err = unpopulate(val, "Constraints", &j.Constraints) + delete(rawMsg, key) + case "displayName": + err = unpopulate(val, "DisplayName", &j.DisplayName) + delete(rawMsg, key) + case "jobManagerTask": + err = unpopulate(val, "JobManagerTask", &j.JobManagerTask) + delete(rawMsg, key) + case "jobPreparationTask": + err = unpopulate(val, "JobPreparationTask", &j.JobPreparationTask) + delete(rawMsg, key) + case "jobReleaseTask": + err = unpopulate(val, "JobReleaseTask", &j.JobReleaseTask) + delete(rawMsg, key) + case "maxParallelTasks": + err = unpopulate(val, "MaxParallelTasks", &j.MaxParallelTasks) + delete(rawMsg, key) + case "metadata": + err = unpopulate(val, "Metadata", &j.Metadata) + delete(rawMsg, key) + case "networkConfiguration": + err = unpopulate(val, "NetworkConfiguration", &j.NetworkConfiguration) + delete(rawMsg, key) + case "onAllTasksComplete": + err = unpopulate(val, "OnAllTasksComplete", &j.OnAllTasksComplete) + delete(rawMsg, key) + case "onTaskFailure": + err = unpopulate(val, "OnTaskFailure", &j.OnTaskFailure) + delete(rawMsg, key) + case "poolInfo": + err = unpopulate(val, "PoolInfo", &j.PoolInfo) + delete(rawMsg, key) + case "priority": + err = unpopulate(val, "Priority", &j.Priority) + delete(rawMsg, key) + case "usesTaskDependencies": + err = unpopulate(val, "UsesTaskDependencies", &j.UsesTaskDependencies) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", j, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type JobStatistics. +func (j JobStatistics) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "kernelCPUTime", j.KernelCPUTime) + populateDateTimeRFC3339(objectMap, "lastUpdateTime", j.LastUpdateTime) + populate(objectMap, "numFailedTasks", to.Ptr(strconv.FormatInt(*j.NumFailedTasks, 10))) + populate(objectMap, "numSucceededTasks", to.Ptr(strconv.FormatInt(*j.NumSucceededTasks, 10))) + populate(objectMap, "numTaskRetries", to.Ptr(strconv.FormatInt(*j.NumTaskRetries, 10))) + populate(objectMap, "readIOGiB", j.ReadIOGiB) + populate(objectMap, "readIOps", to.Ptr(strconv.FormatInt(*j.ReadIOps, 10))) + populateDateTimeRFC3339(objectMap, "startTime", j.StartTime) + populate(objectMap, "url", j.URL) + populate(objectMap, "userCPUTime", j.UserCPUTime) + populate(objectMap, "waitTime", j.WaitTime) + populate(objectMap, "wallClockTime", j.WallClockTime) + populate(objectMap, "writeIOGiB", j.WriteIOGiB) + populate(objectMap, "writeIOps", to.Ptr(strconv.FormatInt(*j.WriteIOps, 10))) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type JobStatistics. +func (j *JobStatistics) 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", j, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "kernelCPUTime": + err = unpopulate(val, "KernelCPUTime", &j.KernelCPUTime) + delete(rawMsg, key) + case "lastUpdateTime": + err = unpopulateDateTimeRFC3339(val, "LastUpdateTime", &j.LastUpdateTime) + delete(rawMsg, key) + case "numFailedTasks": + var aux string + err = unpopulate(val, "NumFailedTasks", &aux) + if err == nil { + var v int64 + v, err = strconv.ParseInt(aux, 10, 0) + if err == nil { + j.NumFailedTasks = to.Ptr(v) + } + } + delete(rawMsg, key) + case "numSucceededTasks": + var aux string + err = unpopulate(val, "NumSucceededTasks", &aux) + if err == nil { + var v int64 + v, err = strconv.ParseInt(aux, 10, 0) + if err == nil { + j.NumSucceededTasks = to.Ptr(v) + } + } + delete(rawMsg, key) + case "numTaskRetries": + var aux string + err = unpopulate(val, "NumTaskRetries", &aux) + if err == nil { + var v int64 + v, err = strconv.ParseInt(aux, 10, 0) + if err == nil { + j.NumTaskRetries = to.Ptr(v) + } + } + delete(rawMsg, key) + case "readIOGiB": + err = unpopulate(val, "ReadIOGiB", &j.ReadIOGiB) + delete(rawMsg, key) + case "readIOps": + var aux string + err = unpopulate(val, "ReadIOps", &aux) + if err == nil { + var v int64 + v, err = strconv.ParseInt(aux, 10, 0) + if err == nil { + j.ReadIOps = to.Ptr(v) + } + } + delete(rawMsg, key) + case "startTime": + err = unpopulateDateTimeRFC3339(val, "StartTime", &j.StartTime) + delete(rawMsg, key) + case "url": + err = unpopulate(val, "URL", &j.URL) + delete(rawMsg, key) + case "userCPUTime": + err = unpopulate(val, "UserCPUTime", &j.UserCPUTime) + delete(rawMsg, key) + case "waitTime": + err = unpopulate(val, "WaitTime", &j.WaitTime) + delete(rawMsg, key) + case "wallClockTime": + err = unpopulate(val, "WallClockTime", &j.WallClockTime) + delete(rawMsg, key) + case "writeIOGiB": + err = unpopulate(val, "WriteIOGiB", &j.WriteIOGiB) + delete(rawMsg, key) + case "writeIOps": + var aux string + err = unpopulate(val, "WriteIOps", &aux) + if err == nil { + var v int64 + v, err = strconv.ParseInt(aux, 10, 0) + if err == nil { + j.WriteIOps = to.Ptr(v) + } + } + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", j, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type LinuxUserConfiguration. +func (l LinuxUserConfiguration) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "gid", l.GID) + populate(objectMap, "sshPrivateKey", l.SSHPrivateKey) + populate(objectMap, "uid", l.UID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type LinuxUserConfiguration. +func (l *LinuxUserConfiguration) 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 "gid": + err = unpopulate(val, "GID", &l.GID) + delete(rawMsg, key) + case "sshPrivateKey": + err = unpopulate(val, "SSHPrivateKey", &l.SSHPrivateKey) + delete(rawMsg, key) + case "uid": + err = unpopulate(val, "UID", &l.UID) + 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 ListPoolNodeCountsResult. +func (l ListPoolNodeCountsResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "odata.nextLink", l.NextLink) + populate(objectMap, "value", l.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ListPoolNodeCountsResult. +func (l *ListPoolNodeCountsResult) 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 "odata.nextLink": + err = unpopulate(val, "NextLink", &l.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &l.Value) + 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 ManagedDisk. +func (m ManagedDisk) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "securityProfile", m.SecurityProfile) + populate(objectMap, "storageAccountType", m.StorageAccountType) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ManagedDisk. +func (m *ManagedDisk) 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 "securityProfile": + err = unpopulate(val, "SecurityProfile", &m.SecurityProfile) + delete(rawMsg, key) + case "storageAccountType": + err = unpopulate(val, "StorageAccountType", &m.StorageAccountType) + 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 MetadataItem. +func (m MetadataItem) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", m.Name) + populate(objectMap, "value", m.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type MetadataItem. +func (m *MetadataItem) 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 "name": + err = unpopulate(val, "Name", &m.Name) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &m.Value) + 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 MountConfiguration. +func (m MountConfiguration) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "azureBlobFileSystemConfiguration", m.AzureBlobFileSystemConfiguration) + populate(objectMap, "azureFileShareConfiguration", m.AzureFileShareConfiguration) + populate(objectMap, "cifsMountConfiguration", m.CifsMountConfiguration) + populate(objectMap, "nfsMountConfiguration", m.NfsMountConfiguration) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type MountConfiguration. +func (m *MountConfiguration) 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 "azureBlobFileSystemConfiguration": + err = unpopulate(val, "AzureBlobFileSystemConfiguration", &m.AzureBlobFileSystemConfiguration) + delete(rawMsg, key) + case "azureFileShareConfiguration": + err = unpopulate(val, "AzureFileShareConfiguration", &m.AzureFileShareConfiguration) + delete(rawMsg, key) + case "cifsMountConfiguration": + err = unpopulate(val, "CifsMountConfiguration", &m.CifsMountConfiguration) + delete(rawMsg, key) + case "nfsMountConfiguration": + err = unpopulate(val, "NfsMountConfiguration", &m.NfsMountConfiguration) + 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 MultiInstanceSettings. +func (m MultiInstanceSettings) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "commonResourceFiles", m.CommonResourceFiles) + populate(objectMap, "coordinationCommandLine", m.CoordinationCommandLine) + populate(objectMap, "numberOfInstances", m.NumberOfInstances) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type MultiInstanceSettings. +func (m *MultiInstanceSettings) 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 "commonResourceFiles": + err = unpopulate(val, "CommonResourceFiles", &m.CommonResourceFiles) + delete(rawMsg, key) + case "coordinationCommandLine": + err = unpopulate(val, "CoordinationCommandLine", &m.CoordinationCommandLine) + delete(rawMsg, key) + case "numberOfInstances": + err = unpopulate(val, "NumberOfInstances", &m.NumberOfInstances) + 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 NFSMountConfiguration. +func (n NFSMountConfiguration) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "mountOptions", n.MountOptions) + populate(objectMap, "relativeMountPath", n.RelativeMountPath) + populate(objectMap, "source", n.Source) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type NFSMountConfiguration. +func (n *NFSMountConfiguration) 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", n, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "mountOptions": + err = unpopulate(val, "MountOptions", &n.MountOptions) + delete(rawMsg, key) + case "relativeMountPath": + err = unpopulate(val, "RelativeMountPath", &n.RelativeMountPath) + delete(rawMsg, key) + case "source": + err = unpopulate(val, "Source", &n.Source) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type NameValuePair. +func (n NameValuePair) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", n.Name) + populate(objectMap, "value", n.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type NameValuePair. +func (n *NameValuePair) 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", n, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &n.Name) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &n.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type NetworkConfiguration. +func (n NetworkConfiguration) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "dynamicVNetAssignmentScope", n.DynamicVNetAssignmentScope) + populate(objectMap, "enableAcceleratedNetworking", n.EnableAcceleratedNetworking) + populate(objectMap, "endpointConfiguration", n.EndpointConfiguration) + populate(objectMap, "publicIPAddressConfiguration", n.PublicIPAddressConfiguration) + populate(objectMap, "subnetId", n.SubnetID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type NetworkConfiguration. +func (n *NetworkConfiguration) 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", n, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "dynamicVNetAssignmentScope": + err = unpopulate(val, "DynamicVNetAssignmentScope", &n.DynamicVNetAssignmentScope) + delete(rawMsg, key) + case "enableAcceleratedNetworking": + err = unpopulate(val, "EnableAcceleratedNetworking", &n.EnableAcceleratedNetworking) + delete(rawMsg, key) + case "endpointConfiguration": + err = unpopulate(val, "EndpointConfiguration", &n.EndpointConfiguration) + delete(rawMsg, key) + case "publicIPAddressConfiguration": + err = unpopulate(val, "PublicIPAddressConfiguration", &n.PublicIPAddressConfiguration) + delete(rawMsg, key) + case "subnetId": + err = unpopulate(val, "SubnetID", &n.SubnetID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type NetworkSecurityGroupRule. +func (n NetworkSecurityGroupRule) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "access", n.Access) + populate(objectMap, "priority", n.Priority) + populate(objectMap, "sourceAddressPrefix", n.SourceAddressPrefix) + populate(objectMap, "sourcePortRanges", n.SourcePortRanges) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type NetworkSecurityGroupRule. +func (n *NetworkSecurityGroupRule) 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", n, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "access": + err = unpopulate(val, "Access", &n.Access) + delete(rawMsg, key) + case "priority": + err = unpopulate(val, "Priority", &n.Priority) + delete(rawMsg, key) + case "sourceAddressPrefix": + err = unpopulate(val, "SourceAddressPrefix", &n.SourceAddressPrefix) + delete(rawMsg, key) + case "sourcePortRanges": + err = unpopulate(val, "SourcePortRanges", &n.SourcePortRanges) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Node. +func (n Node) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "affinityId", n.AffinityID) + populateDateTimeRFC3339(objectMap, "allocationTime", n.AllocationTime) + populate(objectMap, "certificateReferences", n.CertificateReferences) + populate(objectMap, "endpointConfiguration", n.EndpointConfiguration) + populate(objectMap, "errors", n.Errors) + populate(objectMap, "id", n.ID) + populate(objectMap, "ipAddress", n.IPAddress) + populate(objectMap, "isDedicated", n.IsDedicated) + populateDateTimeRFC3339(objectMap, "lastBootTime", n.LastBootTime) + populate(objectMap, "nodeAgentInfo", n.NodeAgentInfo) + populate(objectMap, "recentTasks", n.RecentTasks) + populate(objectMap, "runningTaskSlotsCount", n.RunningTaskSlotsCount) + populate(objectMap, "runningTasksCount", n.RunningTasksCount) + populate(objectMap, "schedulingState", n.SchedulingState) + populate(objectMap, "startTask", n.StartTask) + populate(objectMap, "startTaskInfo", n.StartTaskInfo) + populate(objectMap, "state", n.State) + populateDateTimeRFC3339(objectMap, "stateTransitionTime", n.StateTransitionTime) + populate(objectMap, "totalTasksRun", n.TotalTasksRun) + populate(objectMap, "totalTasksSucceeded", n.TotalTasksSucceeded) + populate(objectMap, "url", n.URL) + populate(objectMap, "vmSize", n.VMSize) + populate(objectMap, "virtualMachineInfo", n.VirtualMachineInfo) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Node. +func (n *Node) 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", n, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "affinityId": + err = unpopulate(val, "AffinityID", &n.AffinityID) + delete(rawMsg, key) + case "allocationTime": + err = unpopulateDateTimeRFC3339(val, "AllocationTime", &n.AllocationTime) + delete(rawMsg, key) + case "certificateReferences": + err = unpopulate(val, "CertificateReferences", &n.CertificateReferences) + delete(rawMsg, key) + case "endpointConfiguration": + err = unpopulate(val, "EndpointConfiguration", &n.EndpointConfiguration) + delete(rawMsg, key) + case "errors": + err = unpopulate(val, "Errors", &n.Errors) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &n.ID) + delete(rawMsg, key) + case "ipAddress": + err = unpopulate(val, "IPAddress", &n.IPAddress) + delete(rawMsg, key) + case "isDedicated": + err = unpopulate(val, "IsDedicated", &n.IsDedicated) + delete(rawMsg, key) + case "lastBootTime": + err = unpopulateDateTimeRFC3339(val, "LastBootTime", &n.LastBootTime) + delete(rawMsg, key) + case "nodeAgentInfo": + err = unpopulate(val, "NodeAgentInfo", &n.NodeAgentInfo) + delete(rawMsg, key) + case "recentTasks": + err = unpopulate(val, "RecentTasks", &n.RecentTasks) + delete(rawMsg, key) + case "runningTaskSlotsCount": + err = unpopulate(val, "RunningTaskSlotsCount", &n.RunningTaskSlotsCount) + delete(rawMsg, key) + case "runningTasksCount": + err = unpopulate(val, "RunningTasksCount", &n.RunningTasksCount) + delete(rawMsg, key) + case "schedulingState": + err = unpopulate(val, "SchedulingState", &n.SchedulingState) + delete(rawMsg, key) + case "startTask": + err = unpopulate(val, "StartTask", &n.StartTask) + delete(rawMsg, key) + case "startTaskInfo": + err = unpopulate(val, "StartTaskInfo", &n.StartTaskInfo) + delete(rawMsg, key) + case "state": + err = unpopulate(val, "State", &n.State) + delete(rawMsg, key) + case "stateTransitionTime": + err = unpopulateDateTimeRFC3339(val, "StateTransitionTime", &n.StateTransitionTime) + delete(rawMsg, key) + case "totalTasksRun": + err = unpopulate(val, "TotalTasksRun", &n.TotalTasksRun) + delete(rawMsg, key) + case "totalTasksSucceeded": + err = unpopulate(val, "TotalTasksSucceeded", &n.TotalTasksSucceeded) + delete(rawMsg, key) + case "url": + err = unpopulate(val, "URL", &n.URL) + delete(rawMsg, key) + case "vmSize": + err = unpopulate(val, "VMSize", &n.VMSize) + delete(rawMsg, key) + case "virtualMachineInfo": + err = unpopulate(val, "VirtualMachineInfo", &n.VirtualMachineInfo) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type NodeAgentInfo. +func (n NodeAgentInfo) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateDateTimeRFC3339(objectMap, "lastUpdateTime", n.LastUpdateTime) + populate(objectMap, "version", n.Version) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type NodeAgentInfo. +func (n *NodeAgentInfo) 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", n, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "lastUpdateTime": + err = unpopulateDateTimeRFC3339(val, "LastUpdateTime", &n.LastUpdateTime) + delete(rawMsg, key) + case "version": + err = unpopulate(val, "Version", &n.Version) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type NodeCounts. +func (n NodeCounts) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "creating", n.Creating) + populate(objectMap, "deallocated", n.Deallocated) + populate(objectMap, "deallocating", n.Deallocating) + populate(objectMap, "idle", n.Idle) + populate(objectMap, "leavingPool", n.LeavingPool) + populate(objectMap, "offline", n.Offline) + populate(objectMap, "preempted", n.Preempted) + populate(objectMap, "rebooting", n.Rebooting) + populate(objectMap, "reimaging", n.Reimaging) + populate(objectMap, "running", n.Running) + populate(objectMap, "startTaskFailed", n.StartTaskFailed) + populate(objectMap, "starting", n.Starting) + populate(objectMap, "total", n.Total) + populate(objectMap, "unknown", n.Unknown) + populate(objectMap, "unusable", n.Unusable) + populate(objectMap, "upgradingOS", n.UpgradingOS) + populate(objectMap, "waitingForStartTask", n.WaitingForStartTask) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type NodeCounts. +func (n *NodeCounts) 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", n, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "creating": + err = unpopulate(val, "Creating", &n.Creating) + delete(rawMsg, key) + case "deallocated": + err = unpopulate(val, "Deallocated", &n.Deallocated) + delete(rawMsg, key) + case "deallocating": + err = unpopulate(val, "Deallocating", &n.Deallocating) + delete(rawMsg, key) + case "idle": + err = unpopulate(val, "Idle", &n.Idle) + delete(rawMsg, key) + case "leavingPool": + err = unpopulate(val, "LeavingPool", &n.LeavingPool) + delete(rawMsg, key) + case "offline": + err = unpopulate(val, "Offline", &n.Offline) + delete(rawMsg, key) + case "preempted": + err = unpopulate(val, "Preempted", &n.Preempted) + delete(rawMsg, key) + case "rebooting": + err = unpopulate(val, "Rebooting", &n.Rebooting) + delete(rawMsg, key) + case "reimaging": + err = unpopulate(val, "Reimaging", &n.Reimaging) + delete(rawMsg, key) + case "running": + err = unpopulate(val, "Running", &n.Running) + delete(rawMsg, key) + case "startTaskFailed": + err = unpopulate(val, "StartTaskFailed", &n.StartTaskFailed) + delete(rawMsg, key) + case "starting": + err = unpopulate(val, "Starting", &n.Starting) + delete(rawMsg, key) + case "total": + err = unpopulate(val, "Total", &n.Total) + delete(rawMsg, key) + case "unknown": + err = unpopulate(val, "Unknown", &n.Unknown) + delete(rawMsg, key) + case "unusable": + err = unpopulate(val, "Unusable", &n.Unusable) + delete(rawMsg, key) + case "upgradingOS": + err = unpopulate(val, "UpgradingOS", &n.UpgradingOS) + delete(rawMsg, key) + case "waitingForStartTask": + err = unpopulate(val, "WaitingForStartTask", &n.WaitingForStartTask) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type NodeEndpointConfiguration. +func (n NodeEndpointConfiguration) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "inboundEndpoints", n.InboundEndpoints) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type NodeEndpointConfiguration. +func (n *NodeEndpointConfiguration) 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", n, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "inboundEndpoints": + err = unpopulate(val, "InboundEndpoints", &n.InboundEndpoints) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type NodeError. +func (n NodeError) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "code", n.Code) + populate(objectMap, "errorDetails", n.ErrorDetails) + populate(objectMap, "message", n.Message) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type NodeError. +func (n *NodeError) 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", n, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "code": + err = unpopulate(val, "Code", &n.Code) + delete(rawMsg, key) + case "errorDetails": + err = unpopulate(val, "ErrorDetails", &n.ErrorDetails) + delete(rawMsg, key) + case "message": + err = unpopulate(val, "Message", &n.Message) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type NodeFile. +func (n NodeFile) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "isDirectory", n.IsDirectory) + populate(objectMap, "name", n.Name) + populate(objectMap, "properties", n.Properties) + populate(objectMap, "url", n.URL) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type NodeFile. +func (n *NodeFile) 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", n, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "isDirectory": + err = unpopulate(val, "IsDirectory", &n.IsDirectory) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &n.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &n.Properties) + delete(rawMsg, key) + case "url": + err = unpopulate(val, "URL", &n.URL) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type NodeFileListResult. +func (n NodeFileListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "odata.nextLink", n.NextLink) + populate(objectMap, "value", n.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type NodeFileListResult. +func (n *NodeFileListResult) 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", n, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "odata.nextLink": + err = unpopulate(val, "NextLink", &n.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &n.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type NodeIdentityReference. +func (n NodeIdentityReference) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "resourceId", n.ResourceID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type NodeIdentityReference. +func (n *NodeIdentityReference) 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", n, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "resourceId": + err = unpopulate(val, "ResourceID", &n.ResourceID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type NodeInfo. +func (n NodeInfo) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "affinityId", n.AffinityID) + populate(objectMap, "nodeId", n.NodeID) + populate(objectMap, "nodeUrl", n.NodeURL) + populate(objectMap, "poolId", n.PoolID) + populate(objectMap, "taskRootDirectory", n.TaskRootDirectory) + populate(objectMap, "taskRootDirectoryUrl", n.TaskRootDirectoryURL) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type NodeInfo. +func (n *NodeInfo) 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", n, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "affinityId": + err = unpopulate(val, "AffinityID", &n.AffinityID) + delete(rawMsg, key) + case "nodeId": + err = unpopulate(val, "NodeID", &n.NodeID) + delete(rawMsg, key) + case "nodeUrl": + err = unpopulate(val, "NodeURL", &n.NodeURL) + delete(rawMsg, key) + case "poolId": + err = unpopulate(val, "PoolID", &n.PoolID) + delete(rawMsg, key) + case "taskRootDirectory": + err = unpopulate(val, "TaskRootDirectory", &n.TaskRootDirectory) + delete(rawMsg, key) + case "taskRootDirectoryUrl": + err = unpopulate(val, "TaskRootDirectoryURL", &n.TaskRootDirectoryURL) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type NodeListResult. +func (n NodeListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "odata.nextLink", n.NextLink) + populate(objectMap, "value", n.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type NodeListResult. +func (n *NodeListResult) 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", n, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "odata.nextLink": + err = unpopulate(val, "NextLink", &n.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &n.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type NodePlacementConfiguration. +func (n NodePlacementConfiguration) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "policy", n.Policy) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type NodePlacementConfiguration. +func (n *NodePlacementConfiguration) 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", n, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "policy": + err = unpopulate(val, "Policy", &n.Policy) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type NodeRemoteLoginSettings. +func (n NodeRemoteLoginSettings) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "remoteLoginIPAddress", n.RemoteLoginIPAddress) + populate(objectMap, "remoteLoginPort", n.RemoteLoginPort) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type NodeRemoteLoginSettings. +func (n *NodeRemoteLoginSettings) 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", n, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "remoteLoginIPAddress": + err = unpopulate(val, "RemoteLoginIPAddress", &n.RemoteLoginIPAddress) + delete(rawMsg, key) + case "remoteLoginPort": + err = unpopulate(val, "RemoteLoginPort", &n.RemoteLoginPort) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type NodeVMExtension. +func (n NodeVMExtension) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "instanceView", n.InstanceView) + populate(objectMap, "provisioningState", n.ProvisioningState) + populate(objectMap, "vmExtension", n.VMExtension) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type NodeVMExtension. +func (n *NodeVMExtension) 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", n, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "instanceView": + err = unpopulate(val, "InstanceView", &n.InstanceView) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &n.ProvisioningState) + delete(rawMsg, key) + case "vmExtension": + err = unpopulate(val, "VMExtension", &n.VMExtension) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type NodeVMExtensionListResult. +func (n NodeVMExtensionListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "odata.nextLink", n.NextLink) + populate(objectMap, "value", n.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type NodeVMExtensionListResult. +func (n *NodeVMExtensionListResult) 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", n, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "odata.nextLink": + err = unpopulate(val, "NextLink", &n.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &n.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type OSDisk. +func (o OSDisk) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "caching", o.Caching) + populate(objectMap, "diskSizeGB", o.DiskSizeGB) + populate(objectMap, "ephemeralOSDiskSettings", o.EphemeralOSDiskSettings) + populate(objectMap, "managedDisk", o.ManagedDisk) + populate(objectMap, "writeAcceleratorEnabled", o.WriteAcceleratorEnabled) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OSDisk. +func (o *OSDisk) 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 "caching": + err = unpopulate(val, "Caching", &o.Caching) + delete(rawMsg, key) + case "diskSizeGB": + err = unpopulate(val, "DiskSizeGB", &o.DiskSizeGB) + delete(rawMsg, key) + case "ephemeralOSDiskSettings": + err = unpopulate(val, "EphemeralOSDiskSettings", &o.EphemeralOSDiskSettings) + delete(rawMsg, key) + case "managedDisk": + err = unpopulate(val, "ManagedDisk", &o.ManagedDisk) + delete(rawMsg, key) + case "writeAcceleratorEnabled": + err = unpopulate(val, "WriteAcceleratorEnabled", &o.WriteAcceleratorEnabled) + 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 OutputFile. +func (o OutputFile) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "destination", o.Destination) + populate(objectMap, "filePattern", o.FilePattern) + populate(objectMap, "uploadOptions", o.UploadOptions) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OutputFile. +func (o *OutputFile) 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 "destination": + err = unpopulate(val, "Destination", &o.Destination) + delete(rawMsg, key) + case "filePattern": + err = unpopulate(val, "FilePattern", &o.FilePattern) + delete(rawMsg, key) + case "uploadOptions": + err = unpopulate(val, "UploadOptions", &o.UploadOptions) + 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 OutputFileBlobContainerDestination. +func (o OutputFileBlobContainerDestination) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "containerUrl", o.ContainerURL) + populate(objectMap, "identityReference", o.IdentityReference) + populate(objectMap, "path", o.Path) + populate(objectMap, "uploadHeaders", o.UploadHeaders) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OutputFileBlobContainerDestination. +func (o *OutputFileBlobContainerDestination) 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 "containerUrl": + err = unpopulate(val, "ContainerURL", &o.ContainerURL) + delete(rawMsg, key) + case "identityReference": + err = unpopulate(val, "IdentityReference", &o.IdentityReference) + delete(rawMsg, key) + case "path": + err = unpopulate(val, "Path", &o.Path) + delete(rawMsg, key) + case "uploadHeaders": + err = unpopulate(val, "UploadHeaders", &o.UploadHeaders) + 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 OutputFileDestination. +func (o OutputFileDestination) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "container", o.Container) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OutputFileDestination. +func (o *OutputFileDestination) 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 "container": + err = unpopulate(val, "Container", &o.Container) + 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 OutputFileUploadConfig. +func (o OutputFileUploadConfig) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "uploadCondition", o.UploadCondition) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OutputFileUploadConfig. +func (o *OutputFileUploadConfig) 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 "uploadCondition": + err = unpopulate(val, "UploadCondition", &o.UploadCondition) + 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 Pool. +func (p Pool) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "allocationState", p.AllocationState) + populateDateTimeRFC3339(objectMap, "allocationStateTransitionTime", p.AllocationStateTransitionTime) + populate(objectMap, "applicationPackageReferences", p.ApplicationPackageReferences) + populate(objectMap, "autoScaleEvaluationInterval", p.AutoScaleEvaluationInterval) + populate(objectMap, "autoScaleFormula", p.AutoScaleFormula) + populate(objectMap, "autoScaleRun", p.AutoScaleRun) + populate(objectMap, "certificateReferences", p.CertificateReferences) + populateDateTimeRFC3339(objectMap, "creationTime", p.CreationTime) + populate(objectMap, "currentDedicatedNodes", p.CurrentDedicatedNodes) + populate(objectMap, "currentLowPriorityNodes", p.CurrentLowPriorityNodes) + populate(objectMap, "currentNodeCommunicationMode", p.CurrentNodeCommunicationMode) + populate(objectMap, "displayName", p.DisplayName) + populate(objectMap, "eTag", p.ETag) + populate(objectMap, "enableAutoScale", p.EnableAutoScale) + populate(objectMap, "enableInterNodeCommunication", p.EnableInterNodeCommunication) + populate(objectMap, "id", p.ID) + populate(objectMap, "identity", p.Identity) + populateDateTimeRFC3339(objectMap, "lastModified", p.LastModified) + populate(objectMap, "metadata", p.Metadata) + populate(objectMap, "mountConfiguration", p.MountConfiguration) + populate(objectMap, "networkConfiguration", p.NetworkConfiguration) + populate(objectMap, "resizeErrors", p.ResizeErrors) + populate(objectMap, "resizeTimeout", p.ResizeTimeout) + populate(objectMap, "resourceTags", p.ResourceTags) + populate(objectMap, "startTask", p.StartTask) + populate(objectMap, "state", p.State) + populateDateTimeRFC3339(objectMap, "stateTransitionTime", p.StateTransitionTime) + populate(objectMap, "stats", p.Stats) + populate(objectMap, "targetDedicatedNodes", p.TargetDedicatedNodes) + populate(objectMap, "targetLowPriorityNodes", p.TargetLowPriorityNodes) + populate(objectMap, "targetNodeCommunicationMode", p.TargetNodeCommunicationMode) + populate(objectMap, "taskSchedulingPolicy", p.TaskSchedulingPolicy) + populate(objectMap, "taskSlotsPerNode", p.TaskSlotsPerNode) + populate(objectMap, "url", p.URL) + populate(objectMap, "upgradePolicy", p.UpgradePolicy) + populate(objectMap, "userAccounts", p.UserAccounts) + populate(objectMap, "vmSize", p.VMSize) + populate(objectMap, "virtualMachineConfiguration", p.VirtualMachineConfiguration) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Pool. +func (p *Pool) 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 "allocationState": + err = unpopulate(val, "AllocationState", &p.AllocationState) + delete(rawMsg, key) + case "allocationStateTransitionTime": + err = unpopulateDateTimeRFC3339(val, "AllocationStateTransitionTime", &p.AllocationStateTransitionTime) + delete(rawMsg, key) + case "applicationPackageReferences": + err = unpopulate(val, "ApplicationPackageReferences", &p.ApplicationPackageReferences) + delete(rawMsg, key) + case "autoScaleEvaluationInterval": + err = unpopulate(val, "AutoScaleEvaluationInterval", &p.AutoScaleEvaluationInterval) + delete(rawMsg, key) + case "autoScaleFormula": + err = unpopulate(val, "AutoScaleFormula", &p.AutoScaleFormula) + delete(rawMsg, key) + case "autoScaleRun": + err = unpopulate(val, "AutoScaleRun", &p.AutoScaleRun) + delete(rawMsg, key) + case "certificateReferences": + err = unpopulate(val, "CertificateReferences", &p.CertificateReferences) + delete(rawMsg, key) + case "creationTime": + err = unpopulateDateTimeRFC3339(val, "CreationTime", &p.CreationTime) + delete(rawMsg, key) + case "currentDedicatedNodes": + err = unpopulate(val, "CurrentDedicatedNodes", &p.CurrentDedicatedNodes) + delete(rawMsg, key) + case "currentLowPriorityNodes": + err = unpopulate(val, "CurrentLowPriorityNodes", &p.CurrentLowPriorityNodes) + delete(rawMsg, key) + case "currentNodeCommunicationMode": + err = unpopulate(val, "CurrentNodeCommunicationMode", &p.CurrentNodeCommunicationMode) + delete(rawMsg, key) + case "displayName": + err = unpopulate(val, "DisplayName", &p.DisplayName) + delete(rawMsg, key) + case "eTag": + err = unpopulate(val, "ETag", &p.ETag) + delete(rawMsg, key) + case "enableAutoScale": + err = unpopulate(val, "EnableAutoScale", &p.EnableAutoScale) + delete(rawMsg, key) + case "enableInterNodeCommunication": + err = unpopulate(val, "EnableInterNodeCommunication", &p.EnableInterNodeCommunication) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &p.ID) + delete(rawMsg, key) + case "identity": + err = unpopulate(val, "Identity", &p.Identity) + delete(rawMsg, key) + case "lastModified": + err = unpopulateDateTimeRFC3339(val, "LastModified", &p.LastModified) + delete(rawMsg, key) + case "metadata": + err = unpopulate(val, "Metadata", &p.Metadata) + delete(rawMsg, key) + case "mountConfiguration": + err = unpopulate(val, "MountConfiguration", &p.MountConfiguration) + delete(rawMsg, key) + case "networkConfiguration": + err = unpopulate(val, "NetworkConfiguration", &p.NetworkConfiguration) + delete(rawMsg, key) + case "resizeErrors": + err = unpopulate(val, "ResizeErrors", &p.ResizeErrors) + delete(rawMsg, key) + case "resizeTimeout": + err = unpopulate(val, "ResizeTimeout", &p.ResizeTimeout) + delete(rawMsg, key) + case "resourceTags": + err = unpopulate(val, "ResourceTags", &p.ResourceTags) + delete(rawMsg, key) + case "startTask": + err = unpopulate(val, "StartTask", &p.StartTask) + delete(rawMsg, key) + case "state": + err = unpopulate(val, "State", &p.State) + delete(rawMsg, key) + case "stateTransitionTime": + err = unpopulateDateTimeRFC3339(val, "StateTransitionTime", &p.StateTransitionTime) + delete(rawMsg, key) + case "stats": + err = unpopulate(val, "Stats", &p.Stats) + delete(rawMsg, key) + case "targetDedicatedNodes": + err = unpopulate(val, "TargetDedicatedNodes", &p.TargetDedicatedNodes) + delete(rawMsg, key) + case "targetLowPriorityNodes": + err = unpopulate(val, "TargetLowPriorityNodes", &p.TargetLowPriorityNodes) + delete(rawMsg, key) + case "targetNodeCommunicationMode": + err = unpopulate(val, "TargetNodeCommunicationMode", &p.TargetNodeCommunicationMode) + delete(rawMsg, key) + case "taskSchedulingPolicy": + err = unpopulate(val, "TaskSchedulingPolicy", &p.TaskSchedulingPolicy) + delete(rawMsg, key) + case "taskSlotsPerNode": + err = unpopulate(val, "TaskSlotsPerNode", &p.TaskSlotsPerNode) + delete(rawMsg, key) + case "url": + err = unpopulate(val, "URL", &p.URL) + delete(rawMsg, key) + case "upgradePolicy": + err = unpopulate(val, "UpgradePolicy", &p.UpgradePolicy) + delete(rawMsg, key) + case "userAccounts": + err = unpopulate(val, "UserAccounts", &p.UserAccounts) + delete(rawMsg, key) + case "vmSize": + err = unpopulate(val, "VMSize", &p.VMSize) + delete(rawMsg, key) + case "virtualMachineConfiguration": + err = unpopulate(val, "VirtualMachineConfiguration", &p.VirtualMachineConfiguration) + 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 PoolEndpointConfiguration. +func (p PoolEndpointConfiguration) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "inboundNATPools", p.InboundNATPools) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PoolEndpointConfiguration. +func (p *PoolEndpointConfiguration) 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 "inboundNATPools": + err = unpopulate(val, "InboundNATPools", &p.InboundNATPools) + 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 PoolIdentity. +func (p PoolIdentity) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "type", p.Type) + populate(objectMap, "userAssignedIdentities", p.UserAssignedIdentities) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PoolIdentity. +func (p *PoolIdentity) 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 "type": + err = unpopulate(val, "Type", &p.Type) + delete(rawMsg, key) + case "userAssignedIdentities": + err = unpopulate(val, "UserAssignedIdentities", &p.UserAssignedIdentities) + 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 PoolInfo. +func (p PoolInfo) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "autoPoolSpecification", p.AutoPoolSpecification) + populate(objectMap, "poolId", p.PoolID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PoolInfo. +func (p *PoolInfo) 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 "autoPoolSpecification": + err = unpopulate(val, "AutoPoolSpecification", &p.AutoPoolSpecification) + delete(rawMsg, key) + case "poolId": + err = unpopulate(val, "PoolID", &p.PoolID) + 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 PoolListResult. +func (p PoolListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "odata.nextLink", p.NextLink) + populate(objectMap, "value", p.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PoolListResult. +func (p *PoolListResult) 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 "odata.nextLink": + err = unpopulate(val, "NextLink", &p.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &p.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type PoolNodeCounts. +func (p PoolNodeCounts) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "dedicated", p.Dedicated) + populate(objectMap, "lowPriority", p.LowPriority) + populate(objectMap, "poolId", p.PoolID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PoolNodeCounts. +func (p *PoolNodeCounts) 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 "dedicated": + err = unpopulate(val, "Dedicated", &p.Dedicated) + delete(rawMsg, key) + case "lowPriority": + err = unpopulate(val, "LowPriority", &p.LowPriority) + delete(rawMsg, key) + case "poolId": + err = unpopulate(val, "PoolID", &p.PoolID) + 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 PoolResourceStatistics. +func (p PoolResourceStatistics) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "avgCPUPercentage", p.AvgCPUPercentage) + populate(objectMap, "avgDiskGiB", p.AvgDiskGiB) + populate(objectMap, "avgMemoryGiB", p.AvgMemoryGiB) + populate(objectMap, "diskReadGiB", p.DiskReadGiB) + populate(objectMap, "diskReadIOps", to.Ptr(strconv.FormatInt(*p.DiskReadIOPS, 10))) + populate(objectMap, "diskWriteGiB", p.DiskWriteGiB) + populate(objectMap, "diskWriteIOps", to.Ptr(strconv.FormatInt(*p.DiskWriteIOPS, 10))) + populateDateTimeRFC3339(objectMap, "lastUpdateTime", p.LastUpdateTime) + populate(objectMap, "networkReadGiB", p.NetworkReadGiB) + populate(objectMap, "networkWriteGiB", p.NetworkWriteGiB) + populate(objectMap, "peakDiskGiB", p.PeakDiskGiB) + populate(objectMap, "peakMemoryGiB", p.PeakMemoryGiB) + populateDateTimeRFC3339(objectMap, "startTime", p.StartTime) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PoolResourceStatistics. +func (p *PoolResourceStatistics) 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 "avgCPUPercentage": + err = unpopulate(val, "AvgCPUPercentage", &p.AvgCPUPercentage) + delete(rawMsg, key) + case "avgDiskGiB": + err = unpopulate(val, "AvgDiskGiB", &p.AvgDiskGiB) + delete(rawMsg, key) + case "avgMemoryGiB": + err = unpopulate(val, "AvgMemoryGiB", &p.AvgMemoryGiB) + delete(rawMsg, key) + case "diskReadGiB": + err = unpopulate(val, "DiskReadGiB", &p.DiskReadGiB) + delete(rawMsg, key) + case "diskReadIOps": + var aux string + err = unpopulate(val, "DiskReadIOPS", &aux) + if err == nil { + var v int64 + v, err = strconv.ParseInt(aux, 10, 0) + if err == nil { + p.DiskReadIOPS = to.Ptr(v) + } + } + delete(rawMsg, key) + case "diskWriteGiB": + err = unpopulate(val, "DiskWriteGiB", &p.DiskWriteGiB) + delete(rawMsg, key) + case "diskWriteIOps": + var aux string + err = unpopulate(val, "DiskWriteIOPS", &aux) + if err == nil { + var v int64 + v, err = strconv.ParseInt(aux, 10, 0) + if err == nil { + p.DiskWriteIOPS = to.Ptr(v) + } + } + delete(rawMsg, key) + case "lastUpdateTime": + err = unpopulateDateTimeRFC3339(val, "LastUpdateTime", &p.LastUpdateTime) + delete(rawMsg, key) + case "networkReadGiB": + err = unpopulate(val, "NetworkReadGiB", &p.NetworkReadGiB) + delete(rawMsg, key) + case "networkWriteGiB": + err = unpopulate(val, "NetworkWriteGiB", &p.NetworkWriteGiB) + delete(rawMsg, key) + case "peakDiskGiB": + err = unpopulate(val, "PeakDiskGiB", &p.PeakDiskGiB) + delete(rawMsg, key) + case "peakMemoryGiB": + err = unpopulate(val, "PeakMemoryGiB", &p.PeakMemoryGiB) + delete(rawMsg, key) + case "startTime": + err = unpopulateDateTimeRFC3339(val, "StartTime", &p.StartTime) + 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 PoolSpecification. +func (p PoolSpecification) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "applicationPackageReferences", p.ApplicationPackageReferences) + populate(objectMap, "autoScaleEvaluationInterval", p.AutoScaleEvaluationInterval) + populate(objectMap, "autoScaleFormula", p.AutoScaleFormula) + populate(objectMap, "certificateReferences", p.CertificateReferences) + populate(objectMap, "displayName", p.DisplayName) + populate(objectMap, "enableAutoScale", p.EnableAutoScale) + populate(objectMap, "enableInterNodeCommunication", p.EnableInterNodeCommunication) + populate(objectMap, "metadata", p.Metadata) + populate(objectMap, "mountConfiguration", p.MountConfiguration) + populate(objectMap, "networkConfiguration", p.NetworkConfiguration) + populate(objectMap, "resizeTimeout", p.ResizeTimeout) + populate(objectMap, "resourceTags", p.ResourceTags) + populate(objectMap, "startTask", p.StartTask) + populate(objectMap, "targetDedicatedNodes", p.TargetDedicatedNodes) + populate(objectMap, "targetLowPriorityNodes", p.TargetLowPriorityNodes) + populate(objectMap, "targetNodeCommunicationMode", p.TargetNodeCommunicationMode) + populate(objectMap, "taskSchedulingPolicy", p.TaskSchedulingPolicy) + populate(objectMap, "taskSlotsPerNode", p.TaskSlotsPerNode) + populate(objectMap, "upgradePolicy", p.UpgradePolicy) + populate(objectMap, "userAccounts", p.UserAccounts) + populate(objectMap, "vmSize", p.VMSize) + populate(objectMap, "virtualMachineConfiguration", p.VirtualMachineConfiguration) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PoolSpecification. +func (p *PoolSpecification) 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 "applicationPackageReferences": + err = unpopulate(val, "ApplicationPackageReferences", &p.ApplicationPackageReferences) + delete(rawMsg, key) + case "autoScaleEvaluationInterval": + err = unpopulate(val, "AutoScaleEvaluationInterval", &p.AutoScaleEvaluationInterval) + delete(rawMsg, key) + case "autoScaleFormula": + err = unpopulate(val, "AutoScaleFormula", &p.AutoScaleFormula) + delete(rawMsg, key) + case "certificateReferences": + err = unpopulate(val, "CertificateReferences", &p.CertificateReferences) + delete(rawMsg, key) + case "displayName": + err = unpopulate(val, "DisplayName", &p.DisplayName) + delete(rawMsg, key) + case "enableAutoScale": + err = unpopulate(val, "EnableAutoScale", &p.EnableAutoScale) + delete(rawMsg, key) + case "enableInterNodeCommunication": + err = unpopulate(val, "EnableInterNodeCommunication", &p.EnableInterNodeCommunication) + delete(rawMsg, key) + case "metadata": + err = unpopulate(val, "Metadata", &p.Metadata) + delete(rawMsg, key) + case "mountConfiguration": + err = unpopulate(val, "MountConfiguration", &p.MountConfiguration) + delete(rawMsg, key) + case "networkConfiguration": + err = unpopulate(val, "NetworkConfiguration", &p.NetworkConfiguration) + delete(rawMsg, key) + case "resizeTimeout": + err = unpopulate(val, "ResizeTimeout", &p.ResizeTimeout) + delete(rawMsg, key) + case "resourceTags": + err = unpopulate(val, "ResourceTags", &p.ResourceTags) + delete(rawMsg, key) + case "startTask": + err = unpopulate(val, "StartTask", &p.StartTask) + delete(rawMsg, key) + case "targetDedicatedNodes": + err = unpopulate(val, "TargetDedicatedNodes", &p.TargetDedicatedNodes) + delete(rawMsg, key) + case "targetLowPriorityNodes": + err = unpopulate(val, "TargetLowPriorityNodes", &p.TargetLowPriorityNodes) + delete(rawMsg, key) + case "targetNodeCommunicationMode": + err = unpopulate(val, "TargetNodeCommunicationMode", &p.TargetNodeCommunicationMode) + delete(rawMsg, key) + case "taskSchedulingPolicy": + err = unpopulate(val, "TaskSchedulingPolicy", &p.TaskSchedulingPolicy) + delete(rawMsg, key) + case "taskSlotsPerNode": + err = unpopulate(val, "TaskSlotsPerNode", &p.TaskSlotsPerNode) + delete(rawMsg, key) + case "upgradePolicy": + err = unpopulate(val, "UpgradePolicy", &p.UpgradePolicy) + delete(rawMsg, key) + case "userAccounts": + err = unpopulate(val, "UserAccounts", &p.UserAccounts) + delete(rawMsg, key) + case "vmSize": + err = unpopulate(val, "VMSize", &p.VMSize) + delete(rawMsg, key) + case "virtualMachineConfiguration": + err = unpopulate(val, "VirtualMachineConfiguration", &p.VirtualMachineConfiguration) + 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 PoolStatistics. +func (p PoolStatistics) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateDateTimeRFC3339(objectMap, "lastUpdateTime", p.LastUpdateTime) + populate(objectMap, "resourceStats", p.ResourceStats) + populateDateTimeRFC3339(objectMap, "startTime", p.StartTime) + populate(objectMap, "url", p.URL) + populate(objectMap, "usageStats", p.UsageStats) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PoolStatistics. +func (p *PoolStatistics) 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 "lastUpdateTime": + err = unpopulateDateTimeRFC3339(val, "LastUpdateTime", &p.LastUpdateTime) + delete(rawMsg, key) + case "resourceStats": + err = unpopulate(val, "ResourceStats", &p.ResourceStats) + delete(rawMsg, key) + case "startTime": + err = unpopulateDateTimeRFC3339(val, "StartTime", &p.StartTime) + delete(rawMsg, key) + case "url": + err = unpopulate(val, "URL", &p.URL) + delete(rawMsg, key) + case "usageStats": + err = unpopulate(val, "UsageStats", &p.UsageStats) + 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 PoolUsageStatistics. +func (p PoolUsageStatistics) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "dedicatedCoreTime", p.DedicatedCoreTime) + populateDateTimeRFC3339(objectMap, "lastUpdateTime", p.LastUpdateTime) + populateDateTimeRFC3339(objectMap, "startTime", p.StartTime) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PoolUsageStatistics. +func (p *PoolUsageStatistics) 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 "dedicatedCoreTime": + err = unpopulate(val, "DedicatedCoreTime", &p.DedicatedCoreTime) + delete(rawMsg, key) + case "lastUpdateTime": + err = unpopulateDateTimeRFC3339(val, "LastUpdateTime", &p.LastUpdateTime) + delete(rawMsg, key) + case "startTime": + err = unpopulateDateTimeRFC3339(val, "StartTime", &p.StartTime) + 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 PublicIPAddressConfiguration. +func (p PublicIPAddressConfiguration) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "ipAddressIds", p.IPAddressIDs) + populate(objectMap, "provision", p.IPAddressProvisioningType) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PublicIPAddressConfiguration. +func (p *PublicIPAddressConfiguration) 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 "ipAddressIds": + err = unpopulate(val, "IPAddressIDs", &p.IPAddressIDs) + delete(rawMsg, key) + case "provision": + err = unpopulate(val, "IPAddressProvisioningType", &p.IPAddressProvisioningType) + 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 RebootNodeContent. +func (r RebootNodeContent) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nodeRebootOption", r.NodeRebootOption) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RebootNodeContent. +func (r *RebootNodeContent) 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 "nodeRebootOption": + err = unpopulate(val, "NodeRebootOption", &r.NodeRebootOption) + 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 RecentJob. +func (r RecentJob) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", r.ID) + populate(objectMap, "url", r.URL) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RecentJob. +func (r *RecentJob) 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 "url": + err = unpopulate(val, "URL", &r.URL) + 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 ReimageNodeContent. +func (r ReimageNodeContent) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nodeReimageOption", r.NodeReimageOption) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ReimageNodeContent. +func (r *ReimageNodeContent) 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 "nodeReimageOption": + err = unpopulate(val, "NodeReimageOption", &r.NodeReimageOption) + 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 RemoveNodeContent. +func (r RemoveNodeContent) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nodeDeallocationOption", r.NodeDeallocationOption) + populate(objectMap, "nodeList", r.NodeList) + populate(objectMap, "resizeTimeout", r.ResizeTimeout) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RemoveNodeContent. +func (r *RemoveNodeContent) 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 "nodeDeallocationOption": + err = unpopulate(val, "NodeDeallocationOption", &r.NodeDeallocationOption) + delete(rawMsg, key) + case "nodeList": + err = unpopulate(val, "NodeList", &r.NodeList) + delete(rawMsg, key) + case "resizeTimeout": + err = unpopulate(val, "ResizeTimeout", &r.ResizeTimeout) + 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 ReplacePoolContent. +func (r ReplacePoolContent) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "applicationPackageReferences", r.ApplicationPackageReferences) + populate(objectMap, "certificateReferences", r.CertificateReferences) + populate(objectMap, "metadata", r.Metadata) + populate(objectMap, "startTask", r.StartTask) + populate(objectMap, "targetNodeCommunicationMode", r.TargetNodeCommunicationMode) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ReplacePoolContent. +func (r *ReplacePoolContent) 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 "applicationPackageReferences": + err = unpopulate(val, "ApplicationPackageReferences", &r.ApplicationPackageReferences) + delete(rawMsg, key) + case "certificateReferences": + err = unpopulate(val, "CertificateReferences", &r.CertificateReferences) + delete(rawMsg, key) + case "metadata": + err = unpopulate(val, "Metadata", &r.Metadata) + delete(rawMsg, key) + case "startTask": + err = unpopulate(val, "StartTask", &r.StartTask) + delete(rawMsg, key) + case "targetNodeCommunicationMode": + err = unpopulate(val, "TargetNodeCommunicationMode", &r.TargetNodeCommunicationMode) + 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 ResizeError. +func (r ResizeError) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "code", r.Code) + populate(objectMap, "message", r.Message) + populate(objectMap, "values", r.Values) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ResizeError. +func (r *ResizeError) 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 "code": + err = unpopulate(val, "Code", &r.Code) + delete(rawMsg, key) + case "message": + err = unpopulate(val, "Message", &r.Message) + delete(rawMsg, key) + case "values": + err = unpopulate(val, "Values", &r.Values) + 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 ResizePoolContent. +func (r ResizePoolContent) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nodeDeallocationOption", r.NodeDeallocationOption) + populate(objectMap, "resizeTimeout", r.ResizeTimeout) + populate(objectMap, "targetDedicatedNodes", r.TargetDedicatedNodes) + populate(objectMap, "targetLowPriorityNodes", r.TargetLowPriorityNodes) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ResizePoolContent. +func (r *ResizePoolContent) 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 "nodeDeallocationOption": + err = unpopulate(val, "NodeDeallocationOption", &r.NodeDeallocationOption) + delete(rawMsg, key) + case "resizeTimeout": + err = unpopulate(val, "ResizeTimeout", &r.ResizeTimeout) + delete(rawMsg, key) + case "targetDedicatedNodes": + err = unpopulate(val, "TargetDedicatedNodes", &r.TargetDedicatedNodes) + delete(rawMsg, key) + case "targetLowPriorityNodes": + err = unpopulate(val, "TargetLowPriorityNodes", &r.TargetLowPriorityNodes) + 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 ResourceFile. +func (r ResourceFile) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "autoStorageContainerName", r.AutoStorageContainerName) + populate(objectMap, "blobPrefix", r.BlobPrefix) + populate(objectMap, "fileMode", r.FileMode) + populate(objectMap, "filePath", r.FilePath) + populate(objectMap, "httpUrl", r.HTTPURL) + populate(objectMap, "identityReference", r.IdentityReference) + populate(objectMap, "storageContainerUrl", r.StorageContainerURL) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ResourceFile. +func (r *ResourceFile) 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 "autoStorageContainerName": + err = unpopulate(val, "AutoStorageContainerName", &r.AutoStorageContainerName) + delete(rawMsg, key) + case "blobPrefix": + err = unpopulate(val, "BlobPrefix", &r.BlobPrefix) + delete(rawMsg, key) + case "fileMode": + err = unpopulate(val, "FileMode", &r.FileMode) + delete(rawMsg, key) + case "filePath": + err = unpopulate(val, "FilePath", &r.FilePath) + delete(rawMsg, key) + case "httpUrl": + err = unpopulate(val, "HTTPURL", &r.HTTPURL) + delete(rawMsg, key) + case "identityReference": + err = unpopulate(val, "IdentityReference", &r.IdentityReference) + delete(rawMsg, key) + case "storageContainerUrl": + err = unpopulate(val, "StorageContainerURL", &r.StorageContainerURL) + 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 RollingUpgradePolicy. +func (r RollingUpgradePolicy) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "enableCrossZoneUpgrade", r.EnableCrossZoneUpgrade) + populate(objectMap, "maxBatchInstancePercent", r.MaxBatchInstancePercent) + populate(objectMap, "maxUnhealthyInstancePercent", r.MaxUnhealthyInstancePercent) + populate(objectMap, "maxUnhealthyUpgradedInstancePercent", r.MaxUnhealthyUpgradedInstancePercent) + populate(objectMap, "pauseTimeBetweenBatches", r.PauseTimeBetweenBatches) + populate(objectMap, "prioritizeUnhealthyInstances", r.PrioritizeUnhealthyInstances) + populate(objectMap, "rollbackFailedInstancesOnPolicyBreach", r.RollbackFailedInstancesOnPolicyBreach) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RollingUpgradePolicy. +func (r *RollingUpgradePolicy) 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 "enableCrossZoneUpgrade": + err = unpopulate(val, "EnableCrossZoneUpgrade", &r.EnableCrossZoneUpgrade) + delete(rawMsg, key) + case "maxBatchInstancePercent": + err = unpopulate(val, "MaxBatchInstancePercent", &r.MaxBatchInstancePercent) + delete(rawMsg, key) + case "maxUnhealthyInstancePercent": + err = unpopulate(val, "MaxUnhealthyInstancePercent", &r.MaxUnhealthyInstancePercent) + delete(rawMsg, key) + case "maxUnhealthyUpgradedInstancePercent": + err = unpopulate(val, "MaxUnhealthyUpgradedInstancePercent", &r.MaxUnhealthyUpgradedInstancePercent) + delete(rawMsg, key) + case "pauseTimeBetweenBatches": + err = unpopulate(val, "PauseTimeBetweenBatches", &r.PauseTimeBetweenBatches) + delete(rawMsg, key) + case "prioritizeUnhealthyInstances": + err = unpopulate(val, "PrioritizeUnhealthyInstances", &r.PrioritizeUnhealthyInstances) + delete(rawMsg, key) + case "rollbackFailedInstancesOnPolicyBreach": + err = unpopulate(val, "RollbackFailedInstancesOnPolicyBreach", &r.RollbackFailedInstancesOnPolicyBreach) + 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 SecurityProfile. +func (s SecurityProfile) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "encryptionAtHost", s.EncryptionAtHost) + populate(objectMap, "securityType", s.SecurityType) + populate(objectMap, "uefiSettings", s.UefiSettings) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SecurityProfile. +func (s *SecurityProfile) 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 "encryptionAtHost": + err = unpopulate(val, "EncryptionAtHost", &s.EncryptionAtHost) + delete(rawMsg, key) + case "securityType": + err = unpopulate(val, "SecurityType", &s.SecurityType) + delete(rawMsg, key) + case "uefiSettings": + err = unpopulate(val, "UefiSettings", &s.UefiSettings) + 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 ServiceArtifactReference. +func (s ServiceArtifactReference) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", s.ID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ServiceArtifactReference. +func (s *ServiceArtifactReference) 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) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type StartTask. +func (s StartTask) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "commandLine", s.CommandLine) + populate(objectMap, "containerSettings", s.ContainerSettings) + populate(objectMap, "environmentSettings", s.EnvironmentSettings) + populate(objectMap, "maxTaskRetryCount", s.MaxTaskRetryCount) + populate(objectMap, "resourceFiles", s.ResourceFiles) + populate(objectMap, "userIdentity", s.UserIdentity) + populate(objectMap, "waitForSuccess", s.WaitForSuccess) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type StartTask. +func (s *StartTask) 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 "commandLine": + err = unpopulate(val, "CommandLine", &s.CommandLine) + delete(rawMsg, key) + case "containerSettings": + err = unpopulate(val, "ContainerSettings", &s.ContainerSettings) + delete(rawMsg, key) + case "environmentSettings": + err = unpopulate(val, "EnvironmentSettings", &s.EnvironmentSettings) + delete(rawMsg, key) + case "maxTaskRetryCount": + err = unpopulate(val, "MaxTaskRetryCount", &s.MaxTaskRetryCount) + delete(rawMsg, key) + case "resourceFiles": + err = unpopulate(val, "ResourceFiles", &s.ResourceFiles) + delete(rawMsg, key) + case "userIdentity": + err = unpopulate(val, "UserIdentity", &s.UserIdentity) + delete(rawMsg, key) + case "waitForSuccess": + err = unpopulate(val, "WaitForSuccess", &s.WaitForSuccess) + 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 StartTaskInfo. +func (s StartTaskInfo) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "containerInfo", s.ContainerInfo) + populateDateTimeRFC3339(objectMap, "endTime", s.EndTime) + populate(objectMap, "exitCode", s.ExitCode) + populate(objectMap, "failureInfo", s.FailureInfo) + populateDateTimeRFC3339(objectMap, "lastRetryTime", s.LastRetryTime) + populate(objectMap, "result", s.Result) + populate(objectMap, "retryCount", s.RetryCount) + populateDateTimeRFC3339(objectMap, "startTime", s.StartTime) + populate(objectMap, "state", s.State) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type StartTaskInfo. +func (s *StartTaskInfo) 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 "containerInfo": + err = unpopulate(val, "ContainerInfo", &s.ContainerInfo) + delete(rawMsg, key) + case "endTime": + err = unpopulateDateTimeRFC3339(val, "EndTime", &s.EndTime) + delete(rawMsg, key) + case "exitCode": + err = unpopulate(val, "ExitCode", &s.ExitCode) + delete(rawMsg, key) + case "failureInfo": + err = unpopulate(val, "FailureInfo", &s.FailureInfo) + delete(rawMsg, key) + case "lastRetryTime": + err = unpopulateDateTimeRFC3339(val, "LastRetryTime", &s.LastRetryTime) + delete(rawMsg, key) + case "result": + err = unpopulate(val, "Result", &s.Result) + delete(rawMsg, key) + case "retryCount": + err = unpopulate(val, "RetryCount", &s.RetryCount) + delete(rawMsg, key) + case "startTime": + err = unpopulateDateTimeRFC3339(val, "StartTime", &s.StartTime) + delete(rawMsg, key) + case "state": + err = unpopulate(val, "State", &s.State) + 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 Subtask. +func (s Subtask) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "containerInfo", s.ContainerInfo) + populateDateTimeRFC3339(objectMap, "endTime", s.EndTime) + populate(objectMap, "exitCode", s.ExitCode) + populate(objectMap, "failureInfo", s.FailureInfo) + populate(objectMap, "id", s.ID) + populate(objectMap, "nodeInfo", s.NodeInfo) + populate(objectMap, "previousState", s.PreviousState) + populateDateTimeRFC3339(objectMap, "previousStateTransitionTime", s.PreviousStateTransitionTime) + populate(objectMap, "result", s.Result) + populateDateTimeRFC3339(objectMap, "startTime", s.StartTime) + populate(objectMap, "state", s.State) + populateDateTimeRFC3339(objectMap, "stateTransitionTime", s.StateTransitionTime) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Subtask. +func (s *Subtask) 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 "containerInfo": + err = unpopulate(val, "ContainerInfo", &s.ContainerInfo) + delete(rawMsg, key) + case "endTime": + err = unpopulateDateTimeRFC3339(val, "EndTime", &s.EndTime) + delete(rawMsg, key) + case "exitCode": + err = unpopulate(val, "ExitCode", &s.ExitCode) + delete(rawMsg, key) + case "failureInfo": + err = unpopulate(val, "FailureInfo", &s.FailureInfo) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &s.ID) + delete(rawMsg, key) + case "nodeInfo": + err = unpopulate(val, "NodeInfo", &s.NodeInfo) + delete(rawMsg, key) + case "previousState": + err = unpopulate(val, "PreviousState", &s.PreviousState) + delete(rawMsg, key) + case "previousStateTransitionTime": + err = unpopulateDateTimeRFC3339(val, "PreviousStateTransitionTime", &s.PreviousStateTransitionTime) + delete(rawMsg, key) + case "result": + err = unpopulate(val, "Result", &s.Result) + delete(rawMsg, key) + case "startTime": + err = unpopulateDateTimeRFC3339(val, "StartTime", &s.StartTime) + delete(rawMsg, key) + case "state": + err = unpopulate(val, "State", &s.State) + delete(rawMsg, key) + case "stateTransitionTime": + err = unpopulateDateTimeRFC3339(val, "StateTransitionTime", &s.StateTransitionTime) + 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 SupportedImage. +func (s SupportedImage) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateDateTimeRFC3339(objectMap, "batchSupportEndOfLife", s.BatchSupportEndOfLife) + populate(objectMap, "capabilities", s.Capabilities) + populate(objectMap, "imageReference", s.ImageReference) + populate(objectMap, "nodeAgentSKUId", s.NodeAgentSKUID) + populate(objectMap, "osType", s.OSType) + populate(objectMap, "verificationType", s.VerificationType) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SupportedImage. +func (s *SupportedImage) 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 "batchSupportEndOfLife": + err = unpopulateDateTimeRFC3339(val, "BatchSupportEndOfLife", &s.BatchSupportEndOfLife) + delete(rawMsg, key) + case "capabilities": + err = unpopulate(val, "Capabilities", &s.Capabilities) + delete(rawMsg, key) + case "imageReference": + err = unpopulate(val, "ImageReference", &s.ImageReference) + delete(rawMsg, key) + case "nodeAgentSKUId": + err = unpopulate(val, "NodeAgentSKUID", &s.NodeAgentSKUID) + delete(rawMsg, key) + case "osType": + err = unpopulate(val, "OSType", &s.OSType) + delete(rawMsg, key) + case "verificationType": + err = unpopulate(val, "VerificationType", &s.VerificationType) + 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 Task. +func (t Task) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "affinityInfo", t.AffinityInfo) + populate(objectMap, "applicationPackageReferences", t.ApplicationPackageReferences) + populate(objectMap, "authenticationTokenSettings", t.AuthenticationTokenSettings) + populate(objectMap, "commandLine", t.CommandLine) + populate(objectMap, "constraints", t.Constraints) + populate(objectMap, "containerSettings", t.ContainerSettings) + populateDateTimeRFC3339(objectMap, "creationTime", t.CreationTime) + populate(objectMap, "dependsOn", t.DependsOn) + populate(objectMap, "displayName", t.DisplayName) + populate(objectMap, "eTag", t.ETag) + populate(objectMap, "environmentSettings", t.EnvironmentSettings) + populate(objectMap, "executionInfo", t.ExecutionInfo) + populate(objectMap, "exitConditions", t.ExitConditions) + populate(objectMap, "id", t.ID) + populateDateTimeRFC3339(objectMap, "lastModified", t.LastModified) + populate(objectMap, "multiInstanceSettings", t.MultiInstanceSettings) + populate(objectMap, "nodeInfo", t.NodeInfo) + populate(objectMap, "outputFiles", t.OutputFiles) + populate(objectMap, "previousState", t.PreviousState) + populateDateTimeRFC3339(objectMap, "previousStateTransitionTime", t.PreviousStateTransitionTime) + populate(objectMap, "requiredSlots", t.RequiredSlots) + populate(objectMap, "resourceFiles", t.ResourceFiles) + populate(objectMap, "state", t.State) + populateDateTimeRFC3339(objectMap, "stateTransitionTime", t.StateTransitionTime) + populate(objectMap, "stats", t.Stats) + populate(objectMap, "url", t.URL) + populate(objectMap, "userIdentity", t.UserIdentity) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Task. +func (t *Task) 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 "affinityInfo": + err = unpopulate(val, "AffinityInfo", &t.AffinityInfo) + delete(rawMsg, key) + case "applicationPackageReferences": + err = unpopulate(val, "ApplicationPackageReferences", &t.ApplicationPackageReferences) + delete(rawMsg, key) + case "authenticationTokenSettings": + err = unpopulate(val, "AuthenticationTokenSettings", &t.AuthenticationTokenSettings) + delete(rawMsg, key) + case "commandLine": + err = unpopulate(val, "CommandLine", &t.CommandLine) + delete(rawMsg, key) + case "constraints": + err = unpopulate(val, "Constraints", &t.Constraints) + delete(rawMsg, key) + case "containerSettings": + err = unpopulate(val, "ContainerSettings", &t.ContainerSettings) + delete(rawMsg, key) + case "creationTime": + err = unpopulateDateTimeRFC3339(val, "CreationTime", &t.CreationTime) + delete(rawMsg, key) + case "dependsOn": + err = unpopulate(val, "DependsOn", &t.DependsOn) + delete(rawMsg, key) + case "displayName": + err = unpopulate(val, "DisplayName", &t.DisplayName) + delete(rawMsg, key) + case "eTag": + err = unpopulate(val, "ETag", &t.ETag) + delete(rawMsg, key) + case "environmentSettings": + err = unpopulate(val, "EnvironmentSettings", &t.EnvironmentSettings) + delete(rawMsg, key) + case "executionInfo": + err = unpopulate(val, "ExecutionInfo", &t.ExecutionInfo) + delete(rawMsg, key) + case "exitConditions": + err = unpopulate(val, "ExitConditions", &t.ExitConditions) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &t.ID) + delete(rawMsg, key) + case "lastModified": + err = unpopulateDateTimeRFC3339(val, "LastModified", &t.LastModified) + delete(rawMsg, key) + case "multiInstanceSettings": + err = unpopulate(val, "MultiInstanceSettings", &t.MultiInstanceSettings) + delete(rawMsg, key) + case "nodeInfo": + err = unpopulate(val, "NodeInfo", &t.NodeInfo) + delete(rawMsg, key) + case "outputFiles": + err = unpopulate(val, "OutputFiles", &t.OutputFiles) + delete(rawMsg, key) + case "previousState": + err = unpopulate(val, "PreviousState", &t.PreviousState) + delete(rawMsg, key) + case "previousStateTransitionTime": + err = unpopulateDateTimeRFC3339(val, "PreviousStateTransitionTime", &t.PreviousStateTransitionTime) + delete(rawMsg, key) + case "requiredSlots": + err = unpopulate(val, "RequiredSlots", &t.RequiredSlots) + delete(rawMsg, key) + case "resourceFiles": + err = unpopulate(val, "ResourceFiles", &t.ResourceFiles) + delete(rawMsg, key) + case "state": + err = unpopulate(val, "State", &t.State) + delete(rawMsg, key) + case "stateTransitionTime": + err = unpopulateDateTimeRFC3339(val, "StateTransitionTime", &t.StateTransitionTime) + delete(rawMsg, key) + case "stats": + err = unpopulate(val, "Stats", &t.Stats) + delete(rawMsg, key) + case "url": + err = unpopulate(val, "URL", &t.URL) + delete(rawMsg, key) + case "userIdentity": + err = unpopulate(val, "UserIdentity", &t.UserIdentity) + 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 TaskAddResult. +func (t TaskAddResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "eTag", t.ETag) + populate(objectMap, "error", t.Error) + populateDateTimeRFC3339(objectMap, "lastModified", t.LastModified) + populate(objectMap, "location", t.Location) + populate(objectMap, "status", t.Status) + populate(objectMap, "taskId", t.TaskID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type TaskAddResult. +func (t *TaskAddResult) 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 "eTag": + err = unpopulate(val, "ETag", &t.ETag) + delete(rawMsg, key) + case "error": + err = unpopulate(val, "Error", &t.Error) + delete(rawMsg, key) + case "lastModified": + err = unpopulateDateTimeRFC3339(val, "LastModified", &t.LastModified) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &t.Location) + delete(rawMsg, key) + case "status": + err = unpopulate(val, "Status", &t.Status) + delete(rawMsg, key) + case "taskId": + err = unpopulate(val, "TaskID", &t.TaskID) + 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 TaskConstraints. +func (t TaskConstraints) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "maxTaskRetryCount", t.MaxTaskRetryCount) + populate(objectMap, "maxWallClockTime", t.MaxWallClockTime) + populate(objectMap, "retentionTime", t.RetentionTime) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type TaskConstraints. +func (t *TaskConstraints) 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 "maxTaskRetryCount": + err = unpopulate(val, "MaxTaskRetryCount", &t.MaxTaskRetryCount) + delete(rawMsg, key) + case "maxWallClockTime": + err = unpopulate(val, "MaxWallClockTime", &t.MaxWallClockTime) + delete(rawMsg, key) + case "retentionTime": + err = unpopulate(val, "RetentionTime", &t.RetentionTime) + 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 TaskContainerExecutionInfo. +func (t TaskContainerExecutionInfo) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "containerId", t.ContainerID) + populate(objectMap, "error", t.Error) + populate(objectMap, "state", t.State) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type TaskContainerExecutionInfo. +func (t *TaskContainerExecutionInfo) 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 "containerId": + err = unpopulate(val, "ContainerID", &t.ContainerID) + delete(rawMsg, key) + case "error": + err = unpopulate(val, "Error", &t.Error) + delete(rawMsg, key) + case "state": + err = unpopulate(val, "State", &t.State) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type TaskContainerSettings. +func (t TaskContainerSettings) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "containerHostBatchBindMounts", t.ContainerHostBatchBindMounts) + populate(objectMap, "containerRunOptions", t.ContainerRunOptions) + populate(objectMap, "imageName", t.ImageName) + populate(objectMap, "registry", t.Registry) + populate(objectMap, "workingDirectory", t.WorkingDirectory) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type TaskContainerSettings. +func (t *TaskContainerSettings) 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 "containerHostBatchBindMounts": + err = unpopulate(val, "ContainerHostBatchBindMounts", &t.ContainerHostBatchBindMounts) + delete(rawMsg, key) + case "containerRunOptions": + err = unpopulate(val, "ContainerRunOptions", &t.ContainerRunOptions) + delete(rawMsg, key) + case "imageName": + err = unpopulate(val, "ImageName", &t.ImageName) + delete(rawMsg, key) + case "registry": + err = unpopulate(val, "Registry", &t.Registry) + delete(rawMsg, key) + case "workingDirectory": + err = unpopulate(val, "WorkingDirectory", &t.WorkingDirectory) + 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 TaskCounts. +func (t TaskCounts) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "active", t.Active) + populate(objectMap, "completed", t.Completed) + populate(objectMap, "failed", t.Failed) + populate(objectMap, "running", t.Running) + populate(objectMap, "succeeded", t.Succeeded) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type TaskCounts. +func (t *TaskCounts) 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 "active": + err = unpopulate(val, "Active", &t.Active) + delete(rawMsg, key) + case "completed": + err = unpopulate(val, "Completed", &t.Completed) + delete(rawMsg, key) + case "failed": + err = unpopulate(val, "Failed", &t.Failed) + delete(rawMsg, key) + case "running": + err = unpopulate(val, "Running", &t.Running) + delete(rawMsg, key) + case "succeeded": + err = unpopulate(val, "Succeeded", &t.Succeeded) + 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 TaskCountsResult. +func (t TaskCountsResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "taskCounts", t.TaskCounts) + populate(objectMap, "taskSlotCounts", t.TaskSlotCounts) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type TaskCountsResult. +func (t *TaskCountsResult) 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 "taskCounts": + err = unpopulate(val, "TaskCounts", &t.TaskCounts) + delete(rawMsg, key) + case "taskSlotCounts": + err = unpopulate(val, "TaskSlotCounts", &t.TaskSlotCounts) + 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 TaskDependencies. +func (t TaskDependencies) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "taskIdRanges", t.TaskIDRanges) + populate(objectMap, "taskIds", t.TaskIDs) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type TaskDependencies. +func (t *TaskDependencies) 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 "taskIdRanges": + err = unpopulate(val, "TaskIDRanges", &t.TaskIDRanges) + delete(rawMsg, key) + case "taskIds": + err = unpopulate(val, "TaskIDs", &t.TaskIDs) + 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 TaskExecutionInfo. +func (t TaskExecutionInfo) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "containerInfo", t.ContainerInfo) + populateDateTimeRFC3339(objectMap, "endTime", t.EndTime) + populate(objectMap, "exitCode", t.ExitCode) + populate(objectMap, "failureInfo", t.FailureInfo) + populateDateTimeRFC3339(objectMap, "lastRequeueTime", t.LastRequeueTime) + populateDateTimeRFC3339(objectMap, "lastRetryTime", t.LastRetryTime) + populate(objectMap, "requeueCount", t.RequeueCount) + populate(objectMap, "result", t.Result) + populate(objectMap, "retryCount", t.RetryCount) + populateDateTimeRFC3339(objectMap, "startTime", t.StartTime) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type TaskExecutionInfo. +func (t *TaskExecutionInfo) 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 "containerInfo": + err = unpopulate(val, "ContainerInfo", &t.ContainerInfo) + delete(rawMsg, key) + case "endTime": + err = unpopulateDateTimeRFC3339(val, "EndTime", &t.EndTime) + delete(rawMsg, key) + case "exitCode": + err = unpopulate(val, "ExitCode", &t.ExitCode) + delete(rawMsg, key) + case "failureInfo": + err = unpopulate(val, "FailureInfo", &t.FailureInfo) + delete(rawMsg, key) + case "lastRequeueTime": + err = unpopulateDateTimeRFC3339(val, "LastRequeueTime", &t.LastRequeueTime) + delete(rawMsg, key) + case "lastRetryTime": + err = unpopulateDateTimeRFC3339(val, "LastRetryTime", &t.LastRetryTime) + delete(rawMsg, key) + case "requeueCount": + err = unpopulate(val, "RequeueCount", &t.RequeueCount) + delete(rawMsg, key) + case "result": + err = unpopulate(val, "Result", &t.Result) + delete(rawMsg, key) + case "retryCount": + err = unpopulate(val, "RetryCount", &t.RetryCount) + delete(rawMsg, key) + case "startTime": + err = unpopulateDateTimeRFC3339(val, "StartTime", &t.StartTime) + 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 TaskFailureInfo. +func (t TaskFailureInfo) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "category", t.Category) + populate(objectMap, "code", t.Code) + populate(objectMap, "details", t.Details) + populate(objectMap, "message", t.Message) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type TaskFailureInfo. +func (t *TaskFailureInfo) 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 "category": + err = unpopulate(val, "Category", &t.Category) + delete(rawMsg, key) + case "code": + err = unpopulate(val, "Code", &t.Code) + delete(rawMsg, key) + case "details": + err = unpopulate(val, "Details", &t.Details) + delete(rawMsg, key) + case "message": + err = unpopulate(val, "Message", &t.Message) + 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 TaskGroup. +func (t TaskGroup) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "value", t.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type TaskGroup. +func (t *TaskGroup) 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 "value": + err = unpopulate(val, "Value", &t.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type TaskIDRange. +func (t TaskIDRange) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "end", t.End) + populate(objectMap, "start", t.Start) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type TaskIDRange. +func (t *TaskIDRange) 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 "end": + err = unpopulate(val, "End", &t.End) + delete(rawMsg, key) + case "start": + err = unpopulate(val, "Start", &t.Start) + 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 TaskInfo. +func (t TaskInfo) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "executionInfo", t.ExecutionInfo) + populate(objectMap, "jobId", t.JobID) + populate(objectMap, "subtaskId", t.SubtaskID) + populate(objectMap, "taskId", t.TaskID) + populate(objectMap, "taskState", t.TaskState) + populate(objectMap, "taskUrl", t.TaskURL) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type TaskInfo. +func (t *TaskInfo) 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 "executionInfo": + err = unpopulate(val, "ExecutionInfo", &t.ExecutionInfo) + delete(rawMsg, key) + case "jobId": + err = unpopulate(val, "JobID", &t.JobID) + delete(rawMsg, key) + case "subtaskId": + err = unpopulate(val, "SubtaskID", &t.SubtaskID) + delete(rawMsg, key) + case "taskId": + err = unpopulate(val, "TaskID", &t.TaskID) + delete(rawMsg, key) + case "taskState": + err = unpopulate(val, "TaskState", &t.TaskState) + delete(rawMsg, key) + case "taskUrl": + err = unpopulate(val, "TaskURL", &t.TaskURL) + 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 TaskListResult. +func (t TaskListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "odata.nextLink", t.NextLink) + populate(objectMap, "value", t.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type TaskListResult. +func (t *TaskListResult) 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 "odata.nextLink": + err = unpopulate(val, "NextLink", &t.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &t.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type TaskListSubtasksResult. +func (t TaskListSubtasksResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "odata.nextLink", t.NextLink) + populate(objectMap, "value", t.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type TaskListSubtasksResult. +func (t *TaskListSubtasksResult) 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 "odata.nextLink": + err = unpopulate(val, "NextLink", &t.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &t.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type TaskSchedulingPolicy. +func (t TaskSchedulingPolicy) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nodeFillType", t.NodeFillType) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type TaskSchedulingPolicy. +func (t *TaskSchedulingPolicy) 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 "nodeFillType": + err = unpopulate(val, "NodeFillType", &t.NodeFillType) + 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 TaskSlotCounts. +func (t TaskSlotCounts) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "active", t.Active) + populate(objectMap, "completed", t.Completed) + populate(objectMap, "failed", t.Failed) + populate(objectMap, "running", t.Running) + populate(objectMap, "succeeded", t.Succeeded) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type TaskSlotCounts. +func (t *TaskSlotCounts) 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 "active": + err = unpopulate(val, "Active", &t.Active) + delete(rawMsg, key) + case "completed": + err = unpopulate(val, "Completed", &t.Completed) + delete(rawMsg, key) + case "failed": + err = unpopulate(val, "Failed", &t.Failed) + delete(rawMsg, key) + case "running": + err = unpopulate(val, "Running", &t.Running) + delete(rawMsg, key) + case "succeeded": + err = unpopulate(val, "Succeeded", &t.Succeeded) + 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 TaskStatistics. +func (t TaskStatistics) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "kernelCPUTime", t.KernelCPUTime) + populateDateTimeRFC3339(objectMap, "lastUpdateTime", t.LastUpdateTime) + populate(objectMap, "readIOGiB", t.ReadIOGiB) + populate(objectMap, "readIOps", to.Ptr(strconv.FormatInt(*t.ReadIOPS, 10))) + populateDateTimeRFC3339(objectMap, "startTime", t.StartTime) + populate(objectMap, "url", t.URL) + populate(objectMap, "userCPUTime", t.UserCPUTime) + populate(objectMap, "waitTime", t.WaitTime) + populate(objectMap, "wallClockTime", t.WallClockTime) + populate(objectMap, "writeIOGiB", t.WriteIOGiB) + populate(objectMap, "writeIOps", to.Ptr(strconv.FormatInt(*t.WriteIOPS, 10))) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type TaskStatistics. +func (t *TaskStatistics) 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 "kernelCPUTime": + err = unpopulate(val, "KernelCPUTime", &t.KernelCPUTime) + delete(rawMsg, key) + case "lastUpdateTime": + err = unpopulateDateTimeRFC3339(val, "LastUpdateTime", &t.LastUpdateTime) + delete(rawMsg, key) + case "readIOGiB": + err = unpopulate(val, "ReadIOGiB", &t.ReadIOGiB) + delete(rawMsg, key) + case "readIOps": + var aux string + err = unpopulate(val, "ReadIOPS", &aux) + if err == nil { + var v int64 + v, err = strconv.ParseInt(aux, 10, 0) + if err == nil { + t.ReadIOPS = to.Ptr(v) + } + } + delete(rawMsg, key) + case "startTime": + err = unpopulateDateTimeRFC3339(val, "StartTime", &t.StartTime) + delete(rawMsg, key) + case "url": + err = unpopulate(val, "URL", &t.URL) + delete(rawMsg, key) + case "userCPUTime": + err = unpopulate(val, "UserCPUTime", &t.UserCPUTime) + delete(rawMsg, key) + case "waitTime": + err = unpopulate(val, "WaitTime", &t.WaitTime) + delete(rawMsg, key) + case "wallClockTime": + err = unpopulate(val, "WallClockTime", &t.WallClockTime) + delete(rawMsg, key) + case "writeIOGiB": + err = unpopulate(val, "WriteIOGiB", &t.WriteIOGiB) + delete(rawMsg, key) + case "writeIOps": + var aux string + err = unpopulate(val, "WriteIOPS", &aux) + if err == nil { + var v int64 + v, err = strconv.ParseInt(aux, 10, 0) + if err == nil { + t.WriteIOPS = to.Ptr(v) + } + } + 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 TerminateJobContent. +func (t TerminateJobContent) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "terminateReason", t.TerminationReason) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type TerminateJobContent. +func (t *TerminateJobContent) 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 "terminateReason": + err = unpopulate(val, "TerminationReason", &t.TerminationReason) + 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 UEFISettings. +func (u UEFISettings) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "secureBootEnabled", u.SecureBootEnabled) + populate(objectMap, "vTpmEnabled", u.VTPMEnabled) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type UEFISettings. +func (u *UEFISettings) 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 "secureBootEnabled": + err = unpopulate(val, "SecureBootEnabled", &u.SecureBootEnabled) + delete(rawMsg, key) + case "vTpmEnabled": + err = unpopulate(val, "VTPMEnabled", &u.VTPMEnabled) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type UpdateJobContent. +func (u UpdateJobContent) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "allowTaskPreemption", u.AllowTaskPreemption) + populate(objectMap, "constraints", u.Constraints) + populate(objectMap, "maxParallelTasks", u.MaxParallelTasks) + populate(objectMap, "metadata", u.Metadata) + populate(objectMap, "networkConfiguration", u.NetworkConfiguration) + populate(objectMap, "onAllTasksComplete", u.OnAllTasksComplete) + populate(objectMap, "poolInfo", u.PoolInfo) + populate(objectMap, "priority", u.Priority) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type UpdateJobContent. +func (u *UpdateJobContent) 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 "allowTaskPreemption": + err = unpopulate(val, "AllowTaskPreemption", &u.AllowTaskPreemption) + delete(rawMsg, key) + case "constraints": + err = unpopulate(val, "Constraints", &u.Constraints) + delete(rawMsg, key) + case "maxParallelTasks": + err = unpopulate(val, "MaxParallelTasks", &u.MaxParallelTasks) + delete(rawMsg, key) + case "metadata": + err = unpopulate(val, "Metadata", &u.Metadata) + delete(rawMsg, key) + case "networkConfiguration": + err = unpopulate(val, "NetworkConfiguration", &u.NetworkConfiguration) + delete(rawMsg, key) + case "onAllTasksComplete": + err = unpopulate(val, "OnAllTasksComplete", &u.OnAllTasksComplete) + delete(rawMsg, key) + case "poolInfo": + err = unpopulate(val, "PoolInfo", &u.PoolInfo) + delete(rawMsg, key) + case "priority": + err = unpopulate(val, "Priority", &u.Priority) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type UpdateJobScheduleContent. +func (u UpdateJobScheduleContent) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "jobSpecification", u.JobSpecification) + populate(objectMap, "metadata", u.Metadata) + populate(objectMap, "schedule", u.Schedule) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type UpdateJobScheduleContent. +func (u *UpdateJobScheduleContent) 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 "jobSpecification": + err = unpopulate(val, "JobSpecification", &u.JobSpecification) + delete(rawMsg, key) + case "metadata": + err = unpopulate(val, "Metadata", &u.Metadata) + delete(rawMsg, key) + case "schedule": + err = unpopulate(val, "Schedule", &u.Schedule) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type UpdateNodeUserContent. +func (u UpdateNodeUserContent) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateDateTimeRFC3339(objectMap, "expiryTime", u.ExpiryTime) + populate(objectMap, "password", u.Password) + populate(objectMap, "sshPublicKey", u.SSHPublicKey) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type UpdateNodeUserContent. +func (u *UpdateNodeUserContent) 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 "expiryTime": + err = unpopulateDateTimeRFC3339(val, "ExpiryTime", &u.ExpiryTime) + delete(rawMsg, key) + case "password": + err = unpopulate(val, "Password", &u.Password) + delete(rawMsg, key) + case "sshPublicKey": + err = unpopulate(val, "SSHPublicKey", &u.SSHPublicKey) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type UpdatePoolContent. +func (u UpdatePoolContent) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "applicationPackageReferences", u.ApplicationPackageReferences) + populate(objectMap, "certificateReferences", u.CertificateReferences) + populate(objectMap, "displayName", u.DisplayName) + populate(objectMap, "enableInterNodeCommunication", u.EnableInterNodeCommunication) + populate(objectMap, "metadata", u.Metadata) + populate(objectMap, "mountConfiguration", u.MountConfiguration) + populate(objectMap, "networkConfiguration", u.NetworkConfiguration) + populate(objectMap, "resourceTags", u.ResourceTags) + populate(objectMap, "startTask", u.StartTask) + populate(objectMap, "targetNodeCommunicationMode", u.TargetNodeCommunicationMode) + populate(objectMap, "taskSchedulingPolicy", u.TaskSchedulingPolicy) + populate(objectMap, "taskSlotsPerNode", u.TaskSlotsPerNode) + populate(objectMap, "upgradePolicy", u.UpgradePolicy) + populate(objectMap, "userAccounts", u.UserAccounts) + populate(objectMap, "vmSize", u.VMSize) + populate(objectMap, "virtualMachineConfiguration", u.VirtualMachineConfiguration) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type UpdatePoolContent. +func (u *UpdatePoolContent) 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 "applicationPackageReferences": + err = unpopulate(val, "ApplicationPackageReferences", &u.ApplicationPackageReferences) + delete(rawMsg, key) + case "certificateReferences": + err = unpopulate(val, "CertificateReferences", &u.CertificateReferences) + delete(rawMsg, key) + case "displayName": + err = unpopulate(val, "DisplayName", &u.DisplayName) + delete(rawMsg, key) + case "enableInterNodeCommunication": + err = unpopulate(val, "EnableInterNodeCommunication", &u.EnableInterNodeCommunication) + delete(rawMsg, key) + case "metadata": + err = unpopulate(val, "Metadata", &u.Metadata) + delete(rawMsg, key) + case "mountConfiguration": + err = unpopulate(val, "MountConfiguration", &u.MountConfiguration) + delete(rawMsg, key) + case "networkConfiguration": + err = unpopulate(val, "NetworkConfiguration", &u.NetworkConfiguration) + delete(rawMsg, key) + case "resourceTags": + err = unpopulate(val, "ResourceTags", &u.ResourceTags) + delete(rawMsg, key) + case "startTask": + err = unpopulate(val, "StartTask", &u.StartTask) + delete(rawMsg, key) + case "targetNodeCommunicationMode": + err = unpopulate(val, "TargetNodeCommunicationMode", &u.TargetNodeCommunicationMode) + delete(rawMsg, key) + case "taskSchedulingPolicy": + err = unpopulate(val, "TaskSchedulingPolicy", &u.TaskSchedulingPolicy) + delete(rawMsg, key) + case "taskSlotsPerNode": + err = unpopulate(val, "TaskSlotsPerNode", &u.TaskSlotsPerNode) + delete(rawMsg, key) + case "upgradePolicy": + err = unpopulate(val, "UpgradePolicy", &u.UpgradePolicy) + delete(rawMsg, key) + case "userAccounts": + err = unpopulate(val, "UserAccounts", &u.UserAccounts) + delete(rawMsg, key) + case "vmSize": + err = unpopulate(val, "VMSize", &u.VMSize) + delete(rawMsg, key) + case "virtualMachineConfiguration": + err = unpopulate(val, "VirtualMachineConfiguration", &u.VirtualMachineConfiguration) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type UpgradePolicy. +func (u UpgradePolicy) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "automaticOSUpgradePolicy", u.AutomaticOsUpgradePolicy) + populate(objectMap, "mode", u.Mode) + populate(objectMap, "rollingUpgradePolicy", u.RollingUpgradePolicy) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type UpgradePolicy. +func (u *UpgradePolicy) 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 "automaticOSUpgradePolicy": + err = unpopulate(val, "AutomaticOsUpgradePolicy", &u.AutomaticOsUpgradePolicy) + delete(rawMsg, key) + case "mode": + err = unpopulate(val, "Mode", &u.Mode) + delete(rawMsg, key) + case "rollingUpgradePolicy": + err = unpopulate(val, "RollingUpgradePolicy", &u.RollingUpgradePolicy) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type UploadNodeLogsContent. +func (u UploadNodeLogsContent) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "containerUrl", u.ContainerURL) + populateDateTimeRFC3339(objectMap, "endTime", u.EndTime) + populate(objectMap, "identityReference", u.IdentityReference) + populateDateTimeRFC3339(objectMap, "startTime", u.StartTime) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type UploadNodeLogsContent. +func (u *UploadNodeLogsContent) 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 "containerUrl": + err = unpopulate(val, "ContainerURL", &u.ContainerURL) + delete(rawMsg, key) + case "endTime": + err = unpopulateDateTimeRFC3339(val, "EndTime", &u.EndTime) + delete(rawMsg, key) + case "identityReference": + err = unpopulate(val, "IdentityReference", &u.IdentityReference) + delete(rawMsg, key) + case "startTime": + err = unpopulateDateTimeRFC3339(val, "StartTime", &u.StartTime) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type UploadNodeLogsResult. +func (u UploadNodeLogsResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "numberOfFilesUploaded", u.NumberOfFilesUploaded) + populate(objectMap, "virtualDirectoryName", u.VirtualDirectoryName) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type UploadNodeLogsResult. +func (u *UploadNodeLogsResult) 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 "numberOfFilesUploaded": + err = unpopulate(val, "NumberOfFilesUploaded", &u.NumberOfFilesUploaded) + delete(rawMsg, key) + case "virtualDirectoryName": + err = unpopulate(val, "VirtualDirectoryName", &u.VirtualDirectoryName) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type UserAccount. +func (u UserAccount) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "elevationLevel", u.ElevationLevel) + populate(objectMap, "linuxUserConfiguration", u.LinuxUserConfiguration) + populate(objectMap, "name", u.Name) + populate(objectMap, "password", u.Password) + populate(objectMap, "windowsUserConfiguration", u.WindowsUserConfiguration) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type UserAccount. +func (u *UserAccount) 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 "elevationLevel": + err = unpopulate(val, "ElevationLevel", &u.ElevationLevel) + delete(rawMsg, key) + case "linuxUserConfiguration": + err = unpopulate(val, "LinuxUserConfiguration", &u.LinuxUserConfiguration) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &u.Name) + delete(rawMsg, key) + case "password": + err = unpopulate(val, "Password", &u.Password) + delete(rawMsg, key) + case "windowsUserConfiguration": + err = unpopulate(val, "WindowsUserConfiguration", &u.WindowsUserConfiguration) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, 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) + populate(objectMap, "resourceId", u.ResourceID) + 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) + case "resourceId": + err = unpopulate(val, "ResourceID", &u.ResourceID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type UserIdentity. +func (u UserIdentity) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "autoUser", u.AutoUser) + populate(objectMap, "username", u.Username) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type UserIdentity. +func (u *UserIdentity) 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 "autoUser": + err = unpopulate(val, "AutoUser", &u.AutoUser) + delete(rawMsg, key) + case "username": + err = unpopulate(val, "Username", &u.Username) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type VMDiskSecurityProfile. +func (v VMDiskSecurityProfile) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "securityEncryptionType", v.SecurityEncryptionType) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VMDiskSecurityProfile. +func (v *VMDiskSecurityProfile) 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", v, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "securityEncryptionType": + err = unpopulate(val, "SecurityEncryptionType", &v.SecurityEncryptionType) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", v, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type VMExtension. +func (v VMExtension) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "autoUpgradeMinorVersion", v.AutoUpgradeMinorVersion) + populate(objectMap, "enableAutomaticUpgrade", v.EnableAutomaticUpgrade) + populate(objectMap, "name", v.Name) + populate(objectMap, "protectedSettings", v.ProtectedSettings) + populate(objectMap, "provisionAfterExtensions", v.ProvisionAfterExtensions) + populate(objectMap, "publisher", v.Publisher) + populate(objectMap, "settings", v.Settings) + populate(objectMap, "type", v.Type) + populate(objectMap, "typeHandlerVersion", v.TypeHandlerVersion) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VMExtension. +func (v *VMExtension) 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", v, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "autoUpgradeMinorVersion": + err = unpopulate(val, "AutoUpgradeMinorVersion", &v.AutoUpgradeMinorVersion) + delete(rawMsg, key) + case "enableAutomaticUpgrade": + err = unpopulate(val, "EnableAutomaticUpgrade", &v.EnableAutomaticUpgrade) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &v.Name) + delete(rawMsg, key) + case "protectedSettings": + err = unpopulate(val, "ProtectedSettings", &v.ProtectedSettings) + delete(rawMsg, key) + case "provisionAfterExtensions": + err = unpopulate(val, "ProvisionAfterExtensions", &v.ProvisionAfterExtensions) + delete(rawMsg, key) + case "publisher": + err = unpopulate(val, "Publisher", &v.Publisher) + delete(rawMsg, key) + case "settings": + err = unpopulate(val, "Settings", &v.Settings) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &v.Type) + delete(rawMsg, key) + case "typeHandlerVersion": + err = unpopulate(val, "TypeHandlerVersion", &v.TypeHandlerVersion) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", v, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type VMExtensionInstanceView. +func (v VMExtensionInstanceView) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", v.Name) + populate(objectMap, "statuses", v.Statuses) + populate(objectMap, "subStatuses", v.SubStatuses) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VMExtensionInstanceView. +func (v *VMExtensionInstanceView) 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", v, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &v.Name) + delete(rawMsg, key) + case "statuses": + err = unpopulate(val, "Statuses", &v.Statuses) + delete(rawMsg, key) + case "subStatuses": + err = unpopulate(val, "SubStatuses", &v.SubStatuses) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", v, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type VirtualMachineConfiguration. +func (v VirtualMachineConfiguration) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "containerConfiguration", v.ContainerConfiguration) + populate(objectMap, "dataDisks", v.DataDisks) + populate(objectMap, "diskEncryptionConfiguration", v.DiskEncryptionConfiguration) + populate(objectMap, "extensions", v.Extensions) + populate(objectMap, "imageReference", v.ImageReference) + populate(objectMap, "licenseType", v.LicenseType) + populate(objectMap, "nodeAgentSKUId", v.NodeAgentSKUID) + populate(objectMap, "nodePlacementConfiguration", v.NodePlacementConfiguration) + populate(objectMap, "osDisk", v.OSDisk) + populate(objectMap, "securityProfile", v.SecurityProfile) + populate(objectMap, "serviceArtifactReference", v.ServiceArtifactReference) + populate(objectMap, "windowsConfiguration", v.WindowsConfiguration) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachineConfiguration. +func (v *VirtualMachineConfiguration) 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", v, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "containerConfiguration": + err = unpopulate(val, "ContainerConfiguration", &v.ContainerConfiguration) + delete(rawMsg, key) + case "dataDisks": + err = unpopulate(val, "DataDisks", &v.DataDisks) + delete(rawMsg, key) + case "diskEncryptionConfiguration": + err = unpopulate(val, "DiskEncryptionConfiguration", &v.DiskEncryptionConfiguration) + delete(rawMsg, key) + case "extensions": + err = unpopulate(val, "Extensions", &v.Extensions) + delete(rawMsg, key) + case "imageReference": + err = unpopulate(val, "ImageReference", &v.ImageReference) + delete(rawMsg, key) + case "licenseType": + err = unpopulate(val, "LicenseType", &v.LicenseType) + delete(rawMsg, key) + case "nodeAgentSKUId": + err = unpopulate(val, "NodeAgentSKUID", &v.NodeAgentSKUID) + delete(rawMsg, key) + case "nodePlacementConfiguration": + err = unpopulate(val, "NodePlacementConfiguration", &v.NodePlacementConfiguration) + delete(rawMsg, key) + case "osDisk": + err = unpopulate(val, "OSDisk", &v.OSDisk) + delete(rawMsg, key) + case "securityProfile": + err = unpopulate(val, "SecurityProfile", &v.SecurityProfile) + delete(rawMsg, key) + case "serviceArtifactReference": + err = unpopulate(val, "ServiceArtifactReference", &v.ServiceArtifactReference) + delete(rawMsg, key) + case "windowsConfiguration": + err = unpopulate(val, "WindowsConfiguration", &v.WindowsConfiguration) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", v, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type VirtualMachineInfo. +func (v VirtualMachineInfo) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "imageReference", v.ImageReference) + populate(objectMap, "scaleSetVmResourceId", v.ScaleSetVMResourceID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachineInfo. +func (v *VirtualMachineInfo) 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", v, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "imageReference": + err = unpopulate(val, "ImageReference", &v.ImageReference) + delete(rawMsg, key) + case "scaleSetVmResourceId": + err = unpopulate(val, "ScaleSetVMResourceID", &v.ScaleSetVMResourceID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", v, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type WindowsConfiguration. +func (w WindowsConfiguration) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "enableAutomaticUpdates", w.EnableAutomaticUpdates) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type WindowsConfiguration. +func (w *WindowsConfiguration) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", w, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "enableAutomaticUpdates": + err = unpopulate(val, "EnableAutomaticUpdates", &w.EnableAutomaticUpdates) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", w, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type WindowsUserConfiguration. +func (w WindowsUserConfiguration) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "loginMode", w.LoginMode) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type WindowsUserConfiguration. +func (w *WindowsUserConfiguration) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", w, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "loginMode": + err = unpopulate(val, "LoginMode", &w.LoginMode) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", w, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type listPoolUsageMetricsResult. +func (l listPoolUsageMetricsResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "odata.nextLink", l.NextLink) + populate(objectMap, "value", l.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type listPoolUsageMetricsResult. +func (l *listPoolUsageMetricsResult) 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 "odata.nextLink": + err = unpopulate(val, "NextLink", &l.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &l.Value) + 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 poolUsageMetrics. +func (p poolUsageMetrics) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateDateTimeRFC3339(objectMap, "endTime", p.EndTime) + populate(objectMap, "poolId", p.PoolID) + populateDateTimeRFC3339(objectMap, "startTime", p.StartTime) + populate(objectMap, "totalCoreHours", p.TotalCoreHours) + populate(objectMap, "vmSize", p.VMSize) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type poolUsageMetrics. +func (p *poolUsageMetrics) 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 "endTime": + err = unpopulateDateTimeRFC3339(val, "EndTime", &p.EndTime) + delete(rawMsg, key) + case "poolId": + err = unpopulate(val, "PoolID", &p.PoolID) + delete(rawMsg, key) + case "startTime": + err = unpopulateDateTimeRFC3339(val, "StartTime", &p.StartTime) + delete(rawMsg, key) + case "totalCoreHours": + err = unpopulate(val, "TotalCoreHours", &p.TotalCoreHours) + delete(rawMsg, key) + case "vmSize": + err = unpopulate(val, "VMSize", &p.VMSize) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, 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/batch/azbatch/options.go b/sdk/batch/azbatch/options.go new file mode 100644 index 000000000000..65afc74f1748 --- /dev/null +++ b/sdk/batch/azbatch/options.go @@ -0,0 +1,2329 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package azbatch + +import "time" + +// CancelCertificateDeletionOptions contains the optional parameters for the Client.CancelCertificateDeletion method. +type CancelCertificateDeletionOptions struct { + // The caller-generated request identity, in the form of a GUID with no decoration + // such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + ClientRequestID *string + + // The time the request was issued. Client libraries typically set this to the + // current system clock time; set it explicitly if you are calling the REST API + // directly. + Ocpdate *time.Time + + // Whether the server should return the client-request-id in the response. + ReturnClientRequestID *bool + + // The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value + // is larger than 30, the default will be used instead.". + Timeout *int32 +} + +// CreateCertificateOptions contains the optional parameters for the Client.CreateCertificate method. +type CreateCertificateOptions struct { + // The caller-generated request identity, in the form of a GUID with no decoration + // such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + ClientRequestID *string + + // The time the request was issued. Client libraries typically set this to the + // current system clock time; set it explicitly if you are calling the REST API + // directly. + Ocpdate *time.Time + + // Whether the server should return the client-request-id in the response. + ReturnClientRequestID *bool + + // The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value + // is larger than 30, the default will be used instead.". + Timeout *int32 +} + +// CreateJobOptions contains the optional parameters for the Client.CreateJob method. +type CreateJobOptions struct { + // The caller-generated request identity, in the form of a GUID with no decoration + // such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + ClientRequestID *string + + // The time the request was issued. Client libraries typically set this to the + // current system clock time; set it explicitly if you are calling the REST API + // directly. + Ocpdate *time.Time + + // Whether the server should return the client-request-id in the response. + ReturnClientRequestID *bool + + // The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value + // is larger than 30, the default will be used instead.". + Timeout *int32 +} + +// CreateJobScheduleOptions contains the optional parameters for the Client.CreateJobSchedule method. +type CreateJobScheduleOptions struct { + // The caller-generated request identity, in the form of a GUID with no decoration + // such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + ClientRequestID *string + + // The time the request was issued. Client libraries typically set this to the + // current system clock time; set it explicitly if you are calling the REST API + // directly. + Ocpdate *time.Time + + // Whether the server should return the client-request-id in the response. + ReturnClientRequestID *bool + + // The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value + // is larger than 30, the default will be used instead.". + Timeout *int32 +} + +// CreateNodeUserOptions contains the optional parameters for the Client.CreateNodeUser method. +type CreateNodeUserOptions struct { + // The caller-generated request identity, in the form of a GUID with no decoration + // such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + ClientRequestID *string + + // The time the request was issued. Client libraries typically set this to the + // current system clock time; set it explicitly if you are calling the REST API + // directly. + Ocpdate *time.Time + + // Whether the server should return the client-request-id in the response. + ReturnClientRequestID *bool + + // The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value + // is larger than 30, the default will be used instead.". + Timeout *int32 +} + +// CreatePoolOptions contains the optional parameters for the Client.CreatePool method. +type CreatePoolOptions struct { + // The caller-generated request identity, in the form of a GUID with no decoration + // such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + ClientRequestID *string + + // The time the request was issued. Client libraries typically set this to the + // current system clock time; set it explicitly if you are calling the REST API + // directly. + Ocpdate *time.Time + + // Whether the server should return the client-request-id in the response. + ReturnClientRequestID *bool + + // The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value + // is larger than 30, the default will be used instead.". + Timeout *int32 +} + +// CreateTaskCollectionOptions contains the optional parameters for the Client.CreateTaskCollection method. +type CreateTaskCollectionOptions struct { + // The caller-generated request identity, in the form of a GUID with no decoration + // such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + ClientRequestID *string + + // The time the request was issued. Client libraries typically set this to the + // current system clock time; set it explicitly if you are calling the REST API + // directly. + Ocpdate *time.Time + + // Whether the server should return the client-request-id in the response. + ReturnClientRequestID *bool + + // The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value + // is larger than 30, the default will be used instead.". + Timeout *int32 +} + +// CreateTaskOptions contains the optional parameters for the Client.CreateTask method. +type CreateTaskOptions struct { + // The caller-generated request identity, in the form of a GUID with no decoration + // such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + ClientRequestID *string + + // The time the request was issued. Client libraries typically set this to the + // current system clock time; set it explicitly if you are calling the REST API + // directly. + Ocpdate *time.Time + + // Whether the server should return the client-request-id in the response. + ReturnClientRequestID *bool + + // The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value + // is larger than 30, the default will be used instead.". + Timeout *int32 +} + +// DeallocateNodeOptions contains the optional parameters for the Client.DeallocateNode method. +type DeallocateNodeOptions struct { + // The caller-generated request identity, in the form of a GUID with no decoration + // such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + ClientRequestID *string + + // The time the request was issued. Client libraries typically set this to the + // current system clock time; set it explicitly if you are calling the REST API + // directly. + Ocpdate *time.Time + + // The options to use for deallocating the Compute Node. + Parameters *DeallocateNodeContent + + // Whether the server should return the client-request-id in the response. + ReturnClientRequestID *bool + + // The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value + // is larger than 30, the default will be used instead.". + Timeout *int32 +} + +// DeleteCertificateOptions contains the optional parameters for the Client.DeleteCertificate method. +type DeleteCertificateOptions struct { + // The caller-generated request identity, in the form of a GUID with no decoration + // such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + ClientRequestID *string + + // The time the request was issued. Client libraries typically set this to the + // current system clock time; set it explicitly if you are calling the REST API + // directly. + Ocpdate *time.Time + + // Whether the server should return the client-request-id in the response. + ReturnClientRequestID *bool + + // The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value + // is larger than 30, the default will be used instead.". + Timeout *int32 +} + +// DeleteJobOptions contains the optional parameters for the Client.DeleteJob method. +type DeleteJobOptions struct { + // The caller-generated request identity, in the form of a GUID with no decoration + // such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + ClientRequestID *string + + // If true, the server will delete the Job even if the corresponding nodes have not fully processed the deletion. The default + // value is false. + Force *bool + + // An ETag value associated with the version of the resource known to the client. + // The operation will be performed only if the resource's current ETag on the + // service exactly matches the value specified by the client. + IfMatch *string + + // A timestamp indicating the last modified time of the resource known to the + // client. The operation will be performed only if the resource on the service has + // been modified since the specified time. + IfModifiedSince *time.Time + + // An ETag value associated with the version of the resource known to the client. + // The operation will be performed only if the resource's current ETag on the + // service does not match the value specified by the client. + IfNoneMatch *string + + // A timestamp indicating the last modified time of the resource known to the + // client. The operation will be performed only if the resource on the service has + // not been modified since the specified time. + IfUnmodifiedSince *time.Time + + // The time the request was issued. Client libraries typically set this to the + // current system clock time; set it explicitly if you are calling the REST API + // directly. + Ocpdate *time.Time + + // Whether the server should return the client-request-id in the response. + ReturnClientRequestID *bool + + // The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value + // is larger than 30, the default will be used instead.". + Timeout *int32 +} + +// DeleteJobScheduleOptions contains the optional parameters for the Client.DeleteJobSchedule method. +type DeleteJobScheduleOptions struct { + // The caller-generated request identity, in the form of a GUID with no decoration + // such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + ClientRequestID *string + + // If true, the server will delete the JobSchedule even if the corresponding nodes have not fully processed the deletion. + // The default value is false. + Force *bool + + // An ETag value associated with the version of the resource known to the client. + // The operation will be performed only if the resource's current ETag on the + // service exactly matches the value specified by the client. + IfMatch *string + + // A timestamp indicating the last modified time of the resource known to the + // client. The operation will be performed only if the resource on the service has + // been modified since the specified time. + IfModifiedSince *time.Time + + // An ETag value associated with the version of the resource known to the client. + // The operation will be performed only if the resource's current ETag on the + // service does not match the value specified by the client. + IfNoneMatch *string + + // A timestamp indicating the last modified time of the resource known to the + // client. The operation will be performed only if the resource on the service has + // not been modified since the specified time. + IfUnmodifiedSince *time.Time + + // The time the request was issued. Client libraries typically set this to the + // current system clock time; set it explicitly if you are calling the REST API + // directly. + Ocpdate *time.Time + + // Whether the server should return the client-request-id in the response. + ReturnClientRequestID *bool + + // The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value + // is larger than 30, the default will be used instead.". + Timeout *int32 +} + +// DeleteNodeFileOptions contains the optional parameters for the Client.DeleteNodeFile method. +type DeleteNodeFileOptions struct { + // The caller-generated request identity, in the form of a GUID with no decoration + // such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + ClientRequestID *string + + // The time the request was issued. Client libraries typically set this to the + // current system clock time; set it explicitly if you are calling the REST API + // directly. + Ocpdate *time.Time + + // Whether to delete children of a directory. If the filePath parameter represents + // a directory instead of a file, you can set recursive to true to delete the + // directory and all of the files and subdirectories in it. If recursive is false + // then the directory must be empty or deletion will fail. + Recursive *bool + + // Whether the server should return the client-request-id in the response. + ReturnClientRequestID *bool + + // The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value + // is larger than 30, the default will be used instead.". + Timeout *int32 +} + +// DeleteNodeUserOptions contains the optional parameters for the Client.DeleteNodeUser method. +type DeleteNodeUserOptions struct { + // The caller-generated request identity, in the form of a GUID with no decoration + // such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + ClientRequestID *string + + // The time the request was issued. Client libraries typically set this to the + // current system clock time; set it explicitly if you are calling the REST API + // directly. + Ocpdate *time.Time + + // Whether the server should return the client-request-id in the response. + ReturnClientRequestID *bool + + // The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value + // is larger than 30, the default will be used instead.". + Timeout *int32 +} + +// DeletePoolOptions contains the optional parameters for the Client.DeletePool method. +type DeletePoolOptions struct { + // The caller-generated request identity, in the form of a GUID with no decoration + // such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + ClientRequestID *string + + // An ETag value associated with the version of the resource known to the client. + // The operation will be performed only if the resource's current ETag on the + // service exactly matches the value specified by the client. + IfMatch *string + + // A timestamp indicating the last modified time of the resource known to the + // client. The operation will be performed only if the resource on the service has + // been modified since the specified time. + IfModifiedSince *time.Time + + // An ETag value associated with the version of the resource known to the client. + // The operation will be performed only if the resource's current ETag on the + // service does not match the value specified by the client. + IfNoneMatch *string + + // A timestamp indicating the last modified time of the resource known to the + // client. The operation will be performed only if the resource on the service has + // not been modified since the specified time. + IfUnmodifiedSince *time.Time + + // The time the request was issued. Client libraries typically set this to the + // current system clock time; set it explicitly if you are calling the REST API + // directly. + Ocpdate *time.Time + + // Whether the server should return the client-request-id in the response. + ReturnClientRequestID *bool + + // The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value + // is larger than 30, the default will be used instead.". + Timeout *int32 +} + +// DeleteTaskFileOptions contains the optional parameters for the Client.DeleteTaskFile method. +type DeleteTaskFileOptions struct { + // The caller-generated request identity, in the form of a GUID with no decoration + // such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + ClientRequestID *string + + // The time the request was issued. Client libraries typically set this to the + // current system clock time; set it explicitly if you are calling the REST API + // directly. + Ocpdate *time.Time + + // Whether to delete children of a directory. If the filePath parameter represents + // a directory instead of a file, you can set recursive to true to delete the + // directory and all of the files and subdirectories in it. If recursive is false + // then the directory must be empty or deletion will fail. + Recursive *bool + + // Whether the server should return the client-request-id in the response. + ReturnClientRequestID *bool + + // The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value + // is larger than 30, the default will be used instead.". + Timeout *int32 +} + +// DeleteTaskOptions contains the optional parameters for the Client.DeleteTask method. +type DeleteTaskOptions struct { + // The caller-generated request identity, in the form of a GUID with no decoration + // such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + ClientRequestID *string + + // An ETag value associated with the version of the resource known to the client. + // The operation will be performed only if the resource's current ETag on the + // service exactly matches the value specified by the client. + IfMatch *string + + // A timestamp indicating the last modified time of the resource known to the + // client. The operation will be performed only if the resource on the service has + // been modified since the specified time. + IfModifiedSince *time.Time + + // An ETag value associated with the version of the resource known to the client. + // The operation will be performed only if the resource's current ETag on the + // service does not match the value specified by the client. + IfNoneMatch *string + + // A timestamp indicating the last modified time of the resource known to the + // client. The operation will be performed only if the resource on the service has + // not been modified since the specified time. + IfUnmodifiedSince *time.Time + + // The time the request was issued. Client libraries typically set this to the + // current system clock time; set it explicitly if you are calling the REST API + // directly. + Ocpdate *time.Time + + // Whether the server should return the client-request-id in the response. + ReturnClientRequestID *bool + + // The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value + // is larger than 30, the default will be used instead.". + Timeout *int32 +} + +// DisableJobOptions contains the optional parameters for the Client.DisableJob method. +type DisableJobOptions struct { + // The caller-generated request identity, in the form of a GUID with no decoration + // such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + ClientRequestID *string + + // An ETag value associated with the version of the resource known to the client. + // The operation will be performed only if the resource's current ETag on the + // service exactly matches the value specified by the client. + IfMatch *string + + // A timestamp indicating the last modified time of the resource known to the + // client. The operation will be performed only if the resource on the service has + // been modified since the specified time. + IfModifiedSince *time.Time + + // An ETag value associated with the version of the resource known to the client. + // The operation will be performed only if the resource's current ETag on the + // service does not match the value specified by the client. + IfNoneMatch *string + + // A timestamp indicating the last modified time of the resource known to the + // client. The operation will be performed only if the resource on the service has + // not been modified since the specified time. + IfUnmodifiedSince *time.Time + + // The time the request was issued. Client libraries typically set this to the + // current system clock time; set it explicitly if you are calling the REST API + // directly. + Ocpdate *time.Time + + // Whether the server should return the client-request-id in the response. + ReturnClientRequestID *bool + + // The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value + // is larger than 30, the default will be used instead.". + Timeout *int32 +} + +// DisableJobScheduleOptions contains the optional parameters for the Client.DisableJobSchedule method. +type DisableJobScheduleOptions struct { + // The caller-generated request identity, in the form of a GUID with no decoration + // such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + ClientRequestID *string + + // An ETag value associated with the version of the resource known to the client. + // The operation will be performed only if the resource's current ETag on the + // service exactly matches the value specified by the client. + IfMatch *string + + // A timestamp indicating the last modified time of the resource known to the + // client. The operation will be performed only if the resource on the service has + // been modified since the specified time. + IfModifiedSince *time.Time + + // An ETag value associated with the version of the resource known to the client. + // The operation will be performed only if the resource's current ETag on the + // service does not match the value specified by the client. + IfNoneMatch *string + + // A timestamp indicating the last modified time of the resource known to the + // client. The operation will be performed only if the resource on the service has + // not been modified since the specified time. + IfUnmodifiedSince *time.Time + + // The time the request was issued. Client libraries typically set this to the + // current system clock time; set it explicitly if you are calling the REST API + // directly. + Ocpdate *time.Time + + // Whether the server should return the client-request-id in the response. + ReturnClientRequestID *bool + + // The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value + // is larger than 30, the default will be used instead.". + Timeout *int32 +} + +// DisableNodeSchedulingOptions contains the optional parameters for the Client.DisableNodeScheduling method. +type DisableNodeSchedulingOptions struct { + // The caller-generated request identity, in the form of a GUID with no decoration + // such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + ClientRequestID *string + + // The time the request was issued. Client libraries typically set this to the + // current system clock time; set it explicitly if you are calling the REST API + // directly. + Ocpdate *time.Time + + // The options to use for disabling scheduling on the Compute Node. + Parameters *DisableNodeSchedulingContent + + // Whether the server should return the client-request-id in the response. + ReturnClientRequestID *bool + + // The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value + // is larger than 30, the default will be used instead.". + Timeout *int32 +} + +// DisablePoolAutoScaleOptions contains the optional parameters for the Client.DisablePoolAutoScale method. +type DisablePoolAutoScaleOptions struct { + // The caller-generated request identity, in the form of a GUID with no decoration + // such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + ClientRequestID *string + + // The time the request was issued. Client libraries typically set this to the + // current system clock time; set it explicitly if you are calling the REST API + // directly. + Ocpdate *time.Time + + // Whether the server should return the client-request-id in the response. + ReturnClientRequestID *bool + + // The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value + // is larger than 30, the default will be used instead.". + Timeout *int32 +} + +// EnableJobOptions contains the optional parameters for the Client.EnableJob method. +type EnableJobOptions struct { + // The caller-generated request identity, in the form of a GUID with no decoration + // such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + ClientRequestID *string + + // An ETag value associated with the version of the resource known to the client. + // The operation will be performed only if the resource's current ETag on the + // service exactly matches the value specified by the client. + IfMatch *string + + // A timestamp indicating the last modified time of the resource known to the + // client. The operation will be performed only if the resource on the service has + // been modified since the specified time. + IfModifiedSince *time.Time + + // An ETag value associated with the version of the resource known to the client. + // The operation will be performed only if the resource's current ETag on the + // service does not match the value specified by the client. + IfNoneMatch *string + + // A timestamp indicating the last modified time of the resource known to the + // client. The operation will be performed only if the resource on the service has + // not been modified since the specified time. + IfUnmodifiedSince *time.Time + + // The time the request was issued. Client libraries typically set this to the + // current system clock time; set it explicitly if you are calling the REST API + // directly. + Ocpdate *time.Time + + // Whether the server should return the client-request-id in the response. + ReturnClientRequestID *bool + + // The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value + // is larger than 30, the default will be used instead.". + Timeout *int32 +} + +// EnableJobScheduleOptions contains the optional parameters for the Client.EnableJobSchedule method. +type EnableJobScheduleOptions struct { + // The caller-generated request identity, in the form of a GUID with no decoration + // such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + ClientRequestID *string + + // An ETag value associated with the version of the resource known to the client. + // The operation will be performed only if the resource's current ETag on the + // service exactly matches the value specified by the client. + IfMatch *string + + // A timestamp indicating the last modified time of the resource known to the + // client. The operation will be performed only if the resource on the service has + // been modified since the specified time. + IfModifiedSince *time.Time + + // An ETag value associated with the version of the resource known to the client. + // The operation will be performed only if the resource's current ETag on the + // service does not match the value specified by the client. + IfNoneMatch *string + + // A timestamp indicating the last modified time of the resource known to the + // client. The operation will be performed only if the resource on the service has + // not been modified since the specified time. + IfUnmodifiedSince *time.Time + + // The time the request was issued. Client libraries typically set this to the + // current system clock time; set it explicitly if you are calling the REST API + // directly. + Ocpdate *time.Time + + // Whether the server should return the client-request-id in the response. + ReturnClientRequestID *bool + + // The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value + // is larger than 30, the default will be used instead.". + Timeout *int32 +} + +// EnableNodeSchedulingOptions contains the optional parameters for the Client.EnableNodeScheduling method. +type EnableNodeSchedulingOptions struct { + // The caller-generated request identity, in the form of a GUID with no decoration + // such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + ClientRequestID *string + + // The time the request was issued. Client libraries typically set this to the + // current system clock time; set it explicitly if you are calling the REST API + // directly. + Ocpdate *time.Time + + // Whether the server should return the client-request-id in the response. + ReturnClientRequestID *bool + + // The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value + // is larger than 30, the default will be used instead.". + Timeout *int32 +} + +// EnablePoolAutoScaleOptions contains the optional parameters for the Client.EnablePoolAutoScale method. +type EnablePoolAutoScaleOptions struct { + // The caller-generated request identity, in the form of a GUID with no decoration + // such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + ClientRequestID *string + + // An ETag value associated with the version of the resource known to the client. + // The operation will be performed only if the resource's current ETag on the + // service exactly matches the value specified by the client. + IfMatch *string + + // A timestamp indicating the last modified time of the resource known to the + // client. The operation will be performed only if the resource on the service has + // been modified since the specified time. + IfModifiedSince *time.Time + + // An ETag value associated with the version of the resource known to the client. + // The operation will be performed only if the resource's current ETag on the + // service does not match the value specified by the client. + IfNoneMatch *string + + // A timestamp indicating the last modified time of the resource known to the + // client. The operation will be performed only if the resource on the service has + // not been modified since the specified time. + IfUnmodifiedSince *time.Time + + // The time the request was issued. Client libraries typically set this to the + // current system clock time; set it explicitly if you are calling the REST API + // directly. + Ocpdate *time.Time + + // Whether the server should return the client-request-id in the response. + ReturnClientRequestID *bool + + // The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value + // is larger than 30, the default will be used instead.". + Timeout *int32 +} + +// EvaluatePoolAutoScaleOptions contains the optional parameters for the Client.EvaluatePoolAutoScale method. +type EvaluatePoolAutoScaleOptions struct { + // The caller-generated request identity, in the form of a GUID with no decoration + // such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + ClientRequestID *string + + // The time the request was issued. Client libraries typically set this to the + // current system clock time; set it explicitly if you are calling the REST API + // directly. + Ocpdate *time.Time + + // Whether the server should return the client-request-id in the response. + ReturnClientRequestID *bool + + // The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value + // is larger than 30, the default will be used instead.". + Timeout *int32 +} + +// GetApplicationOptions contains the optional parameters for the Client.GetApplication method. +type GetApplicationOptions struct { + // The caller-generated request identity, in the form of a GUID with no decoration + // such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + ClientRequestID *string + + // The time the request was issued. Client libraries typically set this to the + // current system clock time; set it explicitly if you are calling the REST API + // directly. + Ocpdate *time.Time + + // Whether the server should return the client-request-id in the response. + ReturnClientRequestID *bool + + // The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value + // is larger than 30, the default will be used instead.". + Timeout *int32 +} + +// GetCertificateOptions contains the optional parameters for the Client.GetCertificate method. +type GetCertificateOptions struct { + // The caller-generated request identity, in the form of a GUID with no decoration + // such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + ClientRequestID *string + + // The time the request was issued. Client libraries typically set this to the + // current system clock time; set it explicitly if you are calling the REST API + // directly. + Ocpdate *time.Time + + // Whether the server should return the client-request-id in the response. + ReturnClientRequestID *bool + + // An OData $select clause. + SelectParam []string + + // The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value + // is larger than 30, the default will be used instead.". + Timeout *int32 +} + +// GetJobOptions contains the optional parameters for the Client.GetJob method. +type GetJobOptions struct { + // The caller-generated request identity, in the form of a GUID with no decoration + // such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + ClientRequestID *string + + // An OData $expand clause. + Expand []string + + // An ETag value associated with the version of the resource known to the client. + // The operation will be performed only if the resource's current ETag on the + // service exactly matches the value specified by the client. + IfMatch *string + + // A timestamp indicating the last modified time of the resource known to the + // client. The operation will be performed only if the resource on the service has + // been modified since the specified time. + IfModifiedSince *time.Time + + // An ETag value associated with the version of the resource known to the client. + // The operation will be performed only if the resource's current ETag on the + // service does not match the value specified by the client. + IfNoneMatch *string + + // A timestamp indicating the last modified time of the resource known to the + // client. The operation will be performed only if the resource on the service has + // not been modified since the specified time. + IfUnmodifiedSince *time.Time + + // The time the request was issued. Client libraries typically set this to the + // current system clock time; set it explicitly if you are calling the REST API + // directly. + Ocpdate *time.Time + + // Whether the server should return the client-request-id in the response. + ReturnClientRequestID *bool + + // An OData $select clause. + SelectParam []string + + // The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value + // is larger than 30, the default will be used instead.". + Timeout *int32 +} + +// GetJobScheduleOptions contains the optional parameters for the Client.GetJobSchedule method. +type GetJobScheduleOptions struct { + // The caller-generated request identity, in the form of a GUID with no decoration + // such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + ClientRequestID *string + + // An OData $expand clause. + Expand []string + + // An ETag value associated with the version of the resource known to the client. + // The operation will be performed only if the resource's current ETag on the + // service exactly matches the value specified by the client. + IfMatch *string + + // A timestamp indicating the last modified time of the resource known to the + // client. The operation will be performed only if the resource on the service has + // been modified since the specified time. + IfModifiedSince *time.Time + + // An ETag value associated with the version of the resource known to the client. + // The operation will be performed only if the resource's current ETag on the + // service does not match the value specified by the client. + IfNoneMatch *string + + // A timestamp indicating the last modified time of the resource known to the + // client. The operation will be performed only if the resource on the service has + // not been modified since the specified time. + IfUnmodifiedSince *time.Time + + // The time the request was issued. Client libraries typically set this to the + // current system clock time; set it explicitly if you are calling the REST API + // directly. + Ocpdate *time.Time + + // Whether the server should return the client-request-id in the response. + ReturnClientRequestID *bool + + // An OData $select clause. + SelectParam []string + + // The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value + // is larger than 30, the default will be used instead.". + Timeout *int32 +} + +// GetJobTaskCountsOptions contains the optional parameters for the Client.GetJobTaskCounts method. +type GetJobTaskCountsOptions struct { + // The caller-generated request identity, in the form of a GUID with no decoration + // such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + ClientRequestID *string + + // The time the request was issued. Client libraries typically set this to the + // current system clock time; set it explicitly if you are calling the REST API + // directly. + Ocpdate *time.Time + + // Whether the server should return the client-request-id in the response. + ReturnClientRequestID *bool + + // The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value + // is larger than 30, the default will be used instead.". + Timeout *int32 +} + +// GetNodeExtensionOptions contains the optional parameters for the Client.GetNodeExtension method. +type GetNodeExtensionOptions struct { + // The caller-generated request identity, in the form of a GUID with no decoration + // such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + ClientRequestID *string + + // The time the request was issued. Client libraries typically set this to the + // current system clock time; set it explicitly if you are calling the REST API + // directly. + Ocpdate *time.Time + + // Whether the server should return the client-request-id in the response. + ReturnClientRequestID *bool + + // An OData $select clause. + SelectParam []string + + // The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value + // is larger than 30, the default will be used instead.". + Timeout *int32 +} + +// GetNodeFileOptions contains the optional parameters for the Client.GetNodeFile method. +type GetNodeFileOptions struct { + // The caller-generated request identity, in the form of a GUID with no decoration + // such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + ClientRequestID *string + + // A timestamp indicating the last modified time of the resource known to the + // client. The operation will be performed only if the resource on the service has + // been modified since the specified time. + IfModifiedSince *time.Time + + // A timestamp indicating the last modified time of the resource known to the + // client. The operation will be performed only if the resource on the service has + // not been modified since the specified time. + IfUnmodifiedSince *time.Time + + // The byte range to be retrieved. The default is to retrieve the entire file. The + // format is bytes=startRange-endRange. + OcpRange *string + + // The time the request was issued. Client libraries typically set this to the + // current system clock time; set it explicitly if you are calling the REST API + // directly. + Ocpdate *time.Time + + // Whether the server should return the client-request-id in the response. + ReturnClientRequestID *bool + + // The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value + // is larger than 30, the default will be used instead.". + Timeout *int32 +} + +// GetNodeFilePropertiesOptions contains the optional parameters for the Client.GetNodeFileProperties method. +type GetNodeFilePropertiesOptions struct { + // The caller-generated request identity, in the form of a GUID with no decoration + // such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + ClientRequestID *string + + // A timestamp indicating the last modified time of the resource known to the + // client. The operation will be performed only if the resource on the service has + // been modified since the specified time. + IfModifiedSince *time.Time + + // A timestamp indicating the last modified time of the resource known to the + // client. The operation will be performed only if the resource on the service has + // not been modified since the specified time. + IfUnmodifiedSince *time.Time + + // The time the request was issued. Client libraries typically set this to the + // current system clock time; set it explicitly if you are calling the REST API + // directly. + Ocpdate *time.Time + + // Whether the server should return the client-request-id in the response. + ReturnClientRequestID *bool + + // The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value + // is larger than 30, the default will be used instead.". + Timeout *int32 +} + +// GetNodeOptions contains the optional parameters for the Client.GetNode method. +type GetNodeOptions struct { + // The caller-generated request identity, in the form of a GUID with no decoration + // such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + ClientRequestID *string + + // The time the request was issued. Client libraries typically set this to the + // current system clock time; set it explicitly if you are calling the REST API + // directly. + Ocpdate *time.Time + + // Whether the server should return the client-request-id in the response. + ReturnClientRequestID *bool + + // An OData $select clause. + SelectParam []string + + // The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value + // is larger than 30, the default will be used instead.". + Timeout *int32 +} + +// GetNodeRemoteLoginSettingsOptions contains the optional parameters for the Client.GetNodeRemoteLoginSettings method. +type GetNodeRemoteLoginSettingsOptions struct { + // The caller-generated request identity, in the form of a GUID with no decoration + // such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + ClientRequestID *string + + // The time the request was issued. Client libraries typically set this to the + // current system clock time; set it explicitly if you are calling the REST API + // directly. + Ocpdate *time.Time + + // Whether the server should return the client-request-id in the response. + ReturnClientRequestID *bool + + // The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value + // is larger than 30, the default will be used instead.". + Timeout *int32 +} + +// GetPoolOptions contains the optional parameters for the Client.GetPool method. +type GetPoolOptions struct { + // The caller-generated request identity, in the form of a GUID with no decoration + // such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + ClientRequestID *string + + // An OData $expand clause. + Expand []string + + // An ETag value associated with the version of the resource known to the client. + // The operation will be performed only if the resource's current ETag on the + // service exactly matches the value specified by the client. + IfMatch *string + + // A timestamp indicating the last modified time of the resource known to the + // client. The operation will be performed only if the resource on the service has + // been modified since the specified time. + IfModifiedSince *time.Time + + // An ETag value associated with the version of the resource known to the client. + // The operation will be performed only if the resource's current ETag on the + // service does not match the value specified by the client. + IfNoneMatch *string + + // A timestamp indicating the last modified time of the resource known to the + // client. The operation will be performed only if the resource on the service has + // not been modified since the specified time. + IfUnmodifiedSince *time.Time + + // The time the request was issued. Client libraries typically set this to the + // current system clock time; set it explicitly if you are calling the REST API + // directly. + Ocpdate *time.Time + + // Whether the server should return the client-request-id in the response. + ReturnClientRequestID *bool + + // An OData $select clause. + SelectParam []string + + // The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value + // is larger than 30, the default will be used instead.". + Timeout *int32 +} + +// GetTaskFileOptions contains the optional parameters for the Client.GetTaskFile method. +type GetTaskFileOptions struct { + // The caller-generated request identity, in the form of a GUID with no decoration + // such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + ClientRequestID *string + + // A timestamp indicating the last modified time of the resource known to the + // client. The operation will be performed only if the resource on the service has + // been modified since the specified time. + IfModifiedSince *time.Time + + // A timestamp indicating the last modified time of the resource known to the + // client. The operation will be performed only if the resource on the service has + // not been modified since the specified time. + IfUnmodifiedSince *time.Time + + // The byte range to be retrieved. The default is to retrieve the entire file. The + // format is bytes=startRange-endRange. + OcpRange *string + + // The time the request was issued. Client libraries typically set this to the + // current system clock time; set it explicitly if you are calling the REST API + // directly. + Ocpdate *time.Time + + // Whether the server should return the client-request-id in the response. + ReturnClientRequestID *bool + + // The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value + // is larger than 30, the default will be used instead.". + Timeout *int32 +} + +// GetTaskFilePropertiesOptions contains the optional parameters for the Client.GetTaskFileProperties method. +type GetTaskFilePropertiesOptions struct { + // The caller-generated request identity, in the form of a GUID with no decoration + // such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + ClientRequestID *string + + // A timestamp indicating the last modified time of the resource known to the + // client. The operation will be performed only if the resource on the service has + // been modified since the specified time. + IfModifiedSince *time.Time + + // A timestamp indicating the last modified time of the resource known to the + // client. The operation will be performed only if the resource on the service has + // not been modified since the specified time. + IfUnmodifiedSince *time.Time + + // The time the request was issued. Client libraries typically set this to the + // current system clock time; set it explicitly if you are calling the REST API + // directly. + Ocpdate *time.Time + + // Whether the server should return the client-request-id in the response. + ReturnClientRequestID *bool + + // The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value + // is larger than 30, the default will be used instead.". + Timeout *int32 +} + +// GetTaskOptions contains the optional parameters for the Client.GetTask method. +type GetTaskOptions struct { + // The caller-generated request identity, in the form of a GUID with no decoration + // such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + ClientRequestID *string + + // An OData $expand clause. + Expand []string + + // An ETag value associated with the version of the resource known to the client. + // The operation will be performed only if the resource's current ETag on the + // service exactly matches the value specified by the client. + IfMatch *string + + // A timestamp indicating the last modified time of the resource known to the + // client. The operation will be performed only if the resource on the service has + // been modified since the specified time. + IfModifiedSince *time.Time + + // An ETag value associated with the version of the resource known to the client. + // The operation will be performed only if the resource's current ETag on the + // service does not match the value specified by the client. + IfNoneMatch *string + + // A timestamp indicating the last modified time of the resource known to the + // client. The operation will be performed only if the resource on the service has + // not been modified since the specified time. + IfUnmodifiedSince *time.Time + + // The time the request was issued. Client libraries typically set this to the + // current system clock time; set it explicitly if you are calling the REST API + // directly. + Ocpdate *time.Time + + // Whether the server should return the client-request-id in the response. + ReturnClientRequestID *bool + + // An OData $select clause. + SelectParam []string + + // The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value + // is larger than 30, the default will be used instead.". + Timeout *int32 +} + +// JobScheduleExistsOptions contains the optional parameters for the Client.JobScheduleExists method. +type JobScheduleExistsOptions struct { + // The caller-generated request identity, in the form of a GUID with no decoration + // such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + ClientRequestID *string + + // An ETag value associated with the version of the resource known to the client. + // The operation will be performed only if the resource's current ETag on the + // service exactly matches the value specified by the client. + IfMatch *string + + // A timestamp indicating the last modified time of the resource known to the + // client. The operation will be performed only if the resource on the service has + // been modified since the specified time. + IfModifiedSince *time.Time + + // An ETag value associated with the version of the resource known to the client. + // The operation will be performed only if the resource's current ETag on the + // service does not match the value specified by the client. + IfNoneMatch *string + + // A timestamp indicating the last modified time of the resource known to the + // client. The operation will be performed only if the resource on the service has + // not been modified since the specified time. + IfUnmodifiedSince *time.Time + + // The time the request was issued. Client libraries typically set this to the + // current system clock time; set it explicitly if you are calling the REST API + // directly. + Ocpdate *time.Time + + // Whether the server should return the client-request-id in the response. + ReturnClientRequestID *bool + + // The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value + // is larger than 30, the default will be used instead.". + Timeout *int32 +} + +// ListApplicationsOptions contains the optional parameters for the Client.NewListApplicationsPager method. +type ListApplicationsOptions struct { + // The caller-generated request identity, in the form of a GUID with no decoration + // such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + ClientRequestID *string + + // The maximum number of items to return in the response. A maximum of 1000 + // applications can be returned. + MaxResults *int32 + + // The time the request was issued. Client libraries typically set this to the + // current system clock time; set it explicitly if you are calling the REST API + // directly. + Ocpdate *time.Time + + // Whether the server should return the client-request-id in the response. + ReturnClientRequestID *bool + + // The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value + // is larger than 30, the default will be used instead.". + Timeout *int32 +} + +// ListCertificatesOptions contains the optional parameters for the Client.NewListCertificatesPager method. +type ListCertificatesOptions struct { + // The caller-generated request identity, in the form of a GUID with no decoration + // such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + ClientRequestID *string + + // An OData $filter clause. For more information on constructing this filter, see + // https://docs.microsoft.com/en-us/rest/api/batchservice/odata-filters-in-batch#list-certificates. + Filter *string + + // The maximum number of items to return in the response. A maximum of 1000 + // applications can be returned. + MaxResults *int32 + + // The time the request was issued. Client libraries typically set this to the + // current system clock time; set it explicitly if you are calling the REST API + // directly. + Ocpdate *time.Time + + // Whether the server should return the client-request-id in the response. + ReturnClientRequestID *bool + + // An OData $select clause. + SelectParam []string + + // The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value + // is larger than 30, the default will be used instead.". + Timeout *int32 +} + +// ListJobPreparationAndReleaseTaskStatusOptions contains the optional parameters for the Client.NewListJobPreparationAndReleaseTaskStatusPager +// method. +type ListJobPreparationAndReleaseTaskStatusOptions struct { + // The caller-generated request identity, in the form of a GUID with no decoration + // such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + ClientRequestID *string + + // An OData $filter clause. For more information on constructing this filter, see + // https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-job-preparation-and-release-status. + Filter *string + + // The maximum number of items to return in the response. A maximum of 1000 + // applications can be returned. + MaxResults *int32 + + // The time the request was issued. Client libraries typically set this to the + // current system clock time; set it explicitly if you are calling the REST API + // directly. + Ocpdate *time.Time + + // Whether the server should return the client-request-id in the response. + ReturnClientRequestID *bool + + // An OData $select clause. + SelectParam []string + + // The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value + // is larger than 30, the default will be used instead.". + Timeout *int32 +} + +// ListJobSchedulesOptions contains the optional parameters for the Client.NewListJobSchedulesPager method. +type ListJobSchedulesOptions struct { + // The caller-generated request identity, in the form of a GUID with no decoration + // such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + ClientRequestID *string + + // An OData $expand clause. + Expand []string + + // An OData $filter clause. For more information on constructing this filter, see + // https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-job-schedules. + Filter *string + + // The maximum number of items to return in the response. A maximum of 1000 + // applications can be returned. + MaxResults *int32 + + // The time the request was issued. Client libraries typically set this to the + // current system clock time; set it explicitly if you are calling the REST API + // directly. + Ocpdate *time.Time + + // Whether the server should return the client-request-id in the response. + ReturnClientRequestID *bool + + // An OData $select clause. + SelectParam []string + + // The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value + // is larger than 30, the default will be used instead.". + Timeout *int32 +} + +// ListJobsFromScheduleOptions contains the optional parameters for the Client.NewListJobsFromSchedulePager method. +type ListJobsFromScheduleOptions struct { + // The caller-generated request identity, in the form of a GUID with no decoration + // such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + ClientRequestID *string + + // An OData $expand clause. + Expand []string + + // An OData $filter clause. For more information on constructing this filter, see + // https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-jobs-in-a-job-schedule. + Filter *string + + // The maximum number of items to return in the response. A maximum of 1000 + // applications can be returned. + MaxResults *int32 + + // The time the request was issued. Client libraries typically set this to the + // current system clock time; set it explicitly if you are calling the REST API + // directly. + Ocpdate *time.Time + + // Whether the server should return the client-request-id in the response. + ReturnClientRequestID *bool + + // An OData $select clause. + SelectParam []string + + // The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value + // is larger than 30, the default will be used instead.". + Timeout *int32 +} + +// ListJobsOptions contains the optional parameters for the Client.NewListJobsPager method. +type ListJobsOptions struct { + // The caller-generated request identity, in the form of a GUID with no decoration + // such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + ClientRequestID *string + + // An OData $expand clause. + Expand []string + + // An OData $filter clause. For more information on constructing this filter, see + // https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-jobs. + Filter *string + + // The maximum number of items to return in the response. A maximum of 1000 + // applications can be returned. + MaxResults *int32 + + // The time the request was issued. Client libraries typically set this to the + // current system clock time; set it explicitly if you are calling the REST API + // directly. + Ocpdate *time.Time + + // Whether the server should return the client-request-id in the response. + ReturnClientRequestID *bool + + // An OData $select clause. + SelectParam []string + + // The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value + // is larger than 30, the default will be used instead.". + Timeout *int32 +} + +// ListNodeExtensionsOptions contains the optional parameters for the Client.NewListNodeExtensionsPager method. +type ListNodeExtensionsOptions struct { + // The caller-generated request identity, in the form of a GUID with no decoration + // such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + ClientRequestID *string + + // The maximum number of items to return in the response. A maximum of 1000 + // applications can be returned. + MaxResults *int32 + + // The time the request was issued. Client libraries typically set this to the + // current system clock time; set it explicitly if you are calling the REST API + // directly. + Ocpdate *time.Time + + // Whether the server should return the client-request-id in the response. + ReturnClientRequestID *bool + + // An OData $select clause. + SelectParam []string + + // The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value + // is larger than 30, the default will be used instead.". + Timeout *int32 +} + +// ListNodeFilesOptions contains the optional parameters for the Client.NewListNodeFilesPager method. +type ListNodeFilesOptions struct { + // The caller-generated request identity, in the form of a GUID with no decoration + // such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + ClientRequestID *string + + // An OData $filter clause. For more information on constructing this filter, see + // https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-compute-node-files. + Filter *string + + // The maximum number of items to return in the response. A maximum of 1000 + // applications can be returned. + MaxResults *int32 + + // The time the request was issued. Client libraries typically set this to the + // current system clock time; set it explicitly if you are calling the REST API + // directly. + Ocpdate *time.Time + + // Whether to list children of a directory. + Recursive *bool + + // Whether the server should return the client-request-id in the response. + ReturnClientRequestID *bool + + // The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value + // is larger than 30, the default will be used instead.". + Timeout *int32 +} + +// ListNodesOptions contains the optional parameters for the Client.NewListNodesPager method. +type ListNodesOptions struct { + // The caller-generated request identity, in the form of a GUID with no decoration + // such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + ClientRequestID *string + + // An OData $filter clause. For more information on constructing this filter, see + // https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-nodes-in-a-pool. + Filter *string + + // The maximum number of items to return in the response. A maximum of 1000 + // applications can be returned. + MaxResults *int32 + + // The time the request was issued. Client libraries typically set this to the + // current system clock time; set it explicitly if you are calling the REST API + // directly. + Ocpdate *time.Time + + // Whether the server should return the client-request-id in the response. + ReturnClientRequestID *bool + + // An OData $select clause. + SelectParam []string + + // The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value + // is larger than 30, the default will be used instead.". + Timeout *int32 +} + +// ListPoolNodeCountsOptions contains the optional parameters for the Client.NewListPoolNodeCountsPager method. +type ListPoolNodeCountsOptions struct { + // The caller-generated request identity, in the form of a GUID with no decoration + // such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + ClientRequestID *string + + // An OData $filter clause. For more information on constructing this filter, see + // https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-support-images. + Filter *string + + // The maximum number of items to return in the response. A maximum of 1000 + // applications can be returned. + MaxResults *int32 + + // The time the request was issued. Client libraries typically set this to the + // current system clock time; set it explicitly if you are calling the REST API + // directly. + Ocpdate *time.Time + + // Whether the server should return the client-request-id in the response. + ReturnClientRequestID *bool + + // The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value + // is larger than 30, the default will be used instead.". + Timeout *int32 +} + +// ListPoolsOptions contains the optional parameters for the Client.NewListPoolsPager method. +type ListPoolsOptions struct { + // The caller-generated request identity, in the form of a GUID with no decoration + // such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + ClientRequestID *string + + // An OData $expand clause. + Expand []string + + // An OData $filter clause. For more information on constructing this filter, see + // https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-pools. + Filter *string + + // The maximum number of items to return in the response. A maximum of 1000 + // applications can be returned. + MaxResults *int32 + + // The time the request was issued. Client libraries typically set this to the + // current system clock time; set it explicitly if you are calling the REST API + // directly. + Ocpdate *time.Time + + // Whether the server should return the client-request-id in the response. + ReturnClientRequestID *bool + + // An OData $select clause. + SelectParam []string + + // The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value + // is larger than 30, the default will be used instead.". + Timeout *int32 +} + +// ListSubTasksOptions contains the optional parameters for the Client.NewListSubTasksPager method. +type ListSubTasksOptions struct { + // The caller-generated request identity, in the form of a GUID with no decoration + // such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + ClientRequestID *string + + // The time the request was issued. Client libraries typically set this to the + // current system clock time; set it explicitly if you are calling the REST API + // directly. + Ocpdate *time.Time + + // Whether the server should return the client-request-id in the response. + ReturnClientRequestID *bool + + // An OData $select clause. + SelectParam []string + + // The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value + // is larger than 30, the default will be used instead.". + Timeout *int32 +} + +// ListSupportedImagesOptions contains the optional parameters for the Client.NewListSupportedImagesPager method. +type ListSupportedImagesOptions struct { + // The caller-generated request identity, in the form of a GUID with no decoration + // such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + ClientRequestID *string + + // An OData $filter clause. For more information on constructing this filter, see + // https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-support-images. + Filter *string + + // The maximum number of items to return in the response. A maximum of 1000 + // applications can be returned. + MaxResults *int32 + + // The time the request was issued. Client libraries typically set this to the + // current system clock time; set it explicitly if you are calling the REST API + // directly. + Ocpdate *time.Time + + // Whether the server should return the client-request-id in the response. + ReturnClientRequestID *bool + + // The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value + // is larger than 30, the default will be used instead.". + Timeout *int32 +} + +// ListTaskFilesOptions contains the optional parameters for the Client.NewListTaskFilesPager method. +type ListTaskFilesOptions struct { + // The caller-generated request identity, in the form of a GUID with no decoration + // such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + ClientRequestID *string + + // An OData $filter clause. For more information on constructing this filter, see + // https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-task-files. + Filter *string + + // The maximum number of items to return in the response. A maximum of 1000 + // applications can be returned. + MaxResults *int32 + + // The time the request was issued. Client libraries typically set this to the + // current system clock time; set it explicitly if you are calling the REST API + // directly. + Ocpdate *time.Time + + // Whether to list children of the Task directory. This parameter can be used in + // combination with the filter parameter to list specific type of files. + Recursive *bool + + // Whether the server should return the client-request-id in the response. + ReturnClientRequestID *bool + + // The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value + // is larger than 30, the default will be used instead.". + Timeout *int32 +} + +// ListTasksOptions contains the optional parameters for the Client.NewListTasksPager method. +type ListTasksOptions struct { + // The caller-generated request identity, in the form of a GUID with no decoration + // such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + ClientRequestID *string + + // An OData $expand clause. + Expand []string + + // An OData $filter clause. For more information on constructing this filter, see + // https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-tasks. + Filter *string + + // The maximum number of items to return in the response. A maximum of 1000 + // applications can be returned. + MaxResults *int32 + + // The time the request was issued. Client libraries typically set this to the + // current system clock time; set it explicitly if you are calling the REST API + // directly. + Ocpdate *time.Time + + // Whether the server should return the client-request-id in the response. + ReturnClientRequestID *bool + + // An OData $select clause. + SelectParam []string + + // The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value + // is larger than 30, the default will be used instead.". + Timeout *int32 +} + +// PoolExistsOptions contains the optional parameters for the Client.PoolExists method. +type PoolExistsOptions struct { + // The caller-generated request identity, in the form of a GUID with no decoration + // such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + ClientRequestID *string + + // An ETag value associated with the version of the resource known to the client. + // The operation will be performed only if the resource's current ETag on the + // service exactly matches the value specified by the client. + IfMatch *string + + // A timestamp indicating the last modified time of the resource known to the + // client. The operation will be performed only if the resource on the service has + // been modified since the specified time. + IfModifiedSince *time.Time + + // An ETag value associated with the version of the resource known to the client. + // The operation will be performed only if the resource's current ETag on the + // service does not match the value specified by the client. + IfNoneMatch *string + + // A timestamp indicating the last modified time of the resource known to the + // client. The operation will be performed only if the resource on the service has + // not been modified since the specified time. + IfUnmodifiedSince *time.Time + + // The time the request was issued. Client libraries typically set this to the + // current system clock time; set it explicitly if you are calling the REST API + // directly. + Ocpdate *time.Time + + // Whether the server should return the client-request-id in the response. + ReturnClientRequestID *bool + + // The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value + // is larger than 30, the default will be used instead.". + Timeout *int32 +} + +// ReactivateTaskOptions contains the optional parameters for the Client.ReactivateTask method. +type ReactivateTaskOptions struct { + // The caller-generated request identity, in the form of a GUID with no decoration + // such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + ClientRequestID *string + + // An ETag value associated with the version of the resource known to the client. + // The operation will be performed only if the resource's current ETag on the + // service exactly matches the value specified by the client. + IfMatch *string + + // A timestamp indicating the last modified time of the resource known to the + // client. The operation will be performed only if the resource on the service has + // been modified since the specified time. + IfModifiedSince *time.Time + + // An ETag value associated with the version of the resource known to the client. + // The operation will be performed only if the resource's current ETag on the + // service does not match the value specified by the client. + IfNoneMatch *string + + // A timestamp indicating the last modified time of the resource known to the + // client. The operation will be performed only if the resource on the service has + // not been modified since the specified time. + IfUnmodifiedSince *time.Time + + // The time the request was issued. Client libraries typically set this to the + // current system clock time; set it explicitly if you are calling the REST API + // directly. + Ocpdate *time.Time + + // Whether the server should return the client-request-id in the response. + ReturnClientRequestID *bool + + // The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value + // is larger than 30, the default will be used instead.". + Timeout *int32 +} + +// RebootNodeOptions contains the optional parameters for the Client.RebootNode method. +type RebootNodeOptions struct { + // The caller-generated request identity, in the form of a GUID with no decoration + // such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + ClientRequestID *string + + // The time the request was issued. Client libraries typically set this to the + // current system clock time; set it explicitly if you are calling the REST API + // directly. + Ocpdate *time.Time + + // The options to use for rebooting the Compute Node. + Parameters *RebootNodeContent + + // Whether the server should return the client-request-id in the response. + ReturnClientRequestID *bool + + // The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value + // is larger than 30, the default will be used instead.". + Timeout *int32 +} + +// ReimageNodeOptions contains the optional parameters for the Client.ReimageNode method. +type ReimageNodeOptions struct { + // The caller-generated request identity, in the form of a GUID with no decoration + // such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + ClientRequestID *string + + // The time the request was issued. Client libraries typically set this to the + // current system clock time; set it explicitly if you are calling the REST API + // directly. + Ocpdate *time.Time + + // The options to use for reimaging the Compute Node. + Parameters *ReimageNodeContent + + // Whether the server should return the client-request-id in the response. + ReturnClientRequestID *bool + + // The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value + // is larger than 30, the default will be used instead.". + Timeout *int32 +} + +// RemoveNodesOptions contains the optional parameters for the Client.RemoveNodes method. +type RemoveNodesOptions struct { + // The caller-generated request identity, in the form of a GUID with no decoration + // such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + ClientRequestID *string + + // An ETag value associated with the version of the resource known to the client. + // The operation will be performed only if the resource's current ETag on the + // service exactly matches the value specified by the client. + IfMatch *string + + // A timestamp indicating the last modified time of the resource known to the + // client. The operation will be performed only if the resource on the service has + // been modified since the specified time. + IfModifiedSince *time.Time + + // An ETag value associated with the version of the resource known to the client. + // The operation will be performed only if the resource's current ETag on the + // service does not match the value specified by the client. + IfNoneMatch *string + + // A timestamp indicating the last modified time of the resource known to the + // client. The operation will be performed only if the resource on the service has + // not been modified since the specified time. + IfUnmodifiedSince *time.Time + + // The time the request was issued. Client libraries typically set this to the + // current system clock time; set it explicitly if you are calling the REST API + // directly. + Ocpdate *time.Time + + // Whether the server should return the client-request-id in the response. + ReturnClientRequestID *bool + + // The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value + // is larger than 30, the default will be used instead.". + Timeout *int32 +} + +// ReplaceJobOptions contains the optional parameters for the Client.ReplaceJob method. +type ReplaceJobOptions struct { + // The caller-generated request identity, in the form of a GUID with no decoration + // such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + ClientRequestID *string + + // An ETag value associated with the version of the resource known to the client. + // The operation will be performed only if the resource's current ETag on the + // service exactly matches the value specified by the client. + IfMatch *string + + // A timestamp indicating the last modified time of the resource known to the + // client. The operation will be performed only if the resource on the service has + // been modified since the specified time. + IfModifiedSince *time.Time + + // An ETag value associated with the version of the resource known to the client. + // The operation will be performed only if the resource's current ETag on the + // service does not match the value specified by the client. + IfNoneMatch *string + + // A timestamp indicating the last modified time of the resource known to the + // client. The operation will be performed only if the resource on the service has + // not been modified since the specified time. + IfUnmodifiedSince *time.Time + + // The time the request was issued. Client libraries typically set this to the + // current system clock time; set it explicitly if you are calling the REST API + // directly. + Ocpdate *time.Time + + // Whether the server should return the client-request-id in the response. + ReturnClientRequestID *bool + + // The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value + // is larger than 30, the default will be used instead.". + Timeout *int32 +} + +// ReplaceJobScheduleOptions contains the optional parameters for the Client.ReplaceJobSchedule method. +type ReplaceJobScheduleOptions struct { + // The caller-generated request identity, in the form of a GUID with no decoration + // such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + ClientRequestID *string + + // An ETag value associated with the version of the resource known to the client. + // The operation will be performed only if the resource's current ETag on the + // service exactly matches the value specified by the client. + IfMatch *string + + // A timestamp indicating the last modified time of the resource known to the + // client. The operation will be performed only if the resource on the service has + // been modified since the specified time. + IfModifiedSince *time.Time + + // An ETag value associated with the version of the resource known to the client. + // The operation will be performed only if the resource's current ETag on the + // service does not match the value specified by the client. + IfNoneMatch *string + + // A timestamp indicating the last modified time of the resource known to the + // client. The operation will be performed only if the resource on the service has + // not been modified since the specified time. + IfUnmodifiedSince *time.Time + + // The time the request was issued. Client libraries typically set this to the + // current system clock time; set it explicitly if you are calling the REST API + // directly. + Ocpdate *time.Time + + // Whether the server should return the client-request-id in the response. + ReturnClientRequestID *bool + + // The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value + // is larger than 30, the default will be used instead.". + Timeout *int32 +} + +// ReplaceNodeUserOptions contains the optional parameters for the Client.ReplaceNodeUser method. +type ReplaceNodeUserOptions struct { + // The caller-generated request identity, in the form of a GUID with no decoration + // such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + ClientRequestID *string + + // The time the request was issued. Client libraries typically set this to the + // current system clock time; set it explicitly if you are calling the REST API + // directly. + Ocpdate *time.Time + + // Whether the server should return the client-request-id in the response. + ReturnClientRequestID *bool + + // The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value + // is larger than 30, the default will be used instead.". + Timeout *int32 +} + +// ReplacePoolPropertiesOptions contains the optional parameters for the Client.ReplacePoolProperties method. +type ReplacePoolPropertiesOptions struct { + // The caller-generated request identity, in the form of a GUID with no decoration + // such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + ClientRequestID *string + + // The time the request was issued. Client libraries typically set this to the + // current system clock time; set it explicitly if you are calling the REST API + // directly. + Ocpdate *time.Time + + // Whether the server should return the client-request-id in the response. + ReturnClientRequestID *bool + + // The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value + // is larger than 30, the default will be used instead.". + Timeout *int32 +} + +// ReplaceTaskOptions contains the optional parameters for the Client.ReplaceTask method. +type ReplaceTaskOptions struct { + // The caller-generated request identity, in the form of a GUID with no decoration + // such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + ClientRequestID *string + + // An ETag value associated with the version of the resource known to the client. + // The operation will be performed only if the resource's current ETag on the + // service exactly matches the value specified by the client. + IfMatch *string + + // A timestamp indicating the last modified time of the resource known to the + // client. The operation will be performed only if the resource on the service has + // been modified since the specified time. + IfModifiedSince *time.Time + + // An ETag value associated with the version of the resource known to the client. + // The operation will be performed only if the resource's current ETag on the + // service does not match the value specified by the client. + IfNoneMatch *string + + // A timestamp indicating the last modified time of the resource known to the + // client. The operation will be performed only if the resource on the service has + // not been modified since the specified time. + IfUnmodifiedSince *time.Time + + // The time the request was issued. Client libraries typically set this to the + // current system clock time; set it explicitly if you are calling the REST API + // directly. + Ocpdate *time.Time + + // Whether the server should return the client-request-id in the response. + ReturnClientRequestID *bool + + // The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value + // is larger than 30, the default will be used instead.". + Timeout *int32 +} + +// ResizePoolOptions contains the optional parameters for the Client.ResizePool method. +type ResizePoolOptions struct { + // The caller-generated request identity, in the form of a GUID with no decoration + // such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + ClientRequestID *string + + // An ETag value associated with the version of the resource known to the client. + // The operation will be performed only if the resource's current ETag on the + // service exactly matches the value specified by the client. + IfMatch *string + + // A timestamp indicating the last modified time of the resource known to the + // client. The operation will be performed only if the resource on the service has + // been modified since the specified time. + IfModifiedSince *time.Time + + // An ETag value associated with the version of the resource known to the client. + // The operation will be performed only if the resource's current ETag on the + // service does not match the value specified by the client. + IfNoneMatch *string + + // A timestamp indicating the last modified time of the resource known to the + // client. The operation will be performed only if the resource on the service has + // not been modified since the specified time. + IfUnmodifiedSince *time.Time + + // The time the request was issued. Client libraries typically set this to the + // current system clock time; set it explicitly if you are calling the REST API + // directly. + Ocpdate *time.Time + + // Whether the server should return the client-request-id in the response. + ReturnClientRequestID *bool + + // The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value + // is larger than 30, the default will be used instead.". + Timeout *int32 +} + +// StartNodeOptions contains the optional parameters for the Client.StartNode method. +type StartNodeOptions struct { + // The caller-generated request identity, in the form of a GUID with no decoration + // such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + ClientRequestID *string + + // The time the request was issued. Client libraries typically set this to the + // current system clock time; set it explicitly if you are calling the REST API + // directly. + Ocpdate *time.Time + + // Whether the server should return the client-request-id in the response. + ReturnClientRequestID *bool + + // The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value + // is larger than 30, the default will be used instead.". + Timeout *int32 +} + +// StopPoolResizeOptions contains the optional parameters for the Client.StopPoolResize method. +type StopPoolResizeOptions struct { + // The caller-generated request identity, in the form of a GUID with no decoration + // such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + ClientRequestID *string + + // An ETag value associated with the version of the resource known to the client. + // The operation will be performed only if the resource's current ETag on the + // service exactly matches the value specified by the client. + IfMatch *string + + // A timestamp indicating the last modified time of the resource known to the + // client. The operation will be performed only if the resource on the service has + // been modified since the specified time. + IfModifiedSince *time.Time + + // An ETag value associated with the version of the resource known to the client. + // The operation will be performed only if the resource's current ETag on the + // service does not match the value specified by the client. + IfNoneMatch *string + + // A timestamp indicating the last modified time of the resource known to the + // client. The operation will be performed only if the resource on the service has + // not been modified since the specified time. + IfUnmodifiedSince *time.Time + + // The time the request was issued. Client libraries typically set this to the + // current system clock time; set it explicitly if you are calling the REST API + // directly. + Ocpdate *time.Time + + // Whether the server should return the client-request-id in the response. + ReturnClientRequestID *bool + + // The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value + // is larger than 30, the default will be used instead.". + Timeout *int32 +} + +// TerminateJobOptions contains the optional parameters for the Client.TerminateJob method. +type TerminateJobOptions struct { + // The caller-generated request identity, in the form of a GUID with no decoration + // such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + ClientRequestID *string + + // If true, the server will terminate the Job even if the corresponding nodes have not fully processed the termination. The + // default value is false. + Force *bool + + // An ETag value associated with the version of the resource known to the client. + // The operation will be performed only if the resource's current ETag on the + // service exactly matches the value specified by the client. + IfMatch *string + + // A timestamp indicating the last modified time of the resource known to the + // client. The operation will be performed only if the resource on the service has + // been modified since the specified time. + IfModifiedSince *time.Time + + // An ETag value associated with the version of the resource known to the client. + // The operation will be performed only if the resource's current ETag on the + // service does not match the value specified by the client. + IfNoneMatch *string + + // A timestamp indicating the last modified time of the resource known to the + // client. The operation will be performed only if the resource on the service has + // not been modified since the specified time. + IfUnmodifiedSince *time.Time + + // The time the request was issued. Client libraries typically set this to the + // current system clock time; set it explicitly if you are calling the REST API + // directly. + Ocpdate *time.Time + + // The options to use for terminating the Job. + Parameters *TerminateJobContent + + // Whether the server should return the client-request-id in the response. + ReturnClientRequestID *bool + + // The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value + // is larger than 30, the default will be used instead.". + Timeout *int32 +} + +// TerminateJobScheduleOptions contains the optional parameters for the Client.TerminateJobSchedule method. +type TerminateJobScheduleOptions struct { + // The caller-generated request identity, in the form of a GUID with no decoration + // such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + ClientRequestID *string + + // If true, the server will terminate the JobSchedule even if the corresponding nodes have not fully processed the termination. + // The default value is false. + Force *bool + + // An ETag value associated with the version of the resource known to the client. + // The operation will be performed only if the resource's current ETag on the + // service exactly matches the value specified by the client. + IfMatch *string + + // A timestamp indicating the last modified time of the resource known to the + // client. The operation will be performed only if the resource on the service has + // been modified since the specified time. + IfModifiedSince *time.Time + + // An ETag value associated with the version of the resource known to the client. + // The operation will be performed only if the resource's current ETag on the + // service does not match the value specified by the client. + IfNoneMatch *string + + // A timestamp indicating the last modified time of the resource known to the + // client. The operation will be performed only if the resource on the service has + // not been modified since the specified time. + IfUnmodifiedSince *time.Time + + // The time the request was issued. Client libraries typically set this to the + // current system clock time; set it explicitly if you are calling the REST API + // directly. + Ocpdate *time.Time + + // Whether the server should return the client-request-id in the response. + ReturnClientRequestID *bool + + // The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value + // is larger than 30, the default will be used instead.". + Timeout *int32 +} + +// TerminateTaskOptions contains the optional parameters for the Client.TerminateTask method. +type TerminateTaskOptions struct { + // The caller-generated request identity, in the form of a GUID with no decoration + // such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + ClientRequestID *string + + // An ETag value associated with the version of the resource known to the client. + // The operation will be performed only if the resource's current ETag on the + // service exactly matches the value specified by the client. + IfMatch *string + + // A timestamp indicating the last modified time of the resource known to the + // client. The operation will be performed only if the resource on the service has + // been modified since the specified time. + IfModifiedSince *time.Time + + // An ETag value associated with the version of the resource known to the client. + // The operation will be performed only if the resource's current ETag on the + // service does not match the value specified by the client. + IfNoneMatch *string + + // A timestamp indicating the last modified time of the resource known to the + // client. The operation will be performed only if the resource on the service has + // not been modified since the specified time. + IfUnmodifiedSince *time.Time + + // The time the request was issued. Client libraries typically set this to the + // current system clock time; set it explicitly if you are calling the REST API + // directly. + Ocpdate *time.Time + + // Whether the server should return the client-request-id in the response. + ReturnClientRequestID *bool + + // The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value + // is larger than 30, the default will be used instead.". + Timeout *int32 +} + +// UpdateJobOptions contains the optional parameters for the Client.UpdateJob method. +type UpdateJobOptions struct { + // The caller-generated request identity, in the form of a GUID with no decoration + // such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + ClientRequestID *string + + // An ETag value associated with the version of the resource known to the client. + // The operation will be performed only if the resource's current ETag on the + // service exactly matches the value specified by the client. + IfMatch *string + + // A timestamp indicating the last modified time of the resource known to the + // client. The operation will be performed only if the resource on the service has + // been modified since the specified time. + IfModifiedSince *time.Time + + // An ETag value associated with the version of the resource known to the client. + // The operation will be performed only if the resource's current ETag on the + // service does not match the value specified by the client. + IfNoneMatch *string + + // A timestamp indicating the last modified time of the resource known to the + // client. The operation will be performed only if the resource on the service has + // not been modified since the specified time. + IfUnmodifiedSince *time.Time + + // The time the request was issued. Client libraries typically set this to the + // current system clock time; set it explicitly if you are calling the REST API + // directly. + Ocpdate *time.Time + + // Whether the server should return the client-request-id in the response. + ReturnClientRequestID *bool + + // The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value + // is larger than 30, the default will be used instead.". + Timeout *int32 +} + +// UpdateJobScheduleOptions contains the optional parameters for the Client.UpdateJobSchedule method. +type UpdateJobScheduleOptions struct { + // The caller-generated request identity, in the form of a GUID with no decoration + // such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + ClientRequestID *string + + // An ETag value associated with the version of the resource known to the client. + // The operation will be performed only if the resource's current ETag on the + // service exactly matches the value specified by the client. + IfMatch *string + + // A timestamp indicating the last modified time of the resource known to the + // client. The operation will be performed only if the resource on the service has + // been modified since the specified time. + IfModifiedSince *time.Time + + // An ETag value associated with the version of the resource known to the client. + // The operation will be performed only if the resource's current ETag on the + // service does not match the value specified by the client. + IfNoneMatch *string + + // A timestamp indicating the last modified time of the resource known to the + // client. The operation will be performed only if the resource on the service has + // not been modified since the specified time. + IfUnmodifiedSince *time.Time + + // The time the request was issued. Client libraries typically set this to the + // current system clock time; set it explicitly if you are calling the REST API + // directly. + Ocpdate *time.Time + + // Whether the server should return the client-request-id in the response. + ReturnClientRequestID *bool + + // The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value + // is larger than 30, the default will be used instead.". + Timeout *int32 +} + +// UpdatePoolOptions contains the optional parameters for the Client.UpdatePool method. +type UpdatePoolOptions struct { + // The caller-generated request identity, in the form of a GUID with no decoration + // such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + ClientRequestID *string + + // An ETag value associated with the version of the resource known to the client. + // The operation will be performed only if the resource's current ETag on the + // service exactly matches the value specified by the client. + IfMatch *string + + // A timestamp indicating the last modified time of the resource known to the + // client. The operation will be performed only if the resource on the service has + // been modified since the specified time. + IfModifiedSince *time.Time + + // An ETag value associated with the version of the resource known to the client. + // The operation will be performed only if the resource's current ETag on the + // service does not match the value specified by the client. + IfNoneMatch *string + + // A timestamp indicating the last modified time of the resource known to the + // client. The operation will be performed only if the resource on the service has + // not been modified since the specified time. + IfUnmodifiedSince *time.Time + + // The time the request was issued. Client libraries typically set this to the + // current system clock time; set it explicitly if you are calling the REST API + // directly. + Ocpdate *time.Time + + // Whether the server should return the client-request-id in the response. + ReturnClientRequestID *bool + + // The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value + // is larger than 30, the default will be used instead.". + Timeout *int32 +} + +// UploadNodeLogsOptions contains the optional parameters for the Client.UploadNodeLogs method. +type UploadNodeLogsOptions struct { + // The caller-generated request identity, in the form of a GUID with no decoration + // such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + ClientRequestID *string + + // The time the request was issued. Client libraries typically set this to the + // current system clock time; set it explicitly if you are calling the REST API + // directly. + Ocpdate *time.Time + + // Whether the server should return the client-request-id in the response. + ReturnClientRequestID *bool + + // The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value + // is larger than 30, the default will be used instead.". + Timeout *int32 +} + +// listPoolUsageMetricsOptions contains the optional parameters for the Client.NewlistPoolUsageMetricsPager method. +type listPoolUsageMetricsOptions struct { + // The caller-generated request identity, in the form of a GUID with no decoration + // such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + ClientRequestID *string + + // The latest time from which to include metrics. This must be at least two hours + // before the current time. If not specified this defaults to the end time of the + // last aggregation interval currently available. + Endtime *time.Time + + // An OData $filter clause. For more information on constructing this filter, see + // https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-account-usage-metrics. + Filter *string + + // The maximum number of items to return in the response. A maximum of 1000 + // applications can be returned. + MaxResults *int32 + + // The time the request was issued. Client libraries typically set this to the + // current system clock time; set it explicitly if you are calling the REST API + // directly. + Ocpdate *time.Time + + // Whether the server should return the client-request-id in the response. + ReturnClientRequestID *bool + + // The earliest time from which to include metrics. This must be at least two and + // a half hours before the current time. If not specified this defaults to the + // start time of the last aggregation interval currently available. + Starttime *time.Time + + // The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value + // is larger than 30, the default will be used instead.". + Timeout *int32 +} diff --git a/sdk/batch/azbatch/responses.go b/sdk/batch/azbatch/responses.go new file mode 100644 index 000000000000..6c3acd79f25e --- /dev/null +++ b/sdk/batch/azbatch/responses.go @@ -0,0 +1,1851 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package azbatch + +import ( + "io" + "time" +) + +// CancelCertificateDeletionResponse contains the response from method Client.CancelCertificateDeletion. +type CancelCertificateDeletionResponse struct { + // The client-request-id provided by the client during the request. This will be returned only if the return-client-request-id + // parameter was set to true. + ClientRequestID *string + + // The OData ID of the resource to which the request applied. + DataServiceID *string + + // The ETag HTTP response header. This is an opaque string. You can use it to detect whether the resource has changed between + // requests. In particular, you can pass the ETag to one of the If-Modified-Since, If-Unmodified-Since, If-Match or If-None-Match + // headers. + ETag *string + + // The time at which the resource was last modified. + LastModified *time.Time + + // A unique identifier for the request that was made to the Batch service. If a request is consistently failing and you have + // verified that the request is properly formulated, you may use this value to report the error to Microsoft. In your report, + // include the value of this request ID, the approximate time that the request was made, the Batch Account against which the + // request was made, and the region that Account resides in. + RequestID *string +} + +// CreateCertificateResponse contains the response from method Client.CreateCertificate. +type CreateCertificateResponse struct { + // The client-request-id provided by the client during the request. This will be returned only if the return-client-request-id + // parameter was set to true. + ClientRequestID *string + + // The OData ID of the resource to which the request applied. + DataServiceID *string + + // The ETag HTTP response header. This is an opaque string. You can use it to detect whether the resource has changed between + // requests. In particular, you can pass the ETag to one of the If-Modified-Since, If-Unmodified-Since, If-Match or If-None-Match + // headers. + ETag *string + + // The time at which the resource was last modified. + LastModified *time.Time + + // A unique identifier for the request that was made to the Batch service. If a request is consistently failing and you have + // verified that the request is properly formulated, you may use this value to report the error to Microsoft. In your report, + // include the value of this request ID, the approximate time that the request was made, the Batch Account against which the + // request was made, and the region that Account resides in. + RequestID *string +} + +// CreateJobResponse contains the response from method Client.CreateJob. +type CreateJobResponse struct { + // The client-request-id provided by the client during the request. This will be returned only if the return-client-request-id + // parameter was set to true. + ClientRequestID *string + + // The OData ID of the resource to which the request applied. + DataServiceID *string + + // The ETag HTTP response header. This is an opaque string. You can use it to detect whether the resource has changed between + // requests. In particular, you can pass the ETag to one of the If-Modified-Since, If-Unmodified-Since, If-Match or If-None-Match + // headers. + ETag *string + + // The time at which the resource was last modified. + LastModified *time.Time + + // A unique identifier for the request that was made to the Batch service. If a request is consistently failing and you have + // verified that the request is properly formulated, you may use this value to report the error to Microsoft. In your report, + // include the value of this request ID, the approximate time that the request was made, the Batch Account against which the + // request was made, and the region that Account resides in. + RequestID *string +} + +// CreateJobScheduleResponse contains the response from method Client.CreateJobSchedule. +type CreateJobScheduleResponse struct { + // The client-request-id provided by the client during the request. This will be returned only if the return-client-request-id + // parameter was set to true. + ClientRequestID *string + + // The OData ID of the resource to which the request applied. + DataServiceID *string + + // The ETag HTTP response header. This is an opaque string. You can use it to detect whether the resource has changed between + // requests. In particular, you can pass the ETag to one of the If-Modified-Since, If-Unmodified-Since, If-Match or If-None-Match + // headers. + ETag *string + + // The time at which the resource was last modified. + LastModified *time.Time + + // A unique identifier for the request that was made to the Batch service. If a request is consistently failing and you have + // verified that the request is properly formulated, you may use this value to report the error to Microsoft. In your report, + // include the value of this request ID, the approximate time that the request was made, the Batch Account against which the + // request was made, and the region that Account resides in. + RequestID *string +} + +// CreateNodeUserResponse contains the response from method Client.CreateNodeUser. +type CreateNodeUserResponse struct { + // The client-request-id provided by the client during the request. This will be returned only if the return-client-request-id + // parameter was set to true. + ClientRequestID *string + + // The OData ID of the resource to which the request applied. + DataServiceID *string + + // The ETag HTTP response header. This is an opaque string. You can use it to detect whether the resource has changed between + // requests. In particular, you can pass the ETag to one of the If-Modified-Since, If-Unmodified-Since, If-Match or If-None-Match + // headers. + ETag *string + + // The time at which the resource was last modified. + LastModified *time.Time + + // A unique identifier for the request that was made to the Batch service. If a request is consistently failing and you have + // verified that the request is properly formulated, you may use this value to report the error to Microsoft. In your report, + // include the value of this request ID, the approximate time that the request was made, the Batch Account against which the + // request was made, and the region that Account resides in. + RequestID *string +} + +// CreatePoolResponse contains the response from method Client.CreatePool. +type CreatePoolResponse struct { + // The client-request-id provided by the client during the request. This will be returned only if the return-client-request-id + // parameter was set to true. + ClientRequestID *string + + // The OData ID of the resource to which the request applied. + DataServiceID *string + + // The ETag HTTP response header. This is an opaque string. You can use it to detect whether the resource has changed between + // requests. In particular, you can pass the ETag to one of the If-Modified-Since, If-Unmodified-Since, If-Match or If-None-Match + // headers. + ETag *string + + // The time at which the resource was last modified. + LastModified *time.Time + + // A unique identifier for the request that was made to the Batch service. If a request is consistently failing and you have + // verified that the request is properly formulated, you may use this value to report the error to Microsoft. In your report, + // include the value of this request ID, the approximate time that the request was made, the Batch Account against which the + // request was made, and the region that Account resides in. + RequestID *string +} + +// CreateTaskCollectionResponse contains the response from method Client.CreateTaskCollection. +type CreateTaskCollectionResponse struct { + // The result of adding a collection of Tasks to a Job. + AddTaskCollectionResult + + // The client-request-id provided by the client during the request. This will be returned only if the return-client-request-id + // parameter was set to true. + ClientRequestID *string + + // The ETag HTTP response header. This is an opaque string. You can use it to detect whether the resource has changed between + // requests. In particular, you can pass the ETag to one of the If-Modified-Since, If-Unmodified-Since, If-Match or If-None-Match + // headers. + ETag *string + + // The time at which the resource was last modified. + LastModified *time.Time + + // A unique identifier for the request that was made to the Batch service. If a request is consistently failing and you have + // verified that the request is properly formulated, you may use this value to report the error to Microsoft. In your report, + // include the value of this request ID, the approximate time that the request was made, the Batch Account against which the + // request was made, and the region that Account resides in. + RequestID *string +} + +// CreateTaskResponse contains the response from method Client.CreateTask. +type CreateTaskResponse struct { + // The client-request-id provided by the client during the request. This will be returned only if the return-client-request-id + // parameter was set to true. + ClientRequestID *string + + // The OData ID of the resource to which the request applied. + DataServiceID *string + + // The ETag HTTP response header. This is an opaque string. You can use it to detect whether the resource has changed between + // requests. In particular, you can pass the ETag to one of the If-Modified-Since, If-Unmodified-Since, If-Match or If-None-Match + // headers. + ETag *string + + // The time at which the resource was last modified. + LastModified *time.Time + + // A unique identifier for the request that was made to the Batch service. If a request is consistently failing and you have + // verified that the request is properly formulated, you may use this value to report the error to Microsoft. In your report, + // include the value of this request ID, the approximate time that the request was made, the Batch Account against which the + // request was made, and the region that Account resides in. + RequestID *string +} + +// DeallocateNodeResponse contains the response from method Client.DeallocateNode. +type DeallocateNodeResponse struct { + // The client-request-id provided by the client during the request. This will be returned only if the return-client-request-id + // parameter was set to true. + ClientRequestID *string + + // The OData ID of the resource to which the request applied. + DataServiceID *string + + // The ETag HTTP response header. This is an opaque string. You can use it to detect whether the resource has changed between + // requests. In particular, you can pass the ETag to one of the If-Modified-Since, If-Unmodified-Since, If-Match or If-None-Match + // headers. + ETag *string + + // The time at which the resource was last modified. + LastModified *time.Time + + // A unique identifier for the request that was made to the Batch service. If a request is consistently failing and you have + // verified that the request is properly formulated, you may use this value to report the error to Microsoft. In your report, + // include the value of this request ID, the approximate time that the request was made, the Batch Account against which the + // request was made, and the region that Account resides in. + RequestID *string +} + +// DeleteCertificateResponse contains the response from method Client.DeleteCertificate. +type DeleteCertificateResponse struct { + // The client-request-id provided by the client during the request. This will be returned only if the return-client-request-id + // parameter was set to true. + ClientRequestID *string + + // The ETag HTTP response header. This is an opaque string. You can use it to detect whether the resource has changed between + // requests. In particular, you can pass the ETag to one of the If-Modified-Since, If-Unmodified-Since, If-Match or If-None-Match + // headers. + ETag *string + + // The time at which the resource was last modified. + LastModified *time.Time + + // A unique identifier for the request that was made to the Batch service. If a request is consistently failing and you have + // verified that the request is properly formulated, you may use this value to report the error to Microsoft. In your report, + // include the value of this request ID, the approximate time that the request was made, the Batch Account against which the + // request was made, and the region that Account resides in. + RequestID *string +} + +// DeleteJobResponse contains the response from method Client.DeleteJob. +type DeleteJobResponse struct { + // The client-request-id provided by the client during the request. This will be returned only if the return-client-request-id + // parameter was set to true. + ClientRequestID *string + + // A unique identifier for the request that was made to the Batch service. If a request is consistently failing and you have + // verified that the request is properly formulated, you may use this value to report the error to Microsoft. In your report, + // include the value of this request ID, the approximate time that the request was made, the Batch Account against which the + // request was made, and the region that Account resides in. + RequestID *string +} + +// DeleteJobScheduleResponse contains the response from method Client.DeleteJobSchedule. +type DeleteJobScheduleResponse struct { + // The client-request-id provided by the client during the request. This will be returned only if the return-client-request-id + // parameter was set to true. + ClientRequestID *string + + // A unique identifier for the request that was made to the Batch service. If a request is consistently failing and you have + // verified that the request is properly formulated, you may use this value to report the error to Microsoft. In your report, + // include the value of this request ID, the approximate time that the request was made, the Batch Account against which the + // request was made, and the region that Account resides in. + RequestID *string +} + +// DeleteNodeFileResponse contains the response from method Client.DeleteNodeFile. +type DeleteNodeFileResponse struct { + // The client-request-id provided by the client during the request. This will be returned only if the return-client-request-id + // parameter was set to true. + ClientRequestID *string + + // A unique identifier for the request that was made to the Batch service. If a request is consistently failing and you have + // verified that the request is properly formulated, you may use this value to report the error to Microsoft. In your report, + // include the value of this request ID, the approximate time that the request was made, the Batch Account against which the + // request was made, and the region that Account resides in. + RequestID *string +} + +// DeleteNodeUserResponse contains the response from method Client.DeleteNodeUser. +type DeleteNodeUserResponse struct { + // The client-request-id provided by the client during the request. This will be returned only if the return-client-request-id + // parameter was set to true. + ClientRequestID *string + + // A unique identifier for the request that was made to the Batch service. If a request is consistently failing and you have + // verified that the request is properly formulated, you may use this value to report the error to Microsoft. In your report, + // include the value of this request ID, the approximate time that the request was made, the Batch Account against which the + // request was made, and the region that Account resides in. + RequestID *string +} + +// DeletePoolResponse contains the response from method Client.DeletePool. +type DeletePoolResponse struct { + // The client-request-id provided by the client during the request. This will be returned only if the return-client-request-id + // parameter was set to true. + ClientRequestID *string + + // A unique identifier for the request that was made to the Batch service. If a request is consistently failing and you have + // verified that the request is properly formulated, you may use this value to report the error to Microsoft. In your report, + // include the value of this request ID, the approximate time that the request was made, the Batch Account against which the + // request was made, and the region that Account resides in. + RequestID *string +} + +// DeleteTaskFileResponse contains the response from method Client.DeleteTaskFile. +type DeleteTaskFileResponse struct { + // The client-request-id provided by the client during the request. This will be returned only if the return-client-request-id + // parameter was set to true. + ClientRequestID *string + + // A unique identifier for the request that was made to the Batch service. If a request is consistently failing and you have + // verified that the request is properly formulated, you may use this value to report the error to Microsoft. In your report, + // include the value of this request ID, the approximate time that the request was made, the Batch Account against which the + // request was made, and the region that Account resides in. + RequestID *string +} + +// DeleteTaskResponse contains the response from method Client.DeleteTask. +type DeleteTaskResponse struct { + // The client-request-id provided by the client during the request. This will be returned only if the return-client-request-id + // parameter was set to true. + ClientRequestID *string + + // A unique identifier for the request that was made to the Batch service. If a request is consistently failing and you have + // verified that the request is properly formulated, you may use this value to report the error to Microsoft. In your report, + // include the value of this request ID, the approximate time that the request was made, the Batch Account against which the + // request was made, and the region that Account resides in. + RequestID *string +} + +// DisableJobResponse contains the response from method Client.DisableJob. +type DisableJobResponse struct { + // The client-request-id provided by the client during the request. This will be returned only if the return-client-request-id + // parameter was set to true. + ClientRequestID *string + + // The OData ID of the resource to which the request applied. + DataServiceID *string + + // The ETag HTTP response header. This is an opaque string. You can use it to detect whether the resource has changed between + // requests. In particular, you can pass the ETag to one of the If-Modified-Since, If-Unmodified-Since, If-Match or If-None-Match + // headers. + ETag *string + + // The time at which the resource was last modified. + LastModified *time.Time + + // A unique identifier for the request that was made to the Batch service. If a request is consistently failing and you have + // verified that the request is properly formulated, you may use this value to report the error to Microsoft. In your report, + // include the value of this request ID, the approximate time that the request was made, the Batch Account against which the + // request was made, and the region that Account resides in. + RequestID *string +} + +// DisableJobScheduleResponse contains the response from method Client.DisableJobSchedule. +type DisableJobScheduleResponse struct { + // The client-request-id provided by the client during the request. This will be returned only if the return-client-request-id + // parameter was set to true. + ClientRequestID *string + + // The OData ID of the resource to which the request applied. + DataServiceID *string + + // The ETag HTTP response header. This is an opaque string. You can use it to detect whether the resource has changed between + // requests. In particular, you can pass the ETag to one of the If-Modified-Since, If-Unmodified-Since, If-Match or If-None-Match + // headers. + ETag *string + + // The time at which the resource was last modified. + LastModified *time.Time + + // A unique identifier for the request that was made to the Batch service. If a request is consistently failing and you have + // verified that the request is properly formulated, you may use this value to report the error to Microsoft. In your report, + // include the value of this request ID, the approximate time that the request was made, the Batch Account against which the + // request was made, and the region that Account resides in. + RequestID *string +} + +// DisableNodeSchedulingResponse contains the response from method Client.DisableNodeScheduling. +type DisableNodeSchedulingResponse struct { + // The client-request-id provided by the client during the request. This will be returned only if the return-client-request-id + // parameter was set to true. + ClientRequestID *string + + // The OData ID of the resource to which the request applied. + DataServiceID *string + + // The ETag HTTP response header. This is an opaque string. You can use it to detect whether the resource has changed between + // requests. In particular, you can pass the ETag to one of the If-Modified-Since, If-Unmodified-Since, If-Match or If-None-Match + // headers. + ETag *string + + // The time at which the resource was last modified. + LastModified *time.Time + + // A unique identifier for the request that was made to the Batch service. If a request is consistently failing and you have + // verified that the request is properly formulated, you may use this value to report the error to Microsoft. In your report, + // include the value of this request ID, the approximate time that the request was made, the Batch Account against which the + // request was made, and the region that Account resides in. + RequestID *string +} + +// DisablePoolAutoScaleResponse contains the response from method Client.DisablePoolAutoScale. +type DisablePoolAutoScaleResponse struct { + // The client-request-id provided by the client during the request. This will be returned only if the return-client-request-id + // parameter was set to true. + ClientRequestID *string + + // The OData ID of the resource to which the request applied. + DataServiceID *string + + // The ETag HTTP response header. This is an opaque string. You can use it to detect whether the resource has changed between + // requests. In particular, you can pass the ETag to one of the If-Modified-Since, If-Unmodified-Since, If-Match or If-None-Match + // headers. + ETag *string + + // The time at which the resource was last modified. + LastModified *time.Time + + // A unique identifier for the request that was made to the Batch service. If a request is consistently failing and you have + // verified that the request is properly formulated, you may use this value to report the error to Microsoft. In your report, + // include the value of this request ID, the approximate time that the request was made, the Batch Account against which the + // request was made, and the region that Account resides in. + RequestID *string +} + +// EnableJobResponse contains the response from method Client.EnableJob. +type EnableJobResponse struct { + // The client-request-id provided by the client during the request. This will be returned only if the return-client-request-id + // parameter was set to true. + ClientRequestID *string + + // The OData ID of the resource to which the request applied. + DataServiceID *string + + // The ETag HTTP response header. This is an opaque string. You can use it to detect whether the resource has changed between + // requests. In particular, you can pass the ETag to one of the If-Modified-Since, If-Unmodified-Since, If-Match or If-None-Match + // headers. + ETag *string + + // The time at which the resource was last modified. + LastModified *time.Time + + // A unique identifier for the request that was made to the Batch service. If a request is consistently failing and you have + // verified that the request is properly formulated, you may use this value to report the error to Microsoft. In your report, + // include the value of this request ID, the approximate time that the request was made, the Batch Account against which the + // request was made, and the region that Account resides in. + RequestID *string +} + +// EnableJobScheduleResponse contains the response from method Client.EnableJobSchedule. +type EnableJobScheduleResponse struct { + // The client-request-id provided by the client during the request. This will be returned only if the return-client-request-id + // parameter was set to true. + ClientRequestID *string + + // The OData ID of the resource to which the request applied. + DataServiceID *string + + // The ETag HTTP response header. This is an opaque string. You can use it to detect whether the resource has changed between + // requests. In particular, you can pass the ETag to one of the If-Modified-Since, If-Unmodified-Since, If-Match or If-None-Match + // headers. + ETag *string + + // The time at which the resource was last modified. + LastModified *time.Time + + // A unique identifier for the request that was made to the Batch service. If a request is consistently failing and you have + // verified that the request is properly formulated, you may use this value to report the error to Microsoft. In your report, + // include the value of this request ID, the approximate time that the request was made, the Batch Account against which the + // request was made, and the region that Account resides in. + RequestID *string +} + +// EnableNodeSchedulingResponse contains the response from method Client.EnableNodeScheduling. +type EnableNodeSchedulingResponse struct { + // The client-request-id provided by the client during the request. This will be returned only if the return-client-request-id + // parameter was set to true. + ClientRequestID *string + + // The OData ID of the resource to which the request applied. + DataServiceID *string + + // The ETag HTTP response header. This is an opaque string. You can use it to detect whether the resource has changed between + // requests. In particular, you can pass the ETag to one of the If-Modified-Since, If-Unmodified-Since, If-Match or If-None-Match + // headers. + ETag *string + + // The time at which the resource was last modified. + LastModified *time.Time + + // A unique identifier for the request that was made to the Batch service. If a request is consistently failing and you have + // verified that the request is properly formulated, you may use this value to report the error to Microsoft. In your report, + // include the value of this request ID, the approximate time that the request was made, the Batch Account against which the + // request was made, and the region that Account resides in. + RequestID *string +} + +// EnablePoolAutoScaleResponse contains the response from method Client.EnablePoolAutoScale. +type EnablePoolAutoScaleResponse struct { + // The client-request-id provided by the client during the request. This will be returned only if the return-client-request-id + // parameter was set to true. + ClientRequestID *string + + // The OData ID of the resource to which the request applied. + DataServiceID *string + + // The ETag HTTP response header. This is an opaque string. You can use it to detect whether the resource has changed between + // requests. In particular, you can pass the ETag to one of the If-Modified-Since, If-Unmodified-Since, If-Match or If-None-Match + // headers. + ETag *string + + // The time at which the resource was last modified. + LastModified *time.Time + + // A unique identifier for the request that was made to the Batch service. If a request is consistently failing and you have + // verified that the request is properly formulated, you may use this value to report the error to Microsoft. In your report, + // include the value of this request ID, the approximate time that the request was made, the Batch Account against which the + // request was made, and the region that Account resides in. + RequestID *string +} + +// EvaluatePoolAutoScaleResponse contains the response from method Client.EvaluatePoolAutoScale. +type EvaluatePoolAutoScaleResponse struct { + // The results and errors from an execution of a Pool autoscale formula. + AutoScaleRun + + // The client-request-id provided by the client during the request. This will be returned only if the return-client-request-id + // parameter was set to true. + ClientRequestID *string + + // The OData ID of the resource to which the request applied. + DataServiceID *string + + // The ETag HTTP response header. This is an opaque string. You can use it to detect whether the resource has changed between + // requests. In particular, you can pass the ETag to one of the If-Modified-Since, If-Unmodified-Since, If-Match or If-None-Match + // headers. + ETag *string + + // The time at which the resource was last modified. + LastModified *time.Time + + // A unique identifier for the request that was made to the Batch service. If a request is consistently failing and you have + // verified that the request is properly formulated, you may use this value to report the error to Microsoft. In your report, + // include the value of this request ID, the approximate time that the request was made, the Batch Account against which the + // request was made, and the region that Account resides in. + RequestID *string +} + +// GetApplicationResponse contains the response from method Client.GetApplication. +type GetApplicationResponse struct { + // Contains information about an application in an Azure Batch Account. + Application + + // The client-request-id provided by the client during the request. This will be returned only if the return-client-request-id + // parameter was set to true. + ClientRequestID *string + + // The ETag HTTP response header. This is an opaque string. You can use it to detect whether the resource has changed between + // requests. In particular, you can pass the ETag to one of the If-Modified-Since, If-Unmodified-Since, If-Match or If-None-Match + // headers. + ETag *string + + // The time at which the resource was last modified. + LastModified *time.Time + + // A unique identifier for the request that was made to the Batch service. If a request is consistently failing and you have + // verified that the request is properly formulated, you may use this value to report the error to Microsoft. In your report, + // include the value of this request ID, the approximate time that the request was made, the Batch Account against which the + // request was made, and the region that Account resides in. + RequestID *string +} + +// GetCertificateResponse contains the response from method Client.GetCertificate. +type GetCertificateResponse struct { + // A Certificate that can be installed on Compute Nodes and can be used to + // authenticate operations on the machine. + Certificate + + // The client-request-id provided by the client during the request. This will be returned only if the return-client-request-id + // parameter was set to true. + ClientRequestID *string + + // The ETag HTTP response header. This is an opaque string. You can use it to detect whether the resource has changed between + // requests. In particular, you can pass the ETag to one of the If-Modified-Since, If-Unmodified-Since, If-Match or If-None-Match + // headers. + ETag *string + + // The time at which the resource was last modified. + LastModified *time.Time + + // A unique identifier for the request that was made to the Batch service. If a request is consistently failing and you have + // verified that the request is properly formulated, you may use this value to report the error to Microsoft. In your report, + // include the value of this request ID, the approximate time that the request was made, the Batch Account against which the + // request was made, and the region that Account resides in. + RequestID *string +} + +// GetJobResponse contains the response from method Client.GetJob. +type GetJobResponse struct { + // An Azure Batch Job. + Job + + // The client-request-id provided by the client during the request. This will be returned only if the return-client-request-id + // parameter was set to true. + ClientRequestID *string + + // The ETag HTTP response header. This is an opaque string. You can use it to detect whether the resource has changed between + // requests. In particular, you can pass the ETag to one of the If-Modified-Since, If-Unmodified-Since, If-Match or If-None-Match + // headers. + ETag *string + + // The time at which the resource was last modified. + LastModified *time.Time + + // A unique identifier for the request that was made to the Batch service. If a request is consistently failing and you have + // verified that the request is properly formulated, you may use this value to report the error to Microsoft. In your report, + // include the value of this request ID, the approximate time that the request was made, the Batch Account against which the + // request was made, and the region that Account resides in. + RequestID *string +} + +// GetJobScheduleResponse contains the response from method Client.GetJobSchedule. +type GetJobScheduleResponse struct { + // A Job Schedule that allows recurring Jobs by specifying when to run Jobs and a + // specification used to create each Job. + JobSchedule + + // The client-request-id provided by the client during the request. This will be returned only if the return-client-request-id + // parameter was set to true. + ClientRequestID *string + + // The ETag HTTP response header. This is an opaque string. You can use it to detect whether the resource has changed between + // requests. In particular, you can pass the ETag to one of the If-Modified-Since, If-Unmodified-Since, If-Match or If-None-Match + // headers. + ETag *string + + // The time at which the resource was last modified. + LastModified *time.Time + + // A unique identifier for the request that was made to the Batch service. If a request is consistently failing and you have + // verified that the request is properly formulated, you may use this value to report the error to Microsoft. In your report, + // include the value of this request ID, the approximate time that the request was made, the Batch Account against which the + // request was made, and the region that Account resides in. + RequestID *string +} + +// GetJobTaskCountsResponse contains the response from method Client.GetJobTaskCounts. +type GetJobTaskCountsResponse struct { + // The Task and TaskSlot counts for a Job. + TaskCountsResult + + // The client-request-id provided by the client during the request. This will be returned only if the return-client-request-id + // parameter was set to true. + ClientRequestID *string + + // The ETag HTTP response header. This is an opaque string. You can use it to detect whether the resource has changed between + // requests. In particular, you can pass the ETag to one of the If-Modified-Since, If-Unmodified-Since, If-Match or If-None-Match + // headers. + ETag *string + + // The time at which the resource was last modified. + LastModified *time.Time + + // A unique identifier for the request that was made to the Batch service. If a request is consistently failing and you have + // verified that the request is properly formulated, you may use this value to report the error to Microsoft. In your report, + // include the value of this request ID, the approximate time that the request was made, the Batch Account against which the + // request was made, and the region that Account resides in. + RequestID *string +} + +// GetNodeExtensionResponse contains the response from method Client.GetNodeExtension. +type GetNodeExtensionResponse struct { + // The configuration for virtual machine extension instance view. + NodeVMExtension + + // The client-request-id provided by the client during the request. This will be returned only if the return-client-request-id + // parameter was set to true. + ClientRequestID *string + + // The ETag HTTP response header. This is an opaque string. You can use it to detect whether the resource has changed between + // requests. In particular, you can pass the ETag to one of the If-Modified-Since, If-Unmodified-Since, If-Match or If-None-Match + // headers. + ETag *string + + // The time at which the resource was last modified. + LastModified *time.Time + + // A unique identifier for the request that was made to the Batch service. If a request is consistently failing and you have + // verified that the request is properly formulated, you may use this value to report the error to Microsoft. In your report, + // include the value of this request ID, the approximate time that the request was made, the Batch Account against which the + // request was made, and the region that Account resides in. + RequestID *string +} + +// GetNodeFilePropertiesResponse contains the response from method Client.GetNodeFileProperties. +type GetNodeFilePropertiesResponse struct { + // The client-request-id provided by the client during the request. This will be returned only if the return-client-request-id + // parameter was set to true. + ClientRequestID *string + + // The length of the file. + ContentLength *int64 + + // The ETag HTTP response header. This is an opaque string. You can use it to detect whether the resource has changed between + // requests. In particular, you can pass the ETag to one of the If-Modified-Since, If-Unmodified-Since, If-Match or If-None-Match + // headers. + ETag *string + + // The time at which the resource was last modified. + LastModified *time.Time + + // Whether the object represents a directory. + OcpBatchFileIsdirectory *bool + + // The file mode attribute in octal format. + OcpBatchFileMode *string + + // The URL of the file. + OcpBatchFileURL *string + + // The file creation time. + OcpCreationTime *time.Time + + // A unique identifier for the request that was made to the Batch service. If a request is consistently failing and you have + // verified that the request is properly formulated, you may use this value to report the error to Microsoft. In your report, + // include the value of this request ID, the approximate time that the request was made, the Batch Account against which the + // request was made, and the region that Account resides in. + RequestID *string +} + +// GetNodeFileResponse contains the response from method Client.GetNodeFile. +type GetNodeFileResponse struct { + // Body contains the streaming response. + Body io.ReadCloser + + // The client-request-id provided by the client during the request. This will be returned only if the return-client-request-id + // parameter was set to true. + ClientRequestID *string + + // The length of the file. + ContentLength *int64 + + // Type of content + ContentType *string + + // The ETag HTTP response header. This is an opaque string. You can use it to detect whether the resource has changed between + // requests. In particular, you can pass the ETag to one of the If-Modified-Since, If-Unmodified-Since, If-Match or If-None-Match + // headers. + ETag *string + + // The time at which the resource was last modified. + LastModified *time.Time + + // Whether the object represents a directory. + OcpBatchFileIsdirectory *bool + + // The file mode attribute in octal format. + OcpBatchFileMode *string + + // The URL of the file. + OcpBatchFileURL *string + + // The file creation time. + OcpCreationTime *time.Time + + // A unique identifier for the request that was made to the Batch service. If a request is consistently failing and you have + // verified that the request is properly formulated, you may use this value to report the error to Microsoft. In your report, + // include the value of this request ID, the approximate time that the request was made, the Batch Account against which the + // request was made, and the region that Account resides in. + RequestID *string +} + +// GetNodeRemoteLoginSettingsResponse contains the response from method Client.GetNodeRemoteLoginSettings. +type GetNodeRemoteLoginSettingsResponse struct { + // The remote login settings for a Compute Node. + NodeRemoteLoginSettings + + // The client-request-id provided by the client during the request. This will be returned only if the return-client-request-id + // parameter was set to true. + ClientRequestID *string + + // The ETag HTTP response header. This is an opaque string. You can use it to detect whether the resource has changed between + // requests. In particular, you can pass the ETag to one of the If-Modified-Since, If-Unmodified-Since, If-Match or If-None-Match + // headers. + ETag *string + + // The time at which the resource was last modified. + LastModified *time.Time + + // A unique identifier for the request that was made to the Batch service. If a request is consistently failing and you have + // verified that the request is properly formulated, you may use this value to report the error to Microsoft. In your report, + // include the value of this request ID, the approximate time that the request was made, the Batch Account against which the + // request was made, and the region that Account resides in. + RequestID *string +} + +// GetNodeResponse contains the response from method Client.GetNode. +type GetNodeResponse struct { + // A Compute Node in the Batch service. + Node + + // The client-request-id provided by the client during the request. This will be returned only if the return-client-request-id + // parameter was set to true. + ClientRequestID *string + + // The ETag HTTP response header. This is an opaque string. You can use it to detect whether the resource has changed between + // requests. In particular, you can pass the ETag to one of the If-Modified-Since, If-Unmodified-Since, If-Match or If-None-Match + // headers. + ETag *string + + // The time at which the resource was last modified. + LastModified *time.Time + + // A unique identifier for the request that was made to the Batch service. If a request is consistently failing and you have + // verified that the request is properly formulated, you may use this value to report the error to Microsoft. In your report, + // include the value of this request ID, the approximate time that the request was made, the Batch Account against which the + // request was made, and the region that Account resides in. + RequestID *string +} + +// GetPoolResponse contains the response from method Client.GetPool. +type GetPoolResponse struct { + // A Pool in the Azure Batch service. + Pool + + // The client-request-id provided by the client during the request. This will be returned only if the return-client-request-id + // parameter was set to true. + ClientRequestID *string + + // The ETag HTTP response header. This is an opaque string. You can use it to detect whether the resource has changed between + // requests. In particular, you can pass the ETag to one of the If-Modified-Since, If-Unmodified-Since, If-Match or If-None-Match + // headers. + ETag *string + + // The time at which the resource was last modified. + LastModified *time.Time + + // A unique identifier for the request that was made to the Batch service. If a request is consistently failing and you have + // verified that the request is properly formulated, you may use this value to report the error to Microsoft. In your report, + // include the value of this request ID, the approximate time that the request was made, the Batch Account against which the + // request was made, and the region that Account resides in. + RequestID *string +} + +// GetTaskFilePropertiesResponse contains the response from method Client.GetTaskFileProperties. +type GetTaskFilePropertiesResponse struct { + // The client-request-id provided by the client during the request. This will be returned only if the return-client-request-id + // parameter was set to true. + ClientRequestID *string + + // The length of the file. + ContentLength *int64 + + // The ETag HTTP response header. This is an opaque string. You can use it to detect whether the resource has changed between + // requests. In particular, you can pass the ETag to one of the If-Modified-Since, If-Unmodified-Since, If-Match or If-None-Match + // headers. + ETag *string + + // The time at which the resource was last modified. + LastModified *time.Time + + // Whether the object represents a directory. + OcpBatchFileIsdirectory *bool + + // The file mode attribute in octal format. + OcpBatchFileMode *string + + // The URL of the file. + OcpBatchFileURL *string + + // The file creation time. + OcpCreationTime *time.Time + + // A unique identifier for the request that was made to the Batch service. If a request is consistently failing and you have + // verified that the request is properly formulated, you may use this value to report the error to Microsoft. In your report, + // include the value of this request ID, the approximate time that the request was made, the Batch Account against which the + // request was made, and the region that Account resides in. + RequestID *string +} + +// GetTaskFileResponse contains the response from method Client.GetTaskFile. +type GetTaskFileResponse struct { + // Body contains the streaming response. + Body io.ReadCloser + + // The client-request-id provided by the client during the request. This will be returned only if the return-client-request-id + // parameter was set to true. + ClientRequestID *string + + // The length of the file. + ContentLength *int64 + + // Type of content + ContentType *string + + // The ETag HTTP response header. This is an opaque string. You can use it to detect whether the resource has changed between + // requests. In particular, you can pass the ETag to one of the If-Modified-Since, If-Unmodified-Since, If-Match or If-None-Match + // headers. + ETag *string + + // The time at which the resource was last modified. + LastModified *time.Time + + // Whether the object represents a directory. + OcpBatchFileIsdirectory *bool + + // The file mode attribute in octal format. + OcpBatchFileMode *string + + // The URL of the file. + OcpBatchFileURL *string + + // The file creation time. + OcpCreationTime *time.Time + + // A unique identifier for the request that was made to the Batch service. If a request is consistently failing and you have + // verified that the request is properly formulated, you may use this value to report the error to Microsoft. In your report, + // include the value of this request ID, the approximate time that the request was made, the Batch Account against which the + // request was made, and the region that Account resides in. + RequestID *string +} + +// GetTaskResponse contains the response from method Client.GetTask. +type GetTaskResponse struct { + // Batch will retry Tasks when a recovery operation is triggered on a Node. + // Examples of recovery operations include (but are not limited to) when an + // unhealthy Node is rebooted or a Compute Node disappeared due to host failure. + // Retries due to recovery operations are independent of and are not counted + // against the maxTaskRetryCount. Even if the maxTaskRetryCount is 0, an internal + // retry due to a recovery operation may occur. Because of this, all Tasks should + // be idempotent. This means Tasks need to tolerate being interrupted and + // restarted without causing any corruption or duplicate data. The best practice + // for long running Tasks is to use some form of checkpointing. + Task + + // The client-request-id provided by the client during the request. This will be returned only if the return-client-request-id + // parameter was set to true. + ClientRequestID *string + + // The OData ID of the resource to which the request applied. + DataServiceID *string + + // The ETag HTTP response header. This is an opaque string. You can use it to detect whether the resource has changed between + // requests. In particular, you can pass the ETag to one of the If-Modified-Since, If-Unmodified-Since, If-Match or If-None-Match + // headers. + ETag *string + + // The time at which the resource was last modified. + LastModified *time.Time + + // A unique identifier for the request that was made to the Batch service. If a request is consistently failing and you have + // verified that the request is properly formulated, you may use this value to report the error to Microsoft. In your report, + // include the value of this request ID, the approximate time that the request was made, the Batch Account against which the + // request was made, and the region that Account resides in. + RequestID *string +} + +// JobScheduleExistsResponse contains the response from method Client.JobScheduleExists. +type JobScheduleExistsResponse struct { + // The client-request-id provided by the client during the request. This will be returned only if the return-client-request-id + // parameter was set to true. + ClientRequestID *string + + // The ETag HTTP response header. This is an opaque string. You can use it to detect whether the resource has changed between + // requests. In particular, you can pass the ETag to one of the If-Modified-Since, If-Unmodified-Since, If-Match or If-None-Match + // headers. + ETag *string + + // The time at which the resource was last modified. + LastModified *time.Time + + // A unique identifier for the request that was made to the Batch service. If a request is consistently failing and you have + // verified that the request is properly formulated, you may use this value to report the error to Microsoft. In your report, + // include the value of this request ID, the approximate time that the request was made, the Batch Account against which the + // request was made, and the region that Account resides in. + RequestID *string +} + +// ListApplicationsResponse contains the response from method Client.NewListApplicationsPager. +type ListApplicationsResponse struct { + // The result of listing the applications available in an Account. + ApplicationListResult + + // The client-request-id provided by the client during the request. This will be returned only if the return-client-request-id + // parameter was set to true. + ClientRequestID *string + + // The ETag HTTP response header. This is an opaque string. You can use it to detect whether the resource has changed between + // requests. In particular, you can pass the ETag to one of the If-Modified-Since, If-Unmodified-Since, If-Match or If-None-Match + // headers. + ETag *string + + // The time at which the resource was last modified. + LastModified *time.Time + + // A unique identifier for the request that was made to the Batch service. If a request is consistently failing and you have + // verified that the request is properly formulated, you may use this value to report the error to Microsoft. In your report, + // include the value of this request ID, the approximate time that the request was made, the Batch Account against which the + // request was made, and the region that Account resides in. + RequestID *string +} + +// ListCertificatesResponse contains the response from method Client.NewListCertificatesPager. +type ListCertificatesResponse struct { + // The result of listing the Certificates in the Account. + CertificateListResult + + // The client-request-id provided by the client during the request. This will be returned only if the return-client-request-id + // parameter was set to true. + ClientRequestID *string + + // The ETag HTTP response header. This is an opaque string. You can use it to detect whether the resource has changed between + // requests. In particular, you can pass the ETag to one of the If-Modified-Since, If-Unmodified-Since, If-Match or If-None-Match + // headers. + ETag *string + + // The time at which the resource was last modified. + LastModified *time.Time + + // A unique identifier for the request that was made to the Batch service. If a request is consistently failing and you have + // verified that the request is properly formulated, you may use this value to report the error to Microsoft. In your report, + // include the value of this request ID, the approximate time that the request was made, the Batch Account against which the + // request was made, and the region that Account resides in. + RequestID *string +} + +// ListJobPreparationAndReleaseTaskStatusResponse contains the response from method Client.NewListJobPreparationAndReleaseTaskStatusPager. +type ListJobPreparationAndReleaseTaskStatusResponse struct { + // The result of listing the status of the Job Preparation and Job Release Tasks + // for a Job. + JobPreparationAndReleaseTaskStatusListResult + + // The client-request-id provided by the client during the request. This will be returned only if the return-client-request-id + // parameter was set to true. + ClientRequestID *string + + // The ETag HTTP response header. This is an opaque string. You can use it to detect whether the resource has changed between + // requests. In particular, you can pass the ETag to one of the If-Modified-Since, If-Unmodified-Since, If-Match or If-None-Match + // headers. + ETag *string + + // The time at which the resource was last modified. + LastModified *time.Time + + // A unique identifier for the request that was made to the Batch service. If a request is consistently failing and you have + // verified that the request is properly formulated, you may use this value to report the error to Microsoft. In your report, + // include the value of this request ID, the approximate time that the request was made, the Batch Account against which the + // request was made, and the region that Account resides in. + RequestID *string +} + +// ListJobSchedulesResponse contains the response from method Client.NewListJobSchedulesPager. +type ListJobSchedulesResponse struct { + // The result of listing the Job Schedules in an Account. + JobScheduleListResult + + // The client-request-id provided by the client during the request. This will be returned only if the return-client-request-id + // parameter was set to true. + ClientRequestID *string + + // The ETag HTTP response header. This is an opaque string. You can use it to detect whether the resource has changed between + // requests. In particular, you can pass the ETag to one of the If-Modified-Since, If-Unmodified-Since, If-Match or If-None-Match + // headers. + ETag *string + + // The time at which the resource was last modified. + LastModified *time.Time + + // A unique identifier for the request that was made to the Batch service. If a request is consistently failing and you have + // verified that the request is properly formulated, you may use this value to report the error to Microsoft. In your report, + // include the value of this request ID, the approximate time that the request was made, the Batch Account against which the + // request was made, and the region that Account resides in. + RequestID *string +} + +// ListJobsFromScheduleResponse contains the response from method Client.NewListJobsFromSchedulePager. +type ListJobsFromScheduleResponse struct { + // The result of listing the Jobs in an Account. + JobListResult + + // The client-request-id provided by the client during the request. This will be returned only if the return-client-request-id + // parameter was set to true. + ClientRequestID *string + + // The ETag HTTP response header. This is an opaque string. You can use it to detect whether the resource has changed between + // requests. In particular, you can pass the ETag to one of the If-Modified-Since, If-Unmodified-Since, If-Match or If-None-Match + // headers. + ETag *string + + // The time at which the resource was last modified. + LastModified *time.Time + + // A unique identifier for the request that was made to the Batch service. If a request is consistently failing and you have + // verified that the request is properly formulated, you may use this value to report the error to Microsoft. In your report, + // include the value of this request ID, the approximate time that the request was made, the Batch Account against which the + // request was made, and the region that Account resides in. + RequestID *string +} + +// ListJobsResponse contains the response from method Client.NewListJobsPager. +type ListJobsResponse struct { + // The result of listing the Jobs in an Account. + JobListResult + + // The client-request-id provided by the client during the request. This will be returned only if the return-client-request-id + // parameter was set to true. + ClientRequestID *string + + // The ETag HTTP response header. This is an opaque string. You can use it to detect whether the resource has changed between + // requests. In particular, you can pass the ETag to one of the If-Modified-Since, If-Unmodified-Since, If-Match or If-None-Match + // headers. + ETag *string + + // The time at which the resource was last modified. + LastModified *time.Time + + // A unique identifier for the request that was made to the Batch service. If a request is consistently failing and you have + // verified that the request is properly formulated, you may use this value to report the error to Microsoft. In your report, + // include the value of this request ID, the approximate time that the request was made, the Batch Account against which the + // request was made, and the region that Account resides in. + RequestID *string +} + +// ListNodeExtensionsResponse contains the response from method Client.NewListNodeExtensionsPager. +type ListNodeExtensionsResponse struct { + // The result of listing the Compute Node extensions in a Node. + NodeVMExtensionListResult + + // The client-request-id provided by the client during the request. This will be returned only if the return-client-request-id + // parameter was set to true. + ClientRequestID *string + + // The ETag HTTP response header. This is an opaque string. You can use it to detect whether the resource has changed between + // requests. In particular, you can pass the ETag to one of the If-Modified-Since, If-Unmodified-Since, If-Match or If-None-Match + // headers. + ETag *string + + // The time at which the resource was last modified. + LastModified *time.Time + + // A unique identifier for the request that was made to the Batch service. If a request is consistently failing and you have + // verified that the request is properly formulated, you may use this value to report the error to Microsoft. In your report, + // include the value of this request ID, the approximate time that the request was made, the Batch Account against which the + // request was made, and the region that Account resides in. + RequestID *string +} + +// ListNodeFilesResponse contains the response from method Client.NewListNodeFilesPager. +type ListNodeFilesResponse struct { + // The result of listing the files on a Compute Node, or the files associated with + // a Task on a Compute Node. + NodeFileListResult + + // The client-request-id provided by the client during the request. This will be returned only if the return-client-request-id + // parameter was set to true. + ClientRequestID *string + + // The ETag HTTP response header. This is an opaque string. You can use it to detect whether the resource has changed between + // requests. In particular, you can pass the ETag to one of the If-Modified-Since, If-Unmodified-Since, If-Match or If-None-Match + // headers. + ETag *string + + // The time at which the resource was last modified. + LastModified *time.Time + + // A unique identifier for the request that was made to the Batch service. If a request is consistently failing and you have + // verified that the request is properly formulated, you may use this value to report the error to Microsoft. In your report, + // include the value of this request ID, the approximate time that the request was made, the Batch Account against which the + // request was made, and the region that Account resides in. + RequestID *string +} + +// ListNodesResponse contains the response from method Client.NewListNodesPager. +type ListNodesResponse struct { + // The result of listing the Compute Nodes in a Pool. + NodeListResult + + // The client-request-id provided by the client during the request. This will be returned only if the return-client-request-id + // parameter was set to true. + ClientRequestID *string + + // The ETag HTTP response header. This is an opaque string. You can use it to detect whether the resource has changed between + // requests. In particular, you can pass the ETag to one of the If-Modified-Since, If-Unmodified-Since, If-Match or If-None-Match + // headers. + ETag *string + + // The time at which the resource was last modified. + LastModified *time.Time + + // A unique identifier for the request that was made to the Batch service. If a request is consistently failing and you have + // verified that the request is properly formulated, you may use this value to report the error to Microsoft. In your report, + // include the value of this request ID, the approximate time that the request was made, the Batch Account against which the + // request was made, and the region that Account resides in. + RequestID *string +} + +// ListPoolNodeCountsResponse contains the response from method Client.NewListPoolNodeCountsPager. +type ListPoolNodeCountsResponse struct { + // The result of listing the Compute Node counts in the Account. + ListPoolNodeCountsResult + + // The client-request-id provided by the client during the request. This will be returned only if the return-client-request-id + // parameter was set to true. + ClientRequestID *string + + // The ETag HTTP response header. This is an opaque string. You can use it to detect whether the resource has changed between + // requests. In particular, you can pass the ETag to one of the If-Modified-Since, If-Unmodified-Since, If-Match or If-None-Match + // headers. + ETag *string + + // The time at which the resource was last modified. + LastModified *time.Time + + // A unique identifier for the request that was made to the Batch service. If a request is consistently failing and you have + // verified that the request is properly formulated, you may use this value to report the error to Microsoft. In your report, + // include the value of this request ID, the approximate time that the request was made, the Batch Account against which the + // request was made, and the region that Account resides in. + RequestID *string +} + +// ListPoolsResponse contains the response from method Client.NewListPoolsPager. +type ListPoolsResponse struct { + // The result of listing the Pools in an Account. + PoolListResult + + // The client-request-id provided by the client during the request. This will be returned only if the return-client-request-id + // parameter was set to true. + ClientRequestID *string + + // The ETag HTTP response header. This is an opaque string. You can use it to detect whether the resource has changed between + // requests. In particular, you can pass the ETag to one of the If-Modified-Since, If-Unmodified-Since, If-Match or If-None-Match + // headers. + ETag *string + + // The time at which the resource was last modified. + LastModified *time.Time + + // A unique identifier for the request that was made to the Batch service. If a request is consistently failing and you have + // verified that the request is properly formulated, you may use this value to report the error to Microsoft. In your report, + // include the value of this request ID, the approximate time that the request was made, the Batch Account against which the + // request was made, and the region that Account resides in. + RequestID *string +} + +// ListSubTasksResponse contains the response from method Client.NewListSubTasksPager. +type ListSubTasksResponse struct { + // The result of listing the subtasks of a Task. + TaskListSubtasksResult + + // The client-request-id provided by the client during the request. This will be returned only if the return-client-request-id + // parameter was set to true. + ClientRequestID *string + + // The ETag HTTP response header. This is an opaque string. You can use it to detect whether the resource has changed between + // requests. In particular, you can pass the ETag to one of the If-Modified-Since, If-Unmodified-Since, If-Match or If-None-Match + // headers. + ETag *string + + // The time at which the resource was last modified. + LastModified *time.Time + + // A unique identifier for the request that was made to the Batch service. If a request is consistently failing and you have + // verified that the request is properly formulated, you may use this value to report the error to Microsoft. In your report, + // include the value of this request ID, the approximate time that the request was made, the Batch Account against which the + // request was made, and the region that Account resides in. + RequestID *string +} + +// ListSupportedImagesResponse contains the response from method Client.NewListSupportedImagesPager. +type ListSupportedImagesResponse struct { + // The result of listing the supported Virtual Machine Images. + AccountListSupportedImagesResult + + // The client-request-id provided by the client during the request. This will be returned only if the return-client-request-id + // parameter was set to true. + ClientRequestID *string + + // The ETag HTTP response header. This is an opaque string. You can use it to detect whether the resource has changed between + // requests. In particular, you can pass the ETag to one of the If-Modified-Since, If-Unmodified-Since, If-Match or If-None-Match + // headers. + ETag *string + + // The time at which the resource was last modified. + LastModified *time.Time + + // A unique identifier for the request that was made to the Batch service. If a request is consistently failing and you have + // verified that the request is properly formulated, you may use this value to report the error to Microsoft. In your report, + // include the value of this request ID, the approximate time that the request was made, the Batch Account against which the + // request was made, and the region that Account resides in. + RequestID *string +} + +// ListTaskFilesResponse contains the response from method Client.NewListTaskFilesPager. +type ListTaskFilesResponse struct { + // The result of listing the files on a Compute Node, or the files associated with + // a Task on a Compute Node. + NodeFileListResult + + // The client-request-id provided by the client during the request. This will be returned only if the return-client-request-id + // parameter was set to true. + ClientRequestID *string + + // The ETag HTTP response header. This is an opaque string. You can use it to detect whether the resource has changed between + // requests. In particular, you can pass the ETag to one of the If-Modified-Since, If-Unmodified-Since, If-Match or If-None-Match + // headers. + ETag *string + + // The time at which the resource was last modified. + LastModified *time.Time + + // A unique identifier for the request that was made to the Batch service. If a request is consistently failing and you have + // verified that the request is properly formulated, you may use this value to report the error to Microsoft. In your report, + // include the value of this request ID, the approximate time that the request was made, the Batch Account against which the + // request was made, and the region that Account resides in. + RequestID *string +} + +// ListTasksResponse contains the response from method Client.NewListTasksPager. +type ListTasksResponse struct { + // The result of listing the Tasks in a Job. + TaskListResult + + // The client-request-id provided by the client during the request. This will be returned only if the return-client-request-id + // parameter was set to true. + ClientRequestID *string + + // The ETag HTTP response header. This is an opaque string. You can use it to detect whether the resource has changed between + // requests. In particular, you can pass the ETag to one of the If-Modified-Since, If-Unmodified-Since, If-Match or If-None-Match + // headers. + ETag *string + + // The time at which the resource was last modified. + LastModified *time.Time + + // A unique identifier for the request that was made to the Batch service. If a request is consistently failing and you have + // verified that the request is properly formulated, you may use this value to report the error to Microsoft. In your report, + // include the value of this request ID, the approximate time that the request was made, the Batch Account against which the + // request was made, and the region that Account resides in. + RequestID *string +} + +// PoolExistsResponse contains the response from method Client.PoolExists. +type PoolExistsResponse struct { + // The client-request-id provided by the client during the request. This will be returned only if the return-client-request-id + // parameter was set to true. + ClientRequestID *string + + // The ETag HTTP response header. This is an opaque string. You can use it to detect whether the resource has changed between + // requests. In particular, you can pass the ETag to one of the If-Modified-Since, If-Unmodified-Since, If-Match or If-None-Match + // headers. + ETag *string + + // The time at which the resource was last modified. + LastModified *time.Time + + // A unique identifier for the request that was made to the Batch service. If a request is consistently failing and you have + // verified that the request is properly formulated, you may use this value to report the error to Microsoft. In your report, + // include the value of this request ID, the approximate time that the request was made, the Batch Account against which the + // request was made, and the region that Account resides in. + RequestID *string +} + +// ReactivateTaskResponse contains the response from method Client.ReactivateTask. +type ReactivateTaskResponse struct { + // The client-request-id provided by the client during the request. This will be returned only if the return-client-request-id + // parameter was set to true. + ClientRequestID *string + + // The OData ID of the resource to which the request applied. + DataServiceID *string + + // The ETag HTTP response header. This is an opaque string. You can use it to detect whether the resource has changed between + // requests. In particular, you can pass the ETag to one of the If-Modified-Since, If-Unmodified-Since, If-Match or If-None-Match + // headers. + ETag *string + + // The time at which the resource was last modified. + LastModified *time.Time + + // A unique identifier for the request that was made to the Batch service. If a request is consistently failing and you have + // verified that the request is properly formulated, you may use this value to report the error to Microsoft. In your report, + // include the value of this request ID, the approximate time that the request was made, the Batch Account against which the + // request was made, and the region that Account resides in. + RequestID *string +} + +// RebootNodeResponse contains the response from method Client.RebootNode. +type RebootNodeResponse struct { + // The client-request-id provided by the client during the request. This will be returned only if the return-client-request-id + // parameter was set to true. + ClientRequestID *string + + // The OData ID of the resource to which the request applied. + DataServiceID *string + + // The ETag HTTP response header. This is an opaque string. You can use it to detect whether the resource has changed between + // requests. In particular, you can pass the ETag to one of the If-Modified-Since, If-Unmodified-Since, If-Match or If-None-Match + // headers. + ETag *string + + // The time at which the resource was last modified. + LastModified *time.Time + + // A unique identifier for the request that was made to the Batch service. If a request is consistently failing and you have + // verified that the request is properly formulated, you may use this value to report the error to Microsoft. In your report, + // include the value of this request ID, the approximate time that the request was made, the Batch Account against which the + // request was made, and the region that Account resides in. + RequestID *string +} + +// ReimageNodeResponse contains the response from method Client.ReimageNode. +type ReimageNodeResponse struct { + // The client-request-id provided by the client during the request. This will be returned only if the return-client-request-id + // parameter was set to true. + ClientRequestID *string + + // The OData ID of the resource to which the request applied. + DataServiceID *string + + // The ETag HTTP response header. This is an opaque string. You can use it to detect whether the resource has changed between + // requests. In particular, you can pass the ETag to one of the If-Modified-Since, If-Unmodified-Since, If-Match or If-None-Match + // headers. + ETag *string + + // The time at which the resource was last modified. + LastModified *time.Time + + // A unique identifier for the request that was made to the Batch service. If a request is consistently failing and you have + // verified that the request is properly formulated, you may use this value to report the error to Microsoft. In your report, + // include the value of this request ID, the approximate time that the request was made, the Batch Account against which the + // request was made, and the region that Account resides in. + RequestID *string +} + +// RemoveNodesResponse contains the response from method Client.RemoveNodes. +type RemoveNodesResponse struct { + // The client-request-id provided by the client during the request. This will be returned only if the return-client-request-id + // parameter was set to true. + ClientRequestID *string + + // The OData ID of the resource to which the request applied. + DataServiceID *string + + // The ETag HTTP response header. This is an opaque string. You can use it to detect whether the resource has changed between + // requests. In particular, you can pass the ETag to one of the If-Modified-Since, If-Unmodified-Since, If-Match or If-None-Match + // headers. + ETag *string + + // The time at which the resource was last modified. + LastModified *time.Time + + // A unique identifier for the request that was made to the Batch service. If a request is consistently failing and you have + // verified that the request is properly formulated, you may use this value to report the error to Microsoft. In your report, + // include the value of this request ID, the approximate time that the request was made, the Batch Account against which the + // request was made, and the region that Account resides in. + RequestID *string +} + +// ReplaceJobResponse contains the response from method Client.ReplaceJob. +type ReplaceJobResponse struct { + // The client-request-id provided by the client during the request. This will be returned only if the return-client-request-id + // parameter was set to true. + ClientRequestID *string + + // The OData ID of the resource to which the request applied. + DataServiceID *string + + // The ETag HTTP response header. This is an opaque string. You can use it to detect whether the resource has changed between + // requests. In particular, you can pass the ETag to one of the If-Modified-Since, If-Unmodified-Since, If-Match or If-None-Match + // headers. + ETag *string + + // The time at which the resource was last modified. + LastModified *time.Time + + // A unique identifier for the request that was made to the Batch service. If a request is consistently failing and you have + // verified that the request is properly formulated, you may use this value to report the error to Microsoft. In your report, + // include the value of this request ID, the approximate time that the request was made, the Batch Account against which the + // request was made, and the region that Account resides in. + RequestID *string +} + +// ReplaceJobScheduleResponse contains the response from method Client.ReplaceJobSchedule. +type ReplaceJobScheduleResponse struct { + // The client-request-id provided by the client during the request. This will be returned only if the return-client-request-id + // parameter was set to true. + ClientRequestID *string + + // The OData ID of the resource to which the request applied. + DataServiceID *string + + // The ETag HTTP response header. This is an opaque string. You can use it to detect whether the resource has changed between + // requests. In particular, you can pass the ETag to one of the If-Modified-Since, If-Unmodified-Since, If-Match or If-None-Match + // headers. + ETag *string + + // The time at which the resource was last modified. + LastModified *time.Time + + // A unique identifier for the request that was made to the Batch service. If a request is consistently failing and you have + // verified that the request is properly formulated, you may use this value to report the error to Microsoft. In your report, + // include the value of this request ID, the approximate time that the request was made, the Batch Account against which the + // request was made, and the region that Account resides in. + RequestID *string +} + +// ReplaceNodeUserResponse contains the response from method Client.ReplaceNodeUser. +type ReplaceNodeUserResponse struct { + // The client-request-id provided by the client during the request. This will be returned only if the return-client-request-id + // parameter was set to true. + ClientRequestID *string + + // The OData ID of the resource to which the request applied. + DataServiceID *string + + // The ETag HTTP response header. This is an opaque string. You can use it to detect whether the resource has changed between + // requests. In particular, you can pass the ETag to one of the If-Modified-Since, If-Unmodified-Since, If-Match or If-None-Match + // headers. + ETag *string + + // The time at which the resource was last modified. + LastModified *time.Time + + // A unique identifier for the request that was made to the Batch service. If a request is consistently failing and you have + // verified that the request is properly formulated, you may use this value to report the error to Microsoft. In your report, + // include the value of this request ID, the approximate time that the request was made, the Batch Account against which the + // request was made, and the region that Account resides in. + RequestID *string +} + +// ReplacePoolPropertiesResponse contains the response from method Client.ReplacePoolProperties. +type ReplacePoolPropertiesResponse struct { + // The client-request-id provided by the client during the request. This will be returned only if the return-client-request-id + // parameter was set to true. + ClientRequestID *string + + // The OData ID of the resource to which the request applied. + DataServiceID *string + + // The ETag HTTP response header. This is an opaque string. You can use it to detect whether the resource has changed between + // requests. In particular, you can pass the ETag to one of the If-Modified-Since, If-Unmodified-Since, If-Match or If-None-Match + // headers. + ETag *string + + // The time at which the resource was last modified. + LastModified *time.Time + + // A unique identifier for the request that was made to the Batch service. If a request is consistently failing and you have + // verified that the request is properly formulated, you may use this value to report the error to Microsoft. In your report, + // include the value of this request ID, the approximate time that the request was made, the Batch Account against which the + // request was made, and the region that Account resides in. + RequestID *string +} + +// ReplaceTaskResponse contains the response from method Client.ReplaceTask. +type ReplaceTaskResponse struct { + // The client-request-id provided by the client during the request. This will be returned only if the return-client-request-id + // parameter was set to true. + ClientRequestID *string + + // The OData ID of the resource to which the request applied. + DataServiceID *string + + // The ETag HTTP response header. This is an opaque string. You can use it to detect whether the resource has changed between + // requests. In particular, you can pass the ETag to one of the If-Modified-Since, If-Unmodified-Since, If-Match or If-None-Match + // headers. + ETag *string + + // The time at which the resource was last modified. + LastModified *time.Time + + // A unique identifier for the request that was made to the Batch service. If a request is consistently failing and you have + // verified that the request is properly formulated, you may use this value to report the error to Microsoft. In your report, + // include the value of this request ID, the approximate time that the request was made, the Batch Account against which the + // request was made, and the region that Account resides in. + RequestID *string +} + +// ResizePoolResponse contains the response from method Client.ResizePool. +type ResizePoolResponse struct { + // The client-request-id provided by the client during the request. This will be returned only if the return-client-request-id + // parameter was set to true. + ClientRequestID *string + + // The OData ID of the resource to which the request applied. + DataServiceID *string + + // The ETag HTTP response header. This is an opaque string. You can use it to detect whether the resource has changed between + // requests. In particular, you can pass the ETag to one of the If-Modified-Since, If-Unmodified-Since, If-Match or If-None-Match + // headers. + ETag *string + + // The time at which the resource was last modified. + LastModified *time.Time + + // A unique identifier for the request that was made to the Batch service. If a request is consistently failing and you have + // verified that the request is properly formulated, you may use this value to report the error to Microsoft. In your report, + // include the value of this request ID, the approximate time that the request was made, the Batch Account against which the + // request was made, and the region that Account resides in. + RequestID *string +} + +// StartNodeResponse contains the response from method Client.StartNode. +type StartNodeResponse struct { + // The client-request-id provided by the client during the request. This will be returned only if the return-client-request-id + // parameter was set to true. + ClientRequestID *string + + // The OData ID of the resource to which the request applied. + DataServiceID *string + + // The ETag HTTP response header. This is an opaque string. You can use it to detect whether the resource has changed between + // requests. In particular, you can pass the ETag to one of the If-Modified-Since, If-Unmodified-Since, If-Match or If-None-Match + // headers. + ETag *string + + // The time at which the resource was last modified. + LastModified *time.Time + + // A unique identifier for the request that was made to the Batch service. If a request is consistently failing and you have + // verified that the request is properly formulated, you may use this value to report the error to Microsoft. In your report, + // include the value of this request ID, the approximate time that the request was made, the Batch Account against which the + // request was made, and the region that Account resides in. + RequestID *string +} + +// StopPoolResizeResponse contains the response from method Client.StopPoolResize. +type StopPoolResizeResponse struct { + // The client-request-id provided by the client during the request. This will be returned only if the return-client-request-id + // parameter was set to true. + ClientRequestID *string + + // The OData ID of the resource to which the request applied. + DataServiceID *string + + // The ETag HTTP response header. This is an opaque string. You can use it to detect whether the resource has changed between + // requests. In particular, you can pass the ETag to one of the If-Modified-Since, If-Unmodified-Since, If-Match or If-None-Match + // headers. + ETag *string + + // The time at which the resource was last modified. + LastModified *time.Time + + // A unique identifier for the request that was made to the Batch service. If a request is consistently failing and you have + // verified that the request is properly formulated, you may use this value to report the error to Microsoft. In your report, + // include the value of this request ID, the approximate time that the request was made, the Batch Account against which the + // request was made, and the region that Account resides in. + RequestID *string +} + +// TerminateJobResponse contains the response from method Client.TerminateJob. +type TerminateJobResponse struct { + // The client-request-id provided by the client during the request. This will be returned only if the return-client-request-id + // parameter was set to true. + ClientRequestID *string + + // The OData ID of the resource to which the request applied. + DataServiceID *string + + // The ETag HTTP response header. This is an opaque string. You can use it to detect whether the resource has changed between + // requests. In particular, you can pass the ETag to one of the If-Modified-Since, If-Unmodified-Since, If-Match or If-None-Match + // headers. + ETag *string + + // The time at which the resource was last modified. + LastModified *time.Time + + // A unique identifier for the request that was made to the Batch service. If a request is consistently failing and you have + // verified that the request is properly formulated, you may use this value to report the error to Microsoft. In your report, + // include the value of this request ID, the approximate time that the request was made, the Batch Account against which the + // request was made, and the region that Account resides in. + RequestID *string +} + +// TerminateJobScheduleResponse contains the response from method Client.TerminateJobSchedule. +type TerminateJobScheduleResponse struct { + // The client-request-id provided by the client during the request. This will be returned only if the return-client-request-id + // parameter was set to true. + ClientRequestID *string + + // The OData ID of the resource to which the request applied. + DataServiceID *string + + // The ETag HTTP response header. This is an opaque string. You can use it to detect whether the resource has changed between + // requests. In particular, you can pass the ETag to one of the If-Modified-Since, If-Unmodified-Since, If-Match or If-None-Match + // headers. + ETag *string + + // The time at which the resource was last modified. + LastModified *time.Time + + // A unique identifier for the request that was made to the Batch service. If a request is consistently failing and you have + // verified that the request is properly formulated, you may use this value to report the error to Microsoft. In your report, + // include the value of this request ID, the approximate time that the request was made, the Batch Account against which the + // request was made, and the region that Account resides in. + RequestID *string +} + +// TerminateTaskResponse contains the response from method Client.TerminateTask. +type TerminateTaskResponse struct { + // The client-request-id provided by the client during the request. This will be returned only if the return-client-request-id + // parameter was set to true. + ClientRequestID *string + + // The OData ID of the resource to which the request applied. + DataServiceID *string + + // The ETag HTTP response header. This is an opaque string. You can use it to detect whether the resource has changed between + // requests. In particular, you can pass the ETag to one of the If-Modified-Since, If-Unmodified-Since, If-Match or If-None-Match + // headers. + ETag *string + + // The time at which the resource was last modified. + LastModified *time.Time + + // A unique identifier for the request that was made to the Batch service. If a request is consistently failing and you have + // verified that the request is properly formulated, you may use this value to report the error to Microsoft. In your report, + // include the value of this request ID, the approximate time that the request was made, the Batch Account against which the + // request was made, and the region that Account resides in. + RequestID *string +} + +// UpdateJobResponse contains the response from method Client.UpdateJob. +type UpdateJobResponse struct { + // The client-request-id provided by the client during the request. This will be returned only if the return-client-request-id + // parameter was set to true. + ClientRequestID *string + + // The OData ID of the resource to which the request applied. + DataServiceID *string + + // The ETag HTTP response header. This is an opaque string. You can use it to detect whether the resource has changed between + // requests. In particular, you can pass the ETag to one of the If-Modified-Since, If-Unmodified-Since, If-Match or If-None-Match + // headers. + ETag *string + + // The time at which the resource was last modified. + LastModified *time.Time + + // A unique identifier for the request that was made to the Batch service. If a request is consistently failing and you have + // verified that the request is properly formulated, you may use this value to report the error to Microsoft. In your report, + // include the value of this request ID, the approximate time that the request was made, the Batch Account against which the + // request was made, and the region that Account resides in. + RequestID *string +} + +// UpdateJobScheduleResponse contains the response from method Client.UpdateJobSchedule. +type UpdateJobScheduleResponse struct { + // The client-request-id provided by the client during the request. This will be returned only if the return-client-request-id + // parameter was set to true. + ClientRequestID *string + + // The OData ID of the resource to which the request applied. + DataServiceID *string + + // The ETag HTTP response header. This is an opaque string. You can use it to detect whether the resource has changed between + // requests. In particular, you can pass the ETag to one of the If-Modified-Since, If-Unmodified-Since, If-Match or If-None-Match + // headers. + ETag *string + + // The time at which the resource was last modified. + LastModified *time.Time + + // A unique identifier for the request that was made to the Batch service. If a request is consistently failing and you have + // verified that the request is properly formulated, you may use this value to report the error to Microsoft. In your report, + // include the value of this request ID, the approximate time that the request was made, the Batch Account against which the + // request was made, and the region that Account resides in. + RequestID *string +} + +// UpdatePoolResponse contains the response from method Client.UpdatePool. +type UpdatePoolResponse struct { + // The client-request-id provided by the client during the request. This will be returned only if the return-client-request-id + // parameter was set to true. + ClientRequestID *string + + // The OData ID of the resource to which the request applied. + DataServiceID *string + + // The ETag HTTP response header. This is an opaque string. You can use it to detect whether the resource has changed between + // requests. In particular, you can pass the ETag to one of the If-Modified-Since, If-Unmodified-Since, If-Match or If-None-Match + // headers. + ETag *string + + // The time at which the resource was last modified. + LastModified *time.Time + + // A unique identifier for the request that was made to the Batch service. If a request is consistently failing and you have + // verified that the request is properly formulated, you may use this value to report the error to Microsoft. In your report, + // include the value of this request ID, the approximate time that the request was made, the Batch Account against which the + // request was made, and the region that Account resides in. + RequestID *string +} + +// UploadNodeLogsResponse contains the response from method Client.UploadNodeLogs. +type UploadNodeLogsResponse struct { + // The result of uploading Batch service log files from a specific Compute Node. + UploadNodeLogsResult + + // The client-request-id provided by the client during the request. This will be returned only if the return-client-request-id + // parameter was set to true. + ClientRequestID *string + + // The ETag HTTP response header. This is an opaque string. You can use it to detect whether the resource has changed between + // requests. In particular, you can pass the ETag to one of the If-Modified-Since, If-Unmodified-Since, If-Match or If-None-Match + // headers. + ETag *string + + // The time at which the resource was last modified. + LastModified *time.Time + + // A unique identifier for the request that was made to the Batch service. If a request is consistently failing and you have + // verified that the request is properly formulated, you may use this value to report the error to Microsoft. In your report, + // include the value of this request ID, the approximate time that the request was made, the Batch Account against which the + // request was made, and the region that Account resides in. + RequestID *string +} + +// listPoolUsageMetricsResponse contains the response from method Client.NewlistPoolUsageMetricsPager. +type listPoolUsageMetricsResponse struct { + // The result of a listing the usage metrics for an Account. + listPoolUsageMetricsResult + + // The client-request-id provided by the client during the request. This will be returned only if the return-client-request-id + // parameter was set to true. + ClientRequestID *string + + // The ETag HTTP response header. This is an opaque string. You can use it to detect whether the resource has changed between + // requests. In particular, you can pass the ETag to one of the If-Modified-Since, If-Unmodified-Since, If-Match or If-None-Match + // headers. + ETag *string + + // The time at which the resource was last modified. + LastModified *time.Time + + // A unique identifier for the request that was made to the Batch service. If a request is consistently failing and you have + // verified that the request is properly formulated, you may use this value to report the error to Microsoft. In your report, + // include the value of this request ID, the approximate time that the request was made, the Batch Account against which the + // request was made, and the region that Account resides in. + RequestID *string +} diff --git a/sdk/batch/azbatch/time_rfc3339.go b/sdk/batch/azbatch/time_rfc3339.go new file mode 100644 index 000000000000..503b7ddf790f --- /dev/null +++ b/sdk/batch/azbatch/time_rfc3339.go @@ -0,0 +1,109 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package azbatch + +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 +} diff --git a/sdk/batch/azbatch/tsp-location.yaml b/sdk/batch/azbatch/tsp-location.yaml new file mode 100644 index 000000000000..a79f0a72b1c3 --- /dev/null +++ b/sdk/batch/azbatch/tsp-location.yaml @@ -0,0 +1,4 @@ +directory: specification/batch/Azure.Batch +commit: 1f578543d267d08febc1bebf4e33ffe14363ddfc +repo: Azure/azure-rest-api-specs +additionalDirectories: diff --git a/sdk/contosowidget/azmanager/CHANGELOG.md b/sdk/contosowidget/azmanager/CHANGELOG.md new file mode 100644 index 000000000000..1de189e320b3 --- /dev/null +++ b/sdk/contosowidget/azmanager/CHANGELOG.md @@ -0,0 +1,8 @@ +# Release History + +## 0.1.0 (2025-04-27) +### Other Changes + +The package of `github.com/Azure/azure-sdk-for-go/sdk/contosowidget/azmanager` 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/contosowidget/azmanager/LICENSE.txt b/sdk/contosowidget/azmanager/LICENSE.txt new file mode 100644 index 000000000000..dc0c2ffb3dc1 --- /dev/null +++ b/sdk/contosowidget/azmanager/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/contosowidget/azmanager/README.md b/sdk/contosowidget/azmanager/README.md new file mode 100644 index 000000000000..6bb46d36ea6d --- /dev/null +++ b/sdk/contosowidget/azmanager/README.md @@ -0,0 +1,90 @@ +# Azure Contosowidget Module for Go + +The `azmanager` module provides operations for working with Azure Contosowidget. + +[Source code](https://github.com/Azure/azure-sdk-for-go/tree/main/sdk/contosowidget/azmanager) + +# 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 Contosowidget module: + +```sh +go get github.com/Azure/azure-sdk-for-go/sdk/contosowidget/azmanager +``` + +## Authorization + +When creating a client, you will need to provide a credential for authenticating with Azure Contosowidget. 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 Contosowidget 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 := azmanager.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 := azmanager.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.() +``` + +## 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 `Contosowidget` 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/contosowidget/azmanager/ci.yml b/sdk/contosowidget/azmanager/ci.yml new file mode 100644 index 000000000000..fade31d15701 --- /dev/null +++ b/sdk/contosowidget/azmanager/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/contosowidget/azmanager/ + +pr: + branches: + include: + - main + - feature/* + - hotfix/* + - release/* + paths: + include: + - sdk/contosowidget/azmanager/ + +extends: + template: /eng/pipelines/templates/jobs/archetype-sdk-client.yml + parameters: + ServiceDirectory: 'contosowidget/azmanager' diff --git a/sdk/contosowidget/azmanager/constants.go b/sdk/contosowidget/azmanager/constants.go new file mode 100644 index 000000000000..e3ffd6813926 --- /dev/null +++ b/sdk/contosowidget/azmanager/constants.go @@ -0,0 +1,32 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package azmanager + +// OperationState - Enum describing allowed operation states. +type OperationState string + +const ( + // OperationStateCanceled - The operation has been canceled by the user. + OperationStateCanceled OperationState = "Canceled" + // OperationStateFailed - The operation has failed. + OperationStateFailed OperationState = "Failed" + // OperationStateNotStarted - The operation has not started. + OperationStateNotStarted OperationState = "NotStarted" + // OperationStateRunning - The operation is in progress. + OperationStateRunning OperationState = "Running" + // OperationStateSucceeded - The operation has completed successfully. + OperationStateSucceeded OperationState = "Succeeded" +) + +// PossibleOperationStateValues returns the possible values for the OperationState const type. +func PossibleOperationStateValues() []OperationState { + return []OperationState{ + OperationStateCanceled, + OperationStateFailed, + OperationStateNotStarted, + OperationStateRunning, + OperationStateSucceeded, + } +} diff --git a/sdk/contosowidget/azmanager/fake/internal.go b/sdk/contosowidget/azmanager/fake/internal.go new file mode 100644 index 000000000000..d9ae2e5818f8 --- /dev/null +++ b/sdk/contosowidget/azmanager/fake/internal.go @@ -0,0 +1,73 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "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 initServer[T any](mu *sync.Mutex, dst **T, src func() *T) { + mu.Lock() + if *dst == nil { + *dst = src() + } + mu.Unlock() +} + +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/contosowidget/azmanager/fake/time_rfc3339.go b/sdk/contosowidget/azmanager/fake/time_rfc3339.go new file mode 100644 index 000000000000..87ee11e83b32 --- /dev/null +++ b/sdk/contosowidget/azmanager/fake/time_rfc3339.go @@ -0,0 +1,109 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "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 +} diff --git a/sdk/contosowidget/azmanager/fake/widgetmanager_server.go b/sdk/contosowidget/azmanager/fake/widgetmanager_server.go new file mode 100644 index 000000000000..86bbc8c21d83 --- /dev/null +++ b/sdk/contosowidget/azmanager/fake/widgetmanager_server.go @@ -0,0 +1,69 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "errors" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" + "sync" +) + +// WidgetManagerServer is a fake server for instances of the azmanager.WidgetManagerClient type. +type WidgetManagerServer struct { + // WidgetManagerWidgetsServer contains the fakes for client WidgetManagerWidgetsClient + WidgetManagerWidgetsServer WidgetManagerWidgetsServer +} + +// NewWidgetManagerServerTransport creates a new instance of WidgetManagerServerTransport with the provided implementation. +// The returned WidgetManagerServerTransport instance is connected to an instance of azmanager.WidgetManagerClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewWidgetManagerServerTransport(srv *WidgetManagerServer) *WidgetManagerServerTransport { + return &WidgetManagerServerTransport{srv: srv} +} + +// WidgetManagerServerTransport connects instances of azmanager.WidgetManagerClient to instances of WidgetManagerServer. +// Don't use this type directly, use NewWidgetManagerServerTransport instead. +type WidgetManagerServerTransport struct { + srv *WidgetManagerServer + trMu sync.Mutex + trWidgetManagerWidgetsServer *WidgetManagerWidgetsServerTransport +} + +// Do implements the policy.Transporter interface for WidgetManagerServerTransport. +func (w *WidgetManagerServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return w.dispatchToClientFake(req, method[:strings.Index(method, ".")]) +} + +func (w *WidgetManagerServerTransport) dispatchToClientFake(req *http.Request, client string) (*http.Response, error) { + var resp *http.Response + var err error + + switch client { + case "WidgetManagerWidgetsClient": + initServer(&w.trMu, &w.trWidgetManagerWidgetsServer, func() *WidgetManagerWidgetsServerTransport { + return NewWidgetManagerWidgetsServerTransport(&w.srv.WidgetManagerWidgetsServer) + }) + resp, err = w.trWidgetManagerWidgetsServer.Do(req) + default: + err = fmt.Errorf("unhandled client %s", client) + } + + return resp, err +} + +// set this to conditionally intercept incoming requests to WidgetManagerServerTransport +var widgetManagerServerTransportInterceptor 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/contosowidget/azmanager/fake/widgetmanagerwidgets_server.go b/sdk/contosowidget/azmanager/fake/widgetmanagerwidgets_server.go new file mode 100644 index 000000000000..13381699fbe7 --- /dev/null +++ b/sdk/contosowidget/azmanager/fake/widgetmanagerwidgets_server.go @@ -0,0 +1,294 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/Azure/azure-sdk-for-go/sdk/contosowidget/azmanager" + "net/http" + "net/url" + "regexp" +) + +// WidgetManagerWidgetsServer is a fake server for instances of the azmanager.WidgetManagerWidgetsClient type. +type WidgetManagerWidgetsServer struct { + // BeginCreateOrUpdateWidget is the fake for method WidgetManagerWidgetsClient.BeginCreateOrUpdateWidget + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + BeginCreateOrUpdateWidget func(ctx context.Context, widgetName string, resource azmanager.WidgetSuite, options *azmanager.BeginCreateOrUpdateWidgetOptions) (resp azfake.PollerResponder[azmanager.CreateOrUpdateWidgetResponse], errResp azfake.ErrorResponder) + + // BeginDeleteWidget is the fake for method WidgetManagerWidgetsClient.BeginDeleteWidget + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted + BeginDeleteWidget func(ctx context.Context, widgetName string, options *azmanager.BeginDeleteWidgetOptions) (resp azfake.PollerResponder[azmanager.DeleteWidgetResponse], errResp azfake.ErrorResponder) + + // GetWidget is the fake for method WidgetManagerWidgetsClient.GetWidget + // HTTP status codes to indicate success: http.StatusOK + GetWidget func(ctx context.Context, widgetName string, options *azmanager.GetWidgetOptions) (resp azfake.Responder[azmanager.GetWidgetResponse], errResp azfake.ErrorResponder) + + // GetWidgetOperationStatus is the fake for method WidgetManagerWidgetsClient.GetWidgetOperationStatus + // HTTP status codes to indicate success: http.StatusOK + GetWidgetOperationStatus func(ctx context.Context, widgetName string, operationID string, options *azmanager.GetWidgetOperationStatusOptions) (resp azfake.Responder[azmanager.GetWidgetOperationStatusResponse], errResp azfake.ErrorResponder) + + // NewListWidgetsPager is the fake for method WidgetManagerWidgetsClient.NewListWidgetsPager + // HTTP status codes to indicate success: http.StatusOK + NewListWidgetsPager func(options *azmanager.ListWidgetsOptions) (resp azfake.PagerResponder[azmanager.ListWidgetsResponse]) +} + +// NewWidgetManagerWidgetsServerTransport creates a new instance of WidgetManagerWidgetsServerTransport with the provided implementation. +// The returned WidgetManagerWidgetsServerTransport instance is connected to an instance of azmanager.WidgetManagerWidgetsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewWidgetManagerWidgetsServerTransport(srv *WidgetManagerWidgetsServer) *WidgetManagerWidgetsServerTransport { + return &WidgetManagerWidgetsServerTransport{ + srv: srv, + beginCreateOrUpdateWidget: newTracker[azfake.PollerResponder[azmanager.CreateOrUpdateWidgetResponse]](), + beginDeleteWidget: newTracker[azfake.PollerResponder[azmanager.DeleteWidgetResponse]](), + newListWidgetsPager: newTracker[azfake.PagerResponder[azmanager.ListWidgetsResponse]](), + } +} + +// WidgetManagerWidgetsServerTransport connects instances of azmanager.WidgetManagerWidgetsClient to instances of WidgetManagerWidgetsServer. +// Don't use this type directly, use NewWidgetManagerWidgetsServerTransport instead. +type WidgetManagerWidgetsServerTransport struct { + srv *WidgetManagerWidgetsServer + beginCreateOrUpdateWidget *tracker[azfake.PollerResponder[azmanager.CreateOrUpdateWidgetResponse]] + beginDeleteWidget *tracker[azfake.PollerResponder[azmanager.DeleteWidgetResponse]] + newListWidgetsPager *tracker[azfake.PagerResponder[azmanager.ListWidgetsResponse]] +} + +// Do implements the policy.Transporter interface for WidgetManagerWidgetsServerTransport. +func (w *WidgetManagerWidgetsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return w.dispatchToMethodFake(req, method) +} + +func (w *WidgetManagerWidgetsServerTransport) 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 widgetManagerWidgetsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = widgetManagerWidgetsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "WidgetManagerWidgetsClient.BeginCreateOrUpdateWidget": + res.resp, res.err = w.dispatchBeginCreateOrUpdateWidget(req) + case "WidgetManagerWidgetsClient.BeginDeleteWidget": + res.resp, res.err = w.dispatchBeginDeleteWidget(req) + case "WidgetManagerWidgetsClient.GetWidget": + res.resp, res.err = w.dispatchGetWidget(req) + case "WidgetManagerWidgetsClient.GetWidgetOperationStatus": + res.resp, res.err = w.dispatchGetWidgetOperationStatus(req) + case "WidgetManagerWidgetsClient.NewListWidgetsPager": + res.resp, res.err = w.dispatchNewListWidgetsPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + select { + case resultChan <- res: + case <-req.Context().Done(): + } + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (w *WidgetManagerWidgetsServerTransport) dispatchBeginCreateOrUpdateWidget(req *http.Request) (*http.Response, error) { + if w.srv.BeginCreateOrUpdateWidget == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginCreateOrUpdateWidget not implemented")} + } + beginCreateOrUpdateWidget := w.beginCreateOrUpdateWidget.get(req) + if beginCreateOrUpdateWidget == nil { + const regexStr = `/widgets/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if matches == nil || len(matches) < 1 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[azmanager.WidgetSuite](req) + if err != nil { + return nil, err + } + widgetNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("widgetName")]) + if err != nil { + return nil, err + } + respr, errRespr := w.srv.BeginCreateOrUpdateWidget(req.Context(), widgetNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginCreateOrUpdateWidget = &respr + w.beginCreateOrUpdateWidget.add(req, beginCreateOrUpdateWidget) + } + + resp, err := server.PollerResponderNext(beginCreateOrUpdateWidget, req) + if err != nil { + return nil, err + } + + if !contains([]int{http.StatusOK, http.StatusCreated}, resp.StatusCode) { + w.beginCreateOrUpdateWidget.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", resp.StatusCode)} + } + if !server.PollerResponderMore(beginCreateOrUpdateWidget) { + w.beginCreateOrUpdateWidget.remove(req) + } + + return resp, nil +} + +func (w *WidgetManagerWidgetsServerTransport) dispatchBeginDeleteWidget(req *http.Request) (*http.Response, error) { + if w.srv.BeginDeleteWidget == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginDeleteWidget not implemented")} + } + beginDeleteWidget := w.beginDeleteWidget.get(req) + if beginDeleteWidget == nil { + const regexStr = `/widgets/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + 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) + } + widgetNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("widgetName")]) + if err != nil { + return nil, err + } + respr, errRespr := w.srv.BeginDeleteWidget(req.Context(), widgetNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginDeleteWidget = &respr + w.beginDeleteWidget.add(req, beginDeleteWidget) + } + + resp, err := server.PollerResponderNext(beginDeleteWidget, req) + if err != nil { + return nil, err + } + + if !contains([]int{http.StatusOK, http.StatusAccepted}, resp.StatusCode) { + w.beginDeleteWidget.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted", resp.StatusCode)} + } + if !server.PollerResponderMore(beginDeleteWidget) { + w.beginDeleteWidget.remove(req) + } + + return resp, nil +} + +func (w *WidgetManagerWidgetsServerTransport) dispatchGetWidget(req *http.Request) (*http.Response, error) { + if w.srv.GetWidget == nil { + return nil, &nonRetriableError{errors.New("fake for method GetWidget not implemented")} + } + const regexStr = `/widgets/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + 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) + } + widgetNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("widgetName")]) + if err != nil { + return nil, err + } + respr, errRespr := w.srv.GetWidget(req.Context(), widgetNameParam, 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).WidgetSuite, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (w *WidgetManagerWidgetsServerTransport) dispatchGetWidgetOperationStatus(req *http.Request) (*http.Response, error) { + if w.srv.GetWidgetOperationStatus == nil { + return nil, &nonRetriableError{errors.New("fake for method GetWidgetOperationStatus not implemented")} + } + const regexStr = `/widgets/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/operations/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if matches == nil || len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + widgetNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("widgetName")]) + if err != nil { + return nil, err + } + operationIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("operationId")]) + if err != nil { + return nil, err + } + respr, errRespr := w.srv.GetWidgetOperationStatus(req.Context(), widgetNameParam, operationIDParam, 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).ResourceOperationStatusWidgetSuiteWidgetSuiteError, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (w *WidgetManagerWidgetsServerTransport) dispatchNewListWidgetsPager(req *http.Request) (*http.Response, error) { + if w.srv.NewListWidgetsPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListWidgetsPager not implemented")} + } + newListWidgetsPager := w.newListWidgetsPager.get(req) + if newListWidgetsPager == nil { + resp := w.srv.NewListWidgetsPager(nil) + newListWidgetsPager = &resp + w.newListWidgetsPager.add(req, newListWidgetsPager) + server.PagerResponderInjectNextLinks(newListWidgetsPager, req, func(page *azmanager.ListWidgetsResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListWidgetsPager, req) + if err != nil { + return nil, err + } + if !contains([]int{http.StatusOK}, resp.StatusCode) { + w.newListWidgetsPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListWidgetsPager) { + w.newListWidgetsPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to WidgetManagerWidgetsServerTransport +var widgetManagerWidgetsServerTransportInterceptor 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/contosowidget/azmanager/go.mod b/sdk/contosowidget/azmanager/go.mod new file mode 100644 index 000000000000..5757b8b1fa4f --- /dev/null +++ b/sdk/contosowidget/azmanager/go.mod @@ -0,0 +1,13 @@ +module github.com/Azure/azure-sdk-for-go/sdk/contosowidget/azmanager + +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/contosowidget/azmanager/go.sum b/sdk/contosowidget/azmanager/go.sum new file mode 100644 index 000000000000..cfff861c9769 --- /dev/null +++ b/sdk/contosowidget/azmanager/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/contosowidget/azmanager/models.go b/sdk/contosowidget/azmanager/models.go new file mode 100644 index 000000000000..192252b3f932 --- /dev/null +++ b/sdk/contosowidget/azmanager/models.go @@ -0,0 +1,79 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package azmanager + +import "time" + +// Error - The error object. +type Error struct { + // REQUIRED; One of a server-defined set of error codes. + Code *string + + // REQUIRED; A human-readable representation of the error. + Message *string + + // An array of details about specific errors that led to this reported error. + Details []Error + + // An object containing more specific information than the current object about the error. + Innererror *InnerError + + // The target of the error. + Target *string +} + +// FakedSharedModel - Faked shared model +type FakedSharedModel struct { + // REQUIRED; The created date. + CreatedAt *time.Time + + // REQUIRED; The tag. + Tag *string +} + +// InnerError - An object containing more specific information about the error. As per Microsoft One API guidelines - https://github.com/Microsoft/api-guidelines/blob/vNext/Guidelines.md#7102-error-condition-responses. +type InnerError struct { + // One of a server-defined set of error codes. + Code *string + + // Inner error. + Innererror *InnerError +} + +// PagedWidgetSuite - Paged collection of WidgetSuite items +type PagedWidgetSuite struct { + // REQUIRED; The WidgetSuite items on this page + Value []WidgetSuite + + // The link to the next page of items + NextLink *string +} + +// ResourceOperationStatusWidgetSuiteWidgetSuiteError - Provides status details for long running operations. +type ResourceOperationStatusWidgetSuiteWidgetSuiteError struct { + // REQUIRED; The unique ID of the operation. + ID *string + + // REQUIRED; The status of the operation + Status *OperationState + + // Error object that describes the error when status is "Failed". + Error *Error + + // The result of the operation. + Result *WidgetSuite +} + +// WidgetSuite - A widget. +type WidgetSuite struct { + // REQUIRED; The ID of the widget's manufacturer. + ManufacturerID *string + + // The faked shared model. + SharedModel *FakedSharedModel + + // READ-ONLY; The widget name. + Name *string +} diff --git a/sdk/contosowidget/azmanager/models_serde.go b/sdk/contosowidget/azmanager/models_serde.go new file mode 100644 index 000000000000..f1b384e3e5e1 --- /dev/null +++ b/sdk/contosowidget/azmanager/models_serde.go @@ -0,0 +1,242 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package azmanager + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "reflect" +) + +// MarshalJSON implements the json.Marshaller interface for type Error. +func (e Error) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "code", e.Code) + populate(objectMap, "details", e.Details) + populate(objectMap, "innererror", e.Innererror) + populate(objectMap, "message", e.Message) + populate(objectMap, "target", e.Target) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Error. +func (e *Error) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "code": + err = unpopulate(val, "Code", &e.Code) + delete(rawMsg, key) + case "details": + err = unpopulate(val, "Details", &e.Details) + delete(rawMsg, key) + case "innererror": + err = unpopulate(val, "Innererror", &e.Innererror) + delete(rawMsg, key) + case "message": + err = unpopulate(val, "Message", &e.Message) + delete(rawMsg, key) + case "target": + err = unpopulate(val, "Target", &e.Target) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type FakedSharedModel. +func (f FakedSharedModel) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateDateTimeRFC3339(objectMap, "createdAt", f.CreatedAt) + populate(objectMap, "tag", f.Tag) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type FakedSharedModel. +func (f *FakedSharedModel) 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", f, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "createdAt": + err = unpopulateDateTimeRFC3339(val, "CreatedAt", &f.CreatedAt) + delete(rawMsg, key) + case "tag": + err = unpopulate(val, "Tag", &f.Tag) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type InnerError. +func (i InnerError) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "code", i.Code) + populate(objectMap, "innererror", i.Innererror) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type InnerError. +func (i *InnerError) 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 "code": + err = unpopulate(val, "Code", &i.Code) + delete(rawMsg, key) + case "innererror": + err = unpopulate(val, "Innererror", &i.Innererror) + 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 PagedWidgetSuite. +func (p PagedWidgetSuite) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", p.NextLink) + populate(objectMap, "value", p.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PagedWidgetSuite. +func (p *PagedWidgetSuite) 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 "nextLink": + err = unpopulate(val, "NextLink", &p.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &p.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ResourceOperationStatusWidgetSuiteWidgetSuiteError. +func (r ResourceOperationStatusWidgetSuiteWidgetSuiteError) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "error", r.Error) + populate(objectMap, "id", r.ID) + populate(objectMap, "result", r.Result) + populate(objectMap, "status", r.Status) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ResourceOperationStatusWidgetSuiteWidgetSuiteError. +func (r *ResourceOperationStatusWidgetSuiteWidgetSuiteError) 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 "error": + err = unpopulate(val, "Error", &r.Error) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &r.ID) + delete(rawMsg, key) + case "result": + err = unpopulate(val, "Result", &r.Result) + delete(rawMsg, key) + case "status": + err = unpopulate(val, "Status", &r.Status) + 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 WidgetSuite. +func (w WidgetSuite) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "manufacturerId", w.ManufacturerID) + populate(objectMap, "name", w.Name) + populate(objectMap, "sharedModel", w.SharedModel) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type WidgetSuite. +func (w *WidgetSuite) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", w, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "manufacturerId": + err = unpopulate(val, "ManufacturerID", &w.ManufacturerID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &w.Name) + delete(rawMsg, key) + case "sharedModel": + err = unpopulate(val, "SharedModel", &w.SharedModel) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", w, err) + } + } + return nil +} + +func populate(m map[string]any, k string, v any) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} + +func 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/contosowidget/azmanager/options.go b/sdk/contosowidget/azmanager/options.go new file mode 100644 index 000000000000..e130f762a64d --- /dev/null +++ b/sdk/contosowidget/azmanager/options.go @@ -0,0 +1,34 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package azmanager + +// BeginCreateOrUpdateWidgetOptions contains the optional parameters for the WidgetManagerWidgetsClient.BeginCreateOrUpdateWidget +// method. +type BeginCreateOrUpdateWidgetOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// BeginDeleteWidgetOptions contains the optional parameters for the WidgetManagerWidgetsClient.BeginDeleteWidget method. +type BeginDeleteWidgetOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// GetWidgetOperationStatusOptions contains the optional parameters for the WidgetManagerWidgetsClient.GetWidgetOperationStatus +// method. +type GetWidgetOperationStatusOptions struct { + // placeholder for future optional parameters +} + +// GetWidgetOptions contains the optional parameters for the WidgetManagerWidgetsClient.GetWidget method. +type GetWidgetOptions struct { + // placeholder for future optional parameters +} + +// ListWidgetsOptions contains the optional parameters for the WidgetManagerWidgetsClient.NewListWidgetsPager method. +type ListWidgetsOptions struct { + // placeholder for future optional parameters +} diff --git a/sdk/contosowidget/azmanager/responses.go b/sdk/contosowidget/azmanager/responses.go new file mode 100644 index 000000000000..6e114585ce85 --- /dev/null +++ b/sdk/contosowidget/azmanager/responses.go @@ -0,0 +1,35 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package azmanager + +// CreateOrUpdateWidgetResponse contains the response from method WidgetManagerWidgetsClient.BeginCreateOrUpdateWidget. +type CreateOrUpdateWidgetResponse struct { + // A widget. + WidgetSuite +} + +// DeleteWidgetResponse contains the response from method WidgetManagerWidgetsClient.BeginDeleteWidget. +type DeleteWidgetResponse struct { + // A widget. + WidgetSuite +} + +// GetWidgetOperationStatusResponse contains the response from method WidgetManagerWidgetsClient.GetWidgetOperationStatus. +type GetWidgetOperationStatusResponse struct { + // Provides status details for long running operations. + ResourceOperationStatusWidgetSuiteWidgetSuiteError +} + +// GetWidgetResponse contains the response from method WidgetManagerWidgetsClient.GetWidget. +type GetWidgetResponse struct { + // A widget. + WidgetSuite +} + +// ListWidgetsResponse contains the response from method WidgetManagerWidgetsClient.NewListWidgetsPager. +type ListWidgetsResponse struct { + // Paged collection of WidgetSuite items + PagedWidgetSuite +} diff --git a/sdk/contosowidget/azmanager/time_rfc3339.go b/sdk/contosowidget/azmanager/time_rfc3339.go new file mode 100644 index 000000000000..e2f185983728 --- /dev/null +++ b/sdk/contosowidget/azmanager/time_rfc3339.go @@ -0,0 +1,109 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package azmanager + +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 +} diff --git a/sdk/contosowidget/azmanager/tsp-location.yaml b/sdk/contosowidget/azmanager/tsp-location.yaml new file mode 100644 index 000000000000..cb8f5c2c8159 --- /dev/null +++ b/sdk/contosowidget/azmanager/tsp-location.yaml @@ -0,0 +1,5 @@ +directory: specification/contosowidgetmanager/Contoso.WidgetManager +commit: 1f578543d267d08febc1bebf4e33ffe14363ddfc +repo: Azure/azure-rest-api-specs +additionalDirectories: +- specification/contosowidgetmanager/Contoso.WidgetManager.Shared diff --git a/sdk/contosowidget/azmanager/widgetmanager_client.go b/sdk/contosowidget/azmanager/widgetmanager_client.go new file mode 100644 index 000000000000..bc1098daaefa --- /dev/null +++ b/sdk/contosowidget/azmanager/widgetmanager_client.go @@ -0,0 +1,22 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package azmanager + +import "github.com/Azure/azure-sdk-for-go/sdk/azcore" + +// WidgetManagerClient contains the methods for the WidgetManager group. +// Don't use this type directly, use a constructor function instead. +type WidgetManagerClient struct { + internal *azcore.Client + endpoint string +} + +// NewWidgetManagerWidgetsClient creates a new instance of [WidgetManagerWidgetsClient]. +func (client *WidgetManagerClient) NewWidgetManagerWidgetsClient() *WidgetManagerWidgetsClient { + return &WidgetManagerWidgetsClient{ + internal: client.internal, + endpoint: client.endpoint, + } +} diff --git a/sdk/contosowidget/azmanager/widgetmanagerwidgets_client.go b/sdk/contosowidget/azmanager/widgetmanagerwidgets_client.go new file mode 100644 index 000000000000..46dffb3d7b75 --- /dev/null +++ b/sdk/contosowidget/azmanager/widgetmanagerwidgets_client.go @@ -0,0 +1,340 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package azmanager + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "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" +) + +// WidgetManagerWidgetsClient contains the methods for the WidgetManagerWidgets group. +// Don't use this type directly, use [WidgetManagerClient.NewWidgetManagerWidgetsClient] instead. +type WidgetManagerWidgetsClient struct { + internal *azcore.Client + endpoint string +} + +// BeginCreateOrUpdateWidget - Creates or updates a Widget asynchronously. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2022-12-01 +// - widgetName - The widget name. +// - resource - The resource instance. +// - options - BeginCreateOrUpdateWidgetOptions contains the optional parameters for the WidgetManagerWidgetsClient.BeginCreateOrUpdateWidget +// method. +func (client *WidgetManagerWidgetsClient) BeginCreateOrUpdateWidget(ctx context.Context, widgetName string, resource WidgetSuite, options *BeginCreateOrUpdateWidgetOptions) (*runtime.Poller[CreateOrUpdateWidgetResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdateWidget(ctx, widgetName, resource, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[CreateOrUpdateWidgetResponse]{ + OperationLocationResultPath: "result", + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[CreateOrUpdateWidgetResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdateWidget - Creates or updates a Widget asynchronously. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2022-12-01 +func (client *WidgetManagerWidgetsClient) createOrUpdateWidget(ctx context.Context, widgetName string, resource WidgetSuite, options *BeginCreateOrUpdateWidgetOptions) (*http.Response, error) { + var err error + const operationName = "WidgetManagerWidgetsClient.BeginCreateOrUpdateWidget" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createOrUpdateWidgetCreateRequest(ctx, widgetName, 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 +} + +// createOrUpdateWidgetCreateRequest creates the CreateOrUpdateWidget request. +func (client *WidgetManagerWidgetsClient) createOrUpdateWidgetCreateRequest(ctx context.Context, widgetName string, resource WidgetSuite, _ *BeginCreateOrUpdateWidgetOptions) (*policy.Request, error) { + host := "{endpoint}" + host = strings.ReplaceAll(host, "{endpoint}", client.endpoint) + urlPath := "/widgets/{widgetName}" + if widgetName == "" { + return nil, errors.New("parameter widgetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{widgetName}", url.PathEscape(widgetName)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2022-12-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/merge-patch+json"} + if err := runtime.MarshalAsJSON(req, resource); err != nil { + return nil, err + } + return req, nil +} + +// BeginDeleteWidget - Delete a Widget asynchronously. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2022-12-01 +// - widgetName - The widget name. +// - options - BeginDeleteWidgetOptions contains the optional parameters for the WidgetManagerWidgetsClient.BeginDeleteWidget +// method. +func (client *WidgetManagerWidgetsClient) BeginDeleteWidget(ctx context.Context, widgetName string, options *BeginDeleteWidgetOptions) (*runtime.Poller[DeleteWidgetResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteWidget(ctx, widgetName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[DeleteWidgetResponse]{ + OperationLocationResultPath: "result", + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[DeleteWidgetResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// DeleteWidget - Delete a Widget asynchronously. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2022-12-01 +func (client *WidgetManagerWidgetsClient) deleteWidget(ctx context.Context, widgetName string, options *BeginDeleteWidgetOptions) (*http.Response, error) { + var err error + const operationName = "WidgetManagerWidgetsClient.BeginDeleteWidget" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteWidgetCreateRequest(ctx, widgetName, 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) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// deleteWidgetCreateRequest creates the DeleteWidget request. +func (client *WidgetManagerWidgetsClient) deleteWidgetCreateRequest(ctx context.Context, widgetName string, _ *BeginDeleteWidgetOptions) (*policy.Request, error) { + host := "{endpoint}" + host = strings.ReplaceAll(host, "{endpoint}", client.endpoint) + urlPath := "/widgets/{widgetName}" + if widgetName == "" { + return nil, errors.New("parameter widgetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{widgetName}", url.PathEscape(widgetName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2022-12-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// GetWidget - Fetch a Widget by name. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2022-12-01 +// - widgetName - The widget name. +// - options - GetWidgetOptions contains the optional parameters for the WidgetManagerWidgetsClient.GetWidget method. +func (client *WidgetManagerWidgetsClient) GetWidget(ctx context.Context, widgetName string, options *GetWidgetOptions) (GetWidgetResponse, error) { + var err error + const operationName = "WidgetManagerWidgetsClient.GetWidget" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getWidgetCreateRequest(ctx, widgetName, options) + if err != nil { + return GetWidgetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return GetWidgetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return GetWidgetResponse{}, err + } + resp, err := client.getWidgetHandleResponse(httpResp) + return resp, err +} + +// getWidgetCreateRequest creates the GetWidget request. +func (client *WidgetManagerWidgetsClient) getWidgetCreateRequest(ctx context.Context, widgetName string, _ *GetWidgetOptions) (*policy.Request, error) { + host := "{endpoint}" + host = strings.ReplaceAll(host, "{endpoint}", client.endpoint) + urlPath := "/widgets/{widgetName}" + if widgetName == "" { + return nil, errors.New("parameter widgetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{widgetName}", url.PathEscape(widgetName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2022-12-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getWidgetHandleResponse handles the GetWidget response. +func (client *WidgetManagerWidgetsClient) getWidgetHandleResponse(resp *http.Response) (GetWidgetResponse, error) { + result := GetWidgetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.WidgetSuite); err != nil { + return GetWidgetResponse{}, err + } + return result, nil +} + +// GetWidgetOperationStatus - Gets status of a Widget operation. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2022-12-01 +// - widgetName - The widget name. +// - operationID - The unique ID of the operation. +// - options - GetWidgetOperationStatusOptions contains the optional parameters for the WidgetManagerWidgetsClient.GetWidgetOperationStatus +// method. +func (client *WidgetManagerWidgetsClient) GetWidgetOperationStatus(ctx context.Context, widgetName string, operationID string, options *GetWidgetOperationStatusOptions) (GetWidgetOperationStatusResponse, error) { + var err error + const operationName = "WidgetManagerWidgetsClient.GetWidgetOperationStatus" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getWidgetOperationStatusCreateRequest(ctx, widgetName, operationID, options) + if err != nil { + return GetWidgetOperationStatusResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return GetWidgetOperationStatusResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return GetWidgetOperationStatusResponse{}, err + } + resp, err := client.getWidgetOperationStatusHandleResponse(httpResp) + return resp, err +} + +// getWidgetOperationStatusCreateRequest creates the GetWidgetOperationStatus request. +func (client *WidgetManagerWidgetsClient) getWidgetOperationStatusCreateRequest(ctx context.Context, widgetName string, operationID string, _ *GetWidgetOperationStatusOptions) (*policy.Request, error) { + host := "{endpoint}" + host = strings.ReplaceAll(host, "{endpoint}", client.endpoint) + urlPath := "/widgets/{widgetName}/operations/{operationId}" + if widgetName == "" { + return nil, errors.New("parameter widgetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{widgetName}", url.PathEscape(widgetName)) + if operationID == "" { + return nil, errors.New("parameter operationID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{operationId}", url.PathEscape(operationID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2022-12-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getWidgetOperationStatusHandleResponse handles the GetWidgetOperationStatus response. +func (client *WidgetManagerWidgetsClient) getWidgetOperationStatusHandleResponse(resp *http.Response) (GetWidgetOperationStatusResponse, error) { + result := GetWidgetOperationStatusResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ResourceOperationStatusWidgetSuiteWidgetSuiteError); err != nil { + return GetWidgetOperationStatusResponse{}, err + } + return result, nil +} + +// NewListWidgetsPager - List Widget resources +// +// Generated from API version 2022-12-01 +// - options - ListWidgetsOptions contains the optional parameters for the WidgetManagerWidgetsClient.NewListWidgetsPager method. +func (client *WidgetManagerWidgetsClient) NewListWidgetsPager(options *ListWidgetsOptions) *runtime.Pager[ListWidgetsResponse] { + return runtime.NewPager(runtime.PagingHandler[ListWidgetsResponse]{ + More: func(page ListWidgetsResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ListWidgetsResponse) (ListWidgetsResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "WidgetManagerWidgetsClient.NewListWidgetsPager") + 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.listWidgetsCreateRequest(ctx, options) + }, nil) + if err != nil { + return ListWidgetsResponse{}, err + } + return client.listWidgetsHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listWidgetsCreateRequest creates the ListWidgets request. +func (client *WidgetManagerWidgetsClient) listWidgetsCreateRequest(ctx context.Context, _ *ListWidgetsOptions) (*policy.Request, error) { + host := "{endpoint}" + host = strings.ReplaceAll(host, "{endpoint}", client.endpoint) + urlPath := "/widgets" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2022-12-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listWidgetsHandleResponse handles the ListWidgets response. +func (client *WidgetManagerWidgetsClient) listWidgetsHandleResponse(resp *http.Response) (ListWidgetsResponse, error) { + result := ListWidgetsResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.PagedWidgetSuite); err != nil { + return ListWidgetsResponse{}, err + } + return result, nil +} diff --git a/sdk/messaging/eventgrid/aznamespaces/CHANGELOG.md b/sdk/messaging/eventgrid/aznamespaces/CHANGELOG.md index 6d7391ceea97..5eac9543220d 100644 --- a/sdk/messaging/eventgrid/aznamespaces/CHANGELOG.md +++ b/sdk/messaging/eventgrid/aznamespaces/CHANGELOG.md @@ -1,5 +1,75 @@ # Release History +## 2.0.0 (2025-04-27) +### Breaking Changes + +- Function `*ReceiverClient.AcknowledgeEvents` parameter(s) have been changed from `(context.Context, []string, *AcknowledgeEventsOptions)` to `(context.Context, string, string, []string, *ReceiverClientAcknowledgeEventsOptions)` +- Function `*ReceiverClient.AcknowledgeEvents` return value(s) have been changed from `(AcknowledgeEventsResponse, error)` to `(ReceiverClientAcknowledgeEventsResponse, error)` +- Function `*ReceiverClient.ReceiveEvents` parameter(s) have been changed from `(context.Context, *ReceiveEventsOptions)` to `(context.Context, string, string, *ReceiverClientReceiveEventsOptions)` +- Function `*ReceiverClient.ReceiveEvents` return value(s) have been changed from `(ReceiveEventsResponse, error)` to `(ReceiverClientReceiveEventsResponse, error)` +- Function `*ReceiverClient.RejectEvents` parameter(s) have been changed from `(context.Context, []string, *RejectEventsOptions)` to `(context.Context, string, string, []string, *ReceiverClientRejectEventsOptions)` +- Function `*ReceiverClient.RejectEvents` return value(s) have been changed from `(RejectEventsResponse, error)` to `(ReceiverClientRejectEventsResponse, error)` +- Function `*ReceiverClient.ReleaseEvents` parameter(s) have been changed from `(context.Context, []string, *ReleaseEventsOptions)` to `(context.Context, string, string, []string, *ReceiverClientReleaseEventsOptions)` +- Function `*ReceiverClient.ReleaseEvents` return value(s) have been changed from `(ReleaseEventsResponse, error)` to `(ReceiverClientReleaseEventsResponse, error)` +- Function `*ReceiverClient.RenewEventLocks` parameter(s) have been changed from `(context.Context, []string, *RenewEventLocksOptions)` to `(context.Context, string, string, []string, *ReceiverClientRenewEventLocksOptions)` +- Function `*ReceiverClient.RenewEventLocks` return value(s) have been changed from `(RenewEventLocksResponse, error)` to `(ReceiverClientRenewEventLocksResponse, error)` +- Function `*SenderClient.SendEvent` parameter(s) have been changed from `(context.Context, *messaging.CloudEvent, *SendEventOptions)` to `(context.Context, string, CloudEvent, *SenderClientSendEventOptions)` +- Function `*SenderClient.SendEvent` return value(s) have been changed from `(SendEventResponse, error)` to `(SenderClientSendEventResponse, error)` +- Function `*SenderClient.SendEvents` parameter(s) have been changed from `(context.Context, []*messaging.CloudEvent, *SendEventsOptions)` to `(context.Context, string, []CloudEvent, *SenderClientSendEventsOptions)` +- Function `*SenderClient.SendEvents` return value(s) have been changed from `(SendEventsResponse, error)` to `(SenderClientSendEventsResponse, error)` +- Type of `ReceiveDetails.Event` has been changed from `messaging.CloudEvent` to `*CloudEvent` +- Function `NewReceiverClient` has been removed +- Function `NewReceiverClientWithSharedKeyCredential` has been removed +- Function `NewSenderClient` has been removed +- Function `NewSenderClientWithSharedKeyCredential` has been removed +- Struct `AcknowledgeEventsOptions` has been removed +- Struct `AcknowledgeEventsResponse` has been removed +- Struct `AcknowledgeEventsResult` has been removed +- Struct `ReceiveEventsOptions` has been removed +- Struct `ReceiveEventsResponse` has been removed +- Struct `ReceiveEventsResult` has been removed +- Struct `ReceiverClientOptions` has been removed +- Struct `RejectEventsOptions` has been removed +- Struct `RejectEventsResponse` has been removed +- Struct `RejectEventsResult` has been removed +- Struct `ReleaseEventsOptions` has been removed +- Struct `ReleaseEventsResponse` has been removed +- Struct `ReleaseEventsResult` has been removed +- Struct `RenewEventLocksOptions` has been removed +- Struct `RenewEventLocksResponse` has been removed +- Struct `RenewEventLocksResult` has been removed +- Struct `SendEventOptions` has been removed +- Struct `SendEventResponse` has been removed +- Struct `SendEventsOptions` has been removed +- Struct `SendEventsResponse` has been removed +- Struct `SenderClientOptions` has been removed + +### Features Added + +- New struct `AcknowledgeResult` +- New struct `CloudEvent` +- New struct `InnerError` +- New struct `PublishResult` +- New struct `ReceiveResult` +- New struct `ReceiverClientAcknowledgeEventsOptions` +- New struct `ReceiverClientAcknowledgeEventsResponse` +- New struct `ReceiverClientReceiveEventsOptions` +- New struct `ReceiverClientReceiveEventsResponse` +- New struct `ReceiverClientRejectEventsOptions` +- New struct `ReceiverClientRejectEventsResponse` +- New struct `ReceiverClientReleaseEventsOptions` +- New struct `ReceiverClientReleaseEventsResponse` +- New struct `ReceiverClientRenewEventLocksOptions` +- New struct `ReceiverClientRenewEventLocksResponse` +- New struct `RejectResult` +- New struct `ReleaseResult` +- New struct `RenewLocksResult` +- New struct `SenderClientSendEventOptions` +- New struct `SenderClientSendEventResponse` +- New struct `SenderClientSendEventsOptions` +- New struct `SenderClientSendEventsResponse` + + ## 1.0.1 (Unreleased) ### Features Added diff --git a/sdk/messaging/eventgrid/aznamespaces/README.md b/sdk/messaging/eventgrid/aznamespaces/README.md index 67247efb9979..2f5dcc0cd077 100644 --- a/sdk/messaging/eventgrid/aznamespaces/README.md +++ b/sdk/messaging/eventgrid/aznamespaces/README.md @@ -19,7 +19,7 @@ Key links: Install the Azure Event Grid Namespaces client module for Go with `go get`: ```bash -go get github.com/Azure/azure-sdk-for-go/sdk/messaging/eventgrid/aznamespaces +go get github.com/Azure/azure-sdk-for-go/sdk/messaging/eventgrid/aznamespaces/v2 ``` ### Prerequisites @@ -114,15 +114,15 @@ Azure SDK for Go is licensed under the [MIT](https://github.com/Azure/azure-sdk- [azure_sdk_for_go_contributing_developer_guide]: https://github.com/Azure/azure-sdk-for-go/blob/main/CONTRIBUTING.md#developer-guide [azure_sdk_for_go_contributing_pull_requests]: https://github.com/Azure/azure-sdk-for-go/blob/main/CONTRIBUTING.md#pull-requests [source]: https://github.com/Azure/azure-sdk-for-go/tree/main/sdk/messaging/eventgrid/aznamespaces -[godoc]: https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/messaging/eventgrid/aznamespaces -[godoc_send]: https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/messaging/eventgrid/aznamespaces#SenderClient.SendEvents -[godoc_receive]: https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/messaging/eventgrid/aznamespaces#ReceiverClient.ReceiveEvents -[godoc_examples]: https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/messaging/eventgrid/aznamespaces#pkg-examples -[godoc_example_newsender_sharedkey]: https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/messaging/eventgrid/aznamespaces#example-NewSenderClientWithSharedKeyCredential -[godoc_example_newreceiver_sharedkey]: https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/messaging/eventgrid/aznamespaces#example-NewReceiverClientWithSharedKeyCredential -[godoc_example_newsender]: https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/messaging/eventgrid/aznamespaces#example-NewSenderClient -[godoc_example_newreceiver]: https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/messaging/eventgrid/aznamespaces#example-NewReceiverClient -[godoc_egbasic_client]: https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/messaging/eventgrid/aznamespaces#Client +[godoc]: https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/messaging/eventgrid/aznamespaces/v2 +[godoc_send]: https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/messaging/eventgrid/aznamespaces/v2#SenderClient.SendEvents +[godoc_receive]: https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/messaging/eventgrid/aznamespaces/v2#ReceiverClient.ReceiveEvents +[godoc_examples]: https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/messaging/eventgrid/aznamespaces/v2#pkg-examples +[godoc_example_newsender_sharedkey]: https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/messaging/eventgrid/aznamespaces/v2#example-NewSenderClientWithSharedKeyCredential +[godoc_example_newreceiver_sharedkey]: https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/messaging/eventgrid/aznamespaces/v2#example-NewReceiverClientWithSharedKeyCredential +[godoc_example_newsender]: https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/messaging/eventgrid/aznamespaces/v2#example-NewSenderClient +[godoc_example_newreceiver]: https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/messaging/eventgrid/aznamespaces/v2#example-NewReceiverClient +[godoc_egbasic_client]: https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/messaging/eventgrid/aznamespaces/v2#Client [ms_namespace]: https://learn.microsoft.com/azure/event-grid/concepts-pull-delivery#namespaces [ms_topic]: https://learn.microsoft.com/azure/event-grid/concepts-pull-delivery#namespace-topics [ms_subscription]: https://learn.microsoft.com/azure/event-grid/concepts-pull-delivery#event-subscriptions diff --git a/sdk/messaging/eventgrid/aznamespaces/build.go b/sdk/messaging/eventgrid/aznamespaces/build.go deleted file mode 100644 index 05938252414f..000000000000 --- a/sdk/messaging/eventgrid/aznamespaces/build.go +++ /dev/null @@ -1,9 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. - -//go:generate tsp-client update -//go:generate goimports -w . -//go:generate go run ./internal/generate -//go:generate goimports -w . - -package aznamespaces diff --git a/sdk/messaging/eventgrid/aznamespaces/go.mod b/sdk/messaging/eventgrid/aznamespaces/go.mod index beaa7bcbf597..550d409bce51 100644 --- a/sdk/messaging/eventgrid/aznamespaces/go.mod +++ b/sdk/messaging/eventgrid/aznamespaces/go.mod @@ -1,10 +1,11 @@ -module github.com/Azure/azure-sdk-for-go/sdk/messaging/eventgrid/aznamespaces +module github.com/Azure/azure-sdk-for-go/sdk/messaging/eventgrid/aznamespaces/v2 go 1.23.0 require ( github.com/Azure/azure-sdk-for-go/sdk/azcore v1.17.1 github.com/Azure/azure-sdk-for-go/sdk/internal v1.11.1 + github.com/Azure/azure-sdk-for-go/sdk/messaging/eventgrid/aznamespaces v1.0.0 ) diff --git a/sdk/messaging/eventgrid/aznamespaces/go.sum b/sdk/messaging/eventgrid/aznamespaces/go.sum index 5ad08fa92386..9b1398c8026e 100644 --- a/sdk/messaging/eventgrid/aznamespaces/go.sum +++ b/sdk/messaging/eventgrid/aznamespaces/go.sum @@ -6,6 +6,8 @@ github.com/Azure/azure-sdk-for-go/sdk/azidentity/cache v0.3.2 h1:yz1bePFlP5Vws5+ github.com/Azure/azure-sdk-for-go/sdk/azidentity/cache v0.3.2/go.mod h1:Pa9ZNPuoNu/GztvBSKk9J1cDJW6vk/n0zLtV4mgd8N8= github.com/Azure/azure-sdk-for-go/sdk/internal v1.11.1 h1:FPKJS1T+clwv+OLGt13a8UjqeRuh0O4SJ3lUriThc+4= github.com/Azure/azure-sdk-for-go/sdk/internal v1.11.1/go.mod h1:j2chePtV91HrC22tGoRX3sGY42uF13WzmmV80/OdVAA= +github.com/Azure/azure-sdk-for-go/sdk/messaging/eventgrid/aznamespaces v1.0.0 h1:NuKtfJWQv4V2lcSDh+lZnm3rLNTQl6ePtqKUHY0qSPU= +github.com/Azure/azure-sdk-for-go/sdk/messaging/eventgrid/aznamespaces v1.0.0/go.mod h1:1VBmb/55EInicb/Z5aS8p6CulJ9olX6BJ9kKjmIHcrA= github.com/AzureAD/microsoft-authentication-extensions-for-go/cache v0.1.1 h1:WJTmL004Abzc5wDB5VtZG2PJk5ndYDgVacGqfirKxjM= github.com/AzureAD/microsoft-authentication-extensions-for-go/cache v0.1.1/go.mod h1:tCcJZ0uHAmvjsVYzEFivsRTN00oz5BEsRgQHu5JZ9WE= github.com/AzureAD/microsoft-authentication-library-for-go v1.4.2 h1:oygO0locgZJe7PpYPXT5A29ZkwJaPqcva7BVeemZOZs= diff --git a/sdk/messaging/eventgrid/aznamespaces/models.go b/sdk/messaging/eventgrid/aznamespaces/models.go index cf95c73508d3..de20a144c98f 100644 --- a/sdk/messaging/eventgrid/aznamespaces/models.go +++ b/sdk/messaging/eventgrid/aznamespaces/models.go @@ -4,15 +4,15 @@ package aznamespaces -import "github.com/Azure/azure-sdk-for-go/sdk/azcore/messaging" +import "time" -// AcknowledgeEventsResult - The result of the Acknowledge operation. -type AcknowledgeEventsResult struct { - // REQUIRED; Array of FailedLockToken for failed cloud events. Each FailedLockToken includes the lock token along with the +// AcknowledgeResult - The result of the Acknowledge operation. +type AcknowledgeResult struct { + // READ-ONLY; Array of FailedLockToken for failed cloud events. Each FailedLockToken includes the lock token along with the // related error information (namely, the error code and description). FailedLockTokens []FailedLockToken - // REQUIRED; Array of lock tokens for the successfully acknowledged cloud events. + // READ-ONLY; Array of lock tokens for the successfully acknowledged cloud events. SucceededLockTokens []string } @@ -25,6 +25,59 @@ type BrokerProperties struct { LockToken *string } +// CloudEvent - Properties of an event published to an Azure Messaging EventGrid Namespace topic using the CloudEvent 1.0 +// Schema. +type CloudEvent struct { + // REQUIRED; An identifier for the event. The combination of id and source must be unique for each distinct event. + ID *string + + // REQUIRED; Identifies the context in which an event happened. The combination of id and source must be unique for each distinct + // event. + Source *string + + // REQUIRED; The version of the CloudEvents specification which the event uses. + Specversion *string + + // REQUIRED; Type of event related to the originating occurrence. + Type *string + + // Event data specific to the event type. + Data any + + // Event data specific to the event type, encoded as a base64 string. + DataBase64 []byte + + // Content type of data value. + Datacontenttype *string + + // Identifies the schema that data adheres to. + Dataschema *string + + // This describes the subject of the event in the context of the event producer (identified by source). + Subject *string + + // The time (in UTC) the event was generated, in RFC3339 format. + Time *time.Time +} + +// Error - The error object. +type Error struct { + // REQUIRED; One of a server-defined set of error codes. + Code *string + + // REQUIRED; A human-readable representation of the error. + Message *string + + // An array of details about specific errors that led to this reported error. + Details []Error + + // An object containing more specific information than the current object about the error. + Innererror *InnerError + + // The target of the error. + Target *string +} + // FailedLockToken - Failed LockToken information. type FailedLockToken struct { // REQUIRED; Error information of the failed operation result for the lock token in the request. @@ -34,47 +87,60 @@ type FailedLockToken struct { LockToken *string } +// InnerError - An object containing more specific information about the error. As per Microsoft One API guidelines - https://github.com/Microsoft/api-guidelines/blob/vNext/Guidelines.md#7102-error-condition-responses. +type InnerError struct { + // One of a server-defined set of error codes. + Code *string + + // Inner error. + Innererror *InnerError +} + +// PublishResult - The result of the Publish operation. +type PublishResult struct { +} + // ReceiveDetails - Receive operation details per Cloud Event. type ReceiveDetails struct { // REQUIRED; The Event Broker details. BrokerProperties *BrokerProperties // REQUIRED; Cloud Event details. - Event messaging.CloudEvent + Event *CloudEvent } -// ReceiveEventsResult - Details of the Receive operation response. -type ReceiveEventsResult struct { - // REQUIRED; Array of receive responses, one per cloud event. +// ReceiveResult - Details of the Receive operation response. +type ReceiveResult struct { + // READ-ONLY; Array of receive responses, one per cloud event. Details []ReceiveDetails } -// RejectEventsResult - The result of the Reject operation. -type RejectEventsResult struct { - // REQUIRED; Array of FailedLockToken for failed cloud events. Each FailedLockToken includes the lock token along with the +// RejectResult - The result of the Reject operation. +type RejectResult struct { + // READ-ONLY; Array of FailedLockToken for failed cloud events. Each FailedLockToken includes the lock token along with the // related error information (namely, the error code and description). FailedLockTokens []FailedLockToken - // REQUIRED; Array of lock tokens for the successfully rejected cloud events. + // READ-ONLY; Array of lock tokens for the successfully rejected cloud events. SucceededLockTokens []string } -// ReleaseEventsResult - The result of the Release operation. -type ReleaseEventsResult struct { - // REQUIRED; Array of FailedLockToken for failed cloud events. Each FailedLockToken includes the lock token along with the +// ReleaseResult - The result of the Release operation. +type ReleaseResult struct { + // READ-ONLY; Array of FailedLockToken for failed cloud events. Each FailedLockToken includes the lock token along with the // related error information (namely, the error code and description). FailedLockTokens []FailedLockToken - // REQUIRED; Array of lock tokens for the successfully released cloud events. + // READ-ONLY; Array of lock tokens for the successfully released cloud events. SucceededLockTokens []string } -// RenewEventLocksResult - The result of the RenewLock operation. -type RenewEventLocksResult struct { - // REQUIRED; Array of FailedLockToken for failed cloud events. Each FailedLockToken includes the lock token along with the +// RenewLocksResult - The result of the RenewLock operation. +type RenewLocksResult struct { + // READ-ONLY; Array of FailedLockToken for failed cloud events. Each FailedLockToken includes the lock token along with the // related error information (namely, the error code and description). FailedLockTokens []FailedLockToken - // REQUIRED; Array of lock tokens for the successfully renewed locks. + // READ-ONLY; Array of lock tokens for the successfully renewed locks. SucceededLockTokens []string } diff --git a/sdk/messaging/eventgrid/aznamespaces/models_serde.go b/sdk/messaging/eventgrid/aznamespaces/models_serde.go index c3229a6780c0..d406c991e8f0 100644 --- a/sdk/messaging/eventgrid/aznamespaces/models_serde.go +++ b/sdk/messaging/eventgrid/aznamespaces/models_serde.go @@ -7,13 +7,13 @@ package aznamespaces import ( "encoding/json" "fmt" - "reflect" - "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "reflect" ) // MarshalJSON implements the json.Marshaller interface for type AcknowledgeResult. -func (a AcknowledgeEventsResult) MarshalJSON() ([]byte, error) { +func (a AcknowledgeResult) MarshalJSON() ([]byte, error) { objectMap := make(map[string]any) populate(objectMap, "failedLockTokens", a.FailedLockTokens) populate(objectMap, "succeededLockTokens", a.SucceededLockTokens) @@ -21,7 +21,7 @@ func (a AcknowledgeEventsResult) MarshalJSON() ([]byte, error) { } // UnmarshalJSON implements the json.Unmarshaller interface for type AcknowledgeResult. -func (a *AcknowledgeEventsResult) UnmarshalJSON(data []byte) error { +func (a *AcknowledgeResult) 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) @@ -74,6 +74,116 @@ func (b *BrokerProperties) UnmarshalJSON(data []byte) error { return nil } +// MarshalJSON implements the json.Marshaller interface for type CloudEvent. +func (c CloudEvent) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateAny(objectMap, "data", c.Data) + populateByteArray(objectMap, "data_base64", c.DataBase64, func() any { + return runtime.EncodeByteArray(c.DataBase64, runtime.Base64StdFormat) + }) + populate(objectMap, "datacontenttype", c.Datacontenttype) + populate(objectMap, "dataschema", c.Dataschema) + populate(objectMap, "id", c.ID) + populate(objectMap, "source", c.Source) + populate(objectMap, "specversion", c.Specversion) + populate(objectMap, "subject", c.Subject) + populateDateTimeRFC3339(objectMap, "time", c.Time) + populate(objectMap, "type", c.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CloudEvent. +func (c *CloudEvent) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "data": + err = unpopulate(val, "Data", &c.Data) + delete(rawMsg, key) + case "data_base64": + if val != nil && string(val) != "null" { + err = runtime.DecodeByteArray(string(val), &c.DataBase64, runtime.Base64StdFormat) + } + delete(rawMsg, key) + case "datacontenttype": + err = unpopulate(val, "Datacontenttype", &c.Datacontenttype) + delete(rawMsg, key) + case "dataschema": + err = unpopulate(val, "Dataschema", &c.Dataschema) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &c.ID) + delete(rawMsg, key) + case "source": + err = unpopulate(val, "Source", &c.Source) + delete(rawMsg, key) + case "specversion": + err = unpopulate(val, "Specversion", &c.Specversion) + delete(rawMsg, key) + case "subject": + err = unpopulate(val, "Subject", &c.Subject) + delete(rawMsg, key) + case "time": + err = unpopulateDateTimeRFC3339(val, "Time", &c.Time) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &c.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Error. +func (e Error) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "code", e.Code) + populate(objectMap, "details", e.Details) + populate(objectMap, "innererror", e.Innererror) + populate(objectMap, "message", e.Message) + populate(objectMap, "target", e.Target) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Error. +func (e *Error) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "code": + err = unpopulate(val, "Code", &e.Code) + delete(rawMsg, key) + case "details": + err = unpopulate(val, "Details", &e.Details) + delete(rawMsg, key) + case "innererror": + err = unpopulate(val, "Innererror", &e.Innererror) + delete(rawMsg, key) + case "message": + err = unpopulate(val, "Message", &e.Message) + delete(rawMsg, key) + case "target": + err = unpopulate(val, "Target", &e.Target) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + // MarshalJSON implements the json.Marshaller interface for type FailedLockToken. func (f FailedLockToken) MarshalJSON() ([]byte, error) { objectMap := make(map[string]any) @@ -105,6 +215,37 @@ func (f *FailedLockToken) UnmarshalJSON(data []byte) error { return nil } +// MarshalJSON implements the json.Marshaller interface for type InnerError. +func (i InnerError) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "code", i.Code) + populate(objectMap, "innererror", i.Innererror) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type InnerError. +func (i *InnerError) 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 "code": + err = unpopulate(val, "Code", &i.Code) + delete(rawMsg, key) + case "innererror": + err = unpopulate(val, "Innererror", &i.Innererror) + 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 ReceiveDetails. func (r ReceiveDetails) MarshalJSON() ([]byte, error) { objectMap := make(map[string]any) @@ -137,14 +278,14 @@ func (r *ReceiveDetails) UnmarshalJSON(data []byte) error { } // MarshalJSON implements the json.Marshaller interface for type ReceiveResult. -func (r ReceiveEventsResult) MarshalJSON() ([]byte, error) { +func (r ReceiveResult) MarshalJSON() ([]byte, error) { objectMap := make(map[string]any) populate(objectMap, "value", r.Details) return json.Marshal(objectMap) } // UnmarshalJSON implements the json.Unmarshaller interface for type ReceiveResult. -func (r *ReceiveEventsResult) UnmarshalJSON(data []byte) error { +func (r *ReceiveResult) 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) @@ -164,7 +305,7 @@ func (r *ReceiveEventsResult) UnmarshalJSON(data []byte) error { } // MarshalJSON implements the json.Marshaller interface for type RejectResult. -func (r RejectEventsResult) MarshalJSON() ([]byte, error) { +func (r RejectResult) MarshalJSON() ([]byte, error) { objectMap := make(map[string]any) populate(objectMap, "failedLockTokens", r.FailedLockTokens) populate(objectMap, "succeededLockTokens", r.SucceededLockTokens) @@ -172,7 +313,7 @@ func (r RejectEventsResult) MarshalJSON() ([]byte, error) { } // UnmarshalJSON implements the json.Unmarshaller interface for type RejectResult. -func (r *RejectEventsResult) UnmarshalJSON(data []byte) error { +func (r *RejectResult) 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) @@ -195,7 +336,7 @@ func (r *RejectEventsResult) UnmarshalJSON(data []byte) error { } // MarshalJSON implements the json.Marshaller interface for type ReleaseResult. -func (r ReleaseEventsResult) MarshalJSON() ([]byte, error) { +func (r ReleaseResult) MarshalJSON() ([]byte, error) { objectMap := make(map[string]any) populate(objectMap, "failedLockTokens", r.FailedLockTokens) populate(objectMap, "succeededLockTokens", r.SucceededLockTokens) @@ -203,7 +344,7 @@ func (r ReleaseEventsResult) MarshalJSON() ([]byte, error) { } // UnmarshalJSON implements the json.Unmarshaller interface for type ReleaseResult. -func (r *ReleaseEventsResult) UnmarshalJSON(data []byte) error { +func (r *ReleaseResult) 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) @@ -226,7 +367,7 @@ func (r *ReleaseEventsResult) UnmarshalJSON(data []byte) error { } // MarshalJSON implements the json.Marshaller interface for type RenewLocksResult. -func (r RenewEventLocksResult) MarshalJSON() ([]byte, error) { +func (r RenewLocksResult) MarshalJSON() ([]byte, error) { objectMap := make(map[string]any) populate(objectMap, "failedLockTokens", r.FailedLockTokens) populate(objectMap, "succeededLockTokens", r.SucceededLockTokens) @@ -234,7 +375,7 @@ func (r RenewEventLocksResult) MarshalJSON() ([]byte, error) { } // UnmarshalJSON implements the json.Unmarshaller interface for type RenewLocksResult. -func (r *RenewEventLocksResult) UnmarshalJSON(data []byte) error { +func (r *RenewLocksResult) 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) diff --git a/sdk/messaging/eventgrid/aznamespaces/options.go b/sdk/messaging/eventgrid/aznamespaces/options.go index 5845c536f55d..c6384646ad1c 100644 --- a/sdk/messaging/eventgrid/aznamespaces/options.go +++ b/sdk/messaging/eventgrid/aznamespaces/options.go @@ -4,13 +4,13 @@ package aznamespaces -// AcknowledgeEventsOptions contains the optional parameters for the ReceiverClient.AcknowledgeEvents method. -type AcknowledgeEventsOptions struct { +// ReceiverClientAcknowledgeEventsOptions contains the optional parameters for the ReceiverClient.AcknowledgeEvents method. +type ReceiverClientAcknowledgeEventsOptions struct { // placeholder for future optional parameters } -// ReceiveEventsOptions contains the optional parameters for the ReceiverClient.ReceiveEvents method. -type ReceiveEventsOptions struct { +// ReceiverClientReceiveEventsOptions contains the optional parameters for the ReceiverClient.ReceiveEvents method. +type ReceiverClientReceiveEventsOptions struct { // Max Events count to be received. Minimum value is 1, while maximum value is 100 events. If not specified, the default value // is 1. MaxEvents *int32 @@ -22,28 +22,28 @@ type ReceiveEventsOptions struct { MaxWaitTime *int32 } -// RejectEventsOptions contains the optional parameters for the ReceiverClient.RejectEvents method. -type RejectEventsOptions struct { +// ReceiverClientRejectEventsOptions contains the optional parameters for the ReceiverClient.RejectEvents method. +type ReceiverClientRejectEventsOptions struct { // placeholder for future optional parameters } -// ReleaseEventsOptions contains the optional parameters for the ReceiverClient.ReleaseEvents method. -type ReleaseEventsOptions struct { +// ReceiverClientReleaseEventsOptions contains the optional parameters for the ReceiverClient.ReleaseEvents method. +type ReceiverClientReleaseEventsOptions struct { // Release cloud events with the specified delay in seconds. ReleaseDelayInSeconds *ReleaseDelay } -// RenewEventLocksOptions contains the optional parameters for the ReceiverClient.RenewEventLocks method. -type RenewEventLocksOptions struct { +// ReceiverClientRenewEventLocksOptions contains the optional parameters for the ReceiverClient.RenewEventLocks method. +type ReceiverClientRenewEventLocksOptions struct { // placeholder for future optional parameters } -// SendEventOptions contains the optional parameters for the SenderClient.SendEvent method. -type SendEventOptions struct { +// SenderClientSendEventOptions contains the optional parameters for the SenderClient.SendEvent method. +type SenderClientSendEventOptions struct { // placeholder for future optional parameters } -// SendEventsOptions contains the optional parameters for the SenderClient.SendEvents method. -type SendEventsOptions struct { +// SenderClientSendEventsOptions contains the optional parameters for the SenderClient.SendEvents method. +type SenderClientSendEventsOptions struct { // placeholder for future optional parameters } diff --git a/sdk/messaging/eventgrid/aznamespaces/receiver_client.go b/sdk/messaging/eventgrid/aznamespaces/receiver_client.go index f693b9622522..920359869022 100644 --- a/sdk/messaging/eventgrid/aznamespaces/receiver_client.go +++ b/sdk/messaging/eventgrid/aznamespaces/receiver_client.go @@ -7,21 +7,18 @@ package aznamespaces import ( "context" "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" "net/http" "net/url" "strconv" "strings" - - "github.com/Azure/azure-sdk-for-go/sdk/azcore" - "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" - "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" ) // ReceiverClient contains the methods for the Receiver group. // Don't use this type directly, use a constructor function instead. type ReceiverClient struct { - data receiverData - internal *azcore.Client endpoint string } @@ -37,26 +34,26 @@ type ReceiverClient struct { // - lockTokens - Array of lock tokens. // - options - ReceiverClientAcknowledgeEventsOptions contains the optional parameters for the ReceiverClient.AcknowledgeEvents // method. -func (client *ReceiverClient) internalAcknowledgeEvents(ctx context.Context, topicName string, eventSubscriptionName string, lockTokens []string, options *AcknowledgeEventsOptions) (AcknowledgeEventsResponse, error) { +func (client *ReceiverClient) AcknowledgeEvents(ctx context.Context, topicName string, eventSubscriptionName string, lockTokens []string, options *ReceiverClientAcknowledgeEventsOptions) (ReceiverClientAcknowledgeEventsResponse, error) { var err error req, err := client.acknowledgeEventsCreateRequest(ctx, topicName, eventSubscriptionName, lockTokens, options) if err != nil { - return AcknowledgeEventsResponse{}, err + return ReceiverClientAcknowledgeEventsResponse{}, err } httpResp, err := client.internal.Pipeline().Do(req) if err != nil { - return AcknowledgeEventsResponse{}, err + return ReceiverClientAcknowledgeEventsResponse{}, err } if !runtime.HasStatusCode(httpResp, http.StatusOK) { err = runtime.NewResponseError(httpResp) - return AcknowledgeEventsResponse{}, err + return ReceiverClientAcknowledgeEventsResponse{}, err } resp, err := client.acknowledgeEventsHandleResponse(httpResp) return resp, err } // acknowledgeEventsCreateRequest creates the AcknowledgeEvents request. -func (client *ReceiverClient) acknowledgeEventsCreateRequest(ctx context.Context, topicName string, eventSubscriptionName string, lockTokens []string, _ *AcknowledgeEventsOptions) (*policy.Request, error) { +func (client *ReceiverClient) acknowledgeEventsCreateRequest(ctx context.Context, topicName string, eventSubscriptionName string, lockTokens []string, _ *ReceiverClientAcknowledgeEventsOptions) (*policy.Request, error) { host := "{endpoint}" host = strings.ReplaceAll(host, "{endpoint}", client.endpoint) urlPath := "/topics/{topicName}/eventsubscriptions/{eventSubscriptionName}:acknowledge" @@ -89,10 +86,10 @@ func (client *ReceiverClient) acknowledgeEventsCreateRequest(ctx context.Context } // acknowledgeEventsHandleResponse handles the AcknowledgeEvents response. -func (client *ReceiverClient) acknowledgeEventsHandleResponse(resp *http.Response) (AcknowledgeEventsResponse, error) { - result := AcknowledgeEventsResponse{} - if err := runtime.UnmarshalAsJSON(resp, &result.AcknowledgeEventsResult); err != nil { - return AcknowledgeEventsResponse{}, err +func (client *ReceiverClient) acknowledgeEventsHandleResponse(resp *http.Response) (ReceiverClientAcknowledgeEventsResponse, error) { + result := ReceiverClientAcknowledgeEventsResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.AcknowledgeResult); err != nil { + return ReceiverClientAcknowledgeEventsResponse{}, err } return result, nil } @@ -104,26 +101,26 @@ func (client *ReceiverClient) acknowledgeEventsHandleResponse(resp *http.Respons // - topicName - Topic Name. // - eventSubscriptionName - Event Subscription Name. // - options - ReceiverClientReceiveEventsOptions contains the optional parameters for the ReceiverClient.ReceiveEvents method. -func (client *ReceiverClient) internalReceiveEvents(ctx context.Context, topicName string, eventSubscriptionName string, options *ReceiveEventsOptions) (ReceiveEventsResponse, error) { +func (client *ReceiverClient) ReceiveEvents(ctx context.Context, topicName string, eventSubscriptionName string, options *ReceiverClientReceiveEventsOptions) (ReceiverClientReceiveEventsResponse, error) { var err error req, err := client.receiveEventsCreateRequest(ctx, topicName, eventSubscriptionName, options) if err != nil { - return ReceiveEventsResponse{}, err + return ReceiverClientReceiveEventsResponse{}, err } httpResp, err := client.internal.Pipeline().Do(req) if err != nil { - return ReceiveEventsResponse{}, err + return ReceiverClientReceiveEventsResponse{}, err } if !runtime.HasStatusCode(httpResp, http.StatusOK) { err = runtime.NewResponseError(httpResp) - return ReceiveEventsResponse{}, err + return ReceiverClientReceiveEventsResponse{}, err } resp, err := client.receiveEventsHandleResponse(httpResp) return resp, err } // receiveEventsCreateRequest creates the ReceiveEvents request. -func (client *ReceiverClient) receiveEventsCreateRequest(ctx context.Context, topicName string, eventSubscriptionName string, options *ReceiveEventsOptions) (*policy.Request, error) { +func (client *ReceiverClient) receiveEventsCreateRequest(ctx context.Context, topicName string, eventSubscriptionName string, options *ReceiverClientReceiveEventsOptions) (*policy.Request, error) { host := "{endpoint}" host = strings.ReplaceAll(host, "{endpoint}", client.endpoint) urlPath := "/topics/{topicName}/eventsubscriptions/{eventSubscriptionName}:receive" @@ -153,10 +150,10 @@ func (client *ReceiverClient) receiveEventsCreateRequest(ctx context.Context, to } // receiveEventsHandleResponse handles the ReceiveEvents response. -func (client *ReceiverClient) receiveEventsHandleResponse(resp *http.Response) (ReceiveEventsResponse, error) { - result := ReceiveEventsResponse{} - if err := runtime.UnmarshalAsJSON(resp, &result.ReceiveEventsResult); err != nil { - return ReceiveEventsResponse{}, err +func (client *ReceiverClient) receiveEventsHandleResponse(resp *http.Response) (ReceiverClientReceiveEventsResponse, error) { + result := ReceiverClientReceiveEventsResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ReceiveResult); err != nil { + return ReceiverClientReceiveEventsResponse{}, err } return result, nil } @@ -171,26 +168,26 @@ func (client *ReceiverClient) receiveEventsHandleResponse(resp *http.Response) ( // - eventSubscriptionName - Event Subscription Name. // - lockTokens - Array of lock tokens. // - options - ReceiverClientRejectEventsOptions contains the optional parameters for the ReceiverClient.RejectEvents method. -func (client *ReceiverClient) internalRejectEvents(ctx context.Context, topicName string, eventSubscriptionName string, lockTokens []string, options *RejectEventsOptions) (RejectEventsResponse, error) { +func (client *ReceiverClient) RejectEvents(ctx context.Context, topicName string, eventSubscriptionName string, lockTokens []string, options *ReceiverClientRejectEventsOptions) (ReceiverClientRejectEventsResponse, error) { var err error req, err := client.rejectEventsCreateRequest(ctx, topicName, eventSubscriptionName, lockTokens, options) if err != nil { - return RejectEventsResponse{}, err + return ReceiverClientRejectEventsResponse{}, err } httpResp, err := client.internal.Pipeline().Do(req) if err != nil { - return RejectEventsResponse{}, err + return ReceiverClientRejectEventsResponse{}, err } if !runtime.HasStatusCode(httpResp, http.StatusOK) { err = runtime.NewResponseError(httpResp) - return RejectEventsResponse{}, err + return ReceiverClientRejectEventsResponse{}, err } resp, err := client.rejectEventsHandleResponse(httpResp) return resp, err } // rejectEventsCreateRequest creates the RejectEvents request. -func (client *ReceiverClient) rejectEventsCreateRequest(ctx context.Context, topicName string, eventSubscriptionName string, lockTokens []string, _ *RejectEventsOptions) (*policy.Request, error) { +func (client *ReceiverClient) rejectEventsCreateRequest(ctx context.Context, topicName string, eventSubscriptionName string, lockTokens []string, _ *ReceiverClientRejectEventsOptions) (*policy.Request, error) { host := "{endpoint}" host = strings.ReplaceAll(host, "{endpoint}", client.endpoint) urlPath := "/topics/{topicName}/eventsubscriptions/{eventSubscriptionName}:reject" @@ -223,10 +220,10 @@ func (client *ReceiverClient) rejectEventsCreateRequest(ctx context.Context, top } // rejectEventsHandleResponse handles the RejectEvents response. -func (client *ReceiverClient) rejectEventsHandleResponse(resp *http.Response) (RejectEventsResponse, error) { - result := RejectEventsResponse{} - if err := runtime.UnmarshalAsJSON(resp, &result.RejectEventsResult); err != nil { - return RejectEventsResponse{}, err +func (client *ReceiverClient) rejectEventsHandleResponse(resp *http.Response) (ReceiverClientRejectEventsResponse, error) { + result := ReceiverClientRejectEventsResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.RejectResult); err != nil { + return ReceiverClientRejectEventsResponse{}, err } return result, nil } @@ -241,26 +238,26 @@ func (client *ReceiverClient) rejectEventsHandleResponse(resp *http.Response) (R // - eventSubscriptionName - Event Subscription Name. // - lockTokens - Array of lock tokens. // - options - ReceiverClientReleaseEventsOptions contains the optional parameters for the ReceiverClient.ReleaseEvents method. -func (client *ReceiverClient) internalReleaseEvents(ctx context.Context, topicName string, eventSubscriptionName string, lockTokens []string, options *ReleaseEventsOptions) (ReleaseEventsResponse, error) { +func (client *ReceiverClient) ReleaseEvents(ctx context.Context, topicName string, eventSubscriptionName string, lockTokens []string, options *ReceiverClientReleaseEventsOptions) (ReceiverClientReleaseEventsResponse, error) { var err error req, err := client.releaseEventsCreateRequest(ctx, topicName, eventSubscriptionName, lockTokens, options) if err != nil { - return ReleaseEventsResponse{}, err + return ReceiverClientReleaseEventsResponse{}, err } httpResp, err := client.internal.Pipeline().Do(req) if err != nil { - return ReleaseEventsResponse{}, err + return ReceiverClientReleaseEventsResponse{}, err } if !runtime.HasStatusCode(httpResp, http.StatusOK) { err = runtime.NewResponseError(httpResp) - return ReleaseEventsResponse{}, err + return ReceiverClientReleaseEventsResponse{}, err } resp, err := client.releaseEventsHandleResponse(httpResp) return resp, err } // releaseEventsCreateRequest creates the ReleaseEvents request. -func (client *ReceiverClient) releaseEventsCreateRequest(ctx context.Context, topicName string, eventSubscriptionName string, lockTokens []string, options *ReleaseEventsOptions) (*policy.Request, error) { +func (client *ReceiverClient) releaseEventsCreateRequest(ctx context.Context, topicName string, eventSubscriptionName string, lockTokens []string, options *ReceiverClientReleaseEventsOptions) (*policy.Request, error) { host := "{endpoint}" host = strings.ReplaceAll(host, "{endpoint}", client.endpoint) urlPath := "/topics/{topicName}/eventsubscriptions/{eventSubscriptionName}:release" @@ -296,10 +293,10 @@ func (client *ReceiverClient) releaseEventsCreateRequest(ctx context.Context, to } // releaseEventsHandleResponse handles the ReleaseEvents response. -func (client *ReceiverClient) releaseEventsHandleResponse(resp *http.Response) (ReleaseEventsResponse, error) { - result := ReleaseEventsResponse{} - if err := runtime.UnmarshalAsJSON(resp, &result.ReleaseEventsResult); err != nil { - return ReleaseEventsResponse{}, err +func (client *ReceiverClient) releaseEventsHandleResponse(resp *http.Response) (ReceiverClientReleaseEventsResponse, error) { + result := ReceiverClientReleaseEventsResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ReleaseResult); err != nil { + return ReceiverClientReleaseEventsResponse{}, err } return result, nil } @@ -315,26 +312,26 @@ func (client *ReceiverClient) releaseEventsHandleResponse(resp *http.Response) ( // - lockTokens - Array of lock tokens. // - options - ReceiverClientRenewEventLocksOptions contains the optional parameters for the ReceiverClient.RenewEventLocks // method. -func (client *ReceiverClient) internalRenewEventLocks(ctx context.Context, topicName string, eventSubscriptionName string, lockTokens []string, options *RenewEventLocksOptions) (RenewEventLocksResponse, error) { +func (client *ReceiverClient) RenewEventLocks(ctx context.Context, topicName string, eventSubscriptionName string, lockTokens []string, options *ReceiverClientRenewEventLocksOptions) (ReceiverClientRenewEventLocksResponse, error) { var err error req, err := client.renewEventLocksCreateRequest(ctx, topicName, eventSubscriptionName, lockTokens, options) if err != nil { - return RenewEventLocksResponse{}, err + return ReceiverClientRenewEventLocksResponse{}, err } httpResp, err := client.internal.Pipeline().Do(req) if err != nil { - return RenewEventLocksResponse{}, err + return ReceiverClientRenewEventLocksResponse{}, err } if !runtime.HasStatusCode(httpResp, http.StatusOK) { err = runtime.NewResponseError(httpResp) - return RenewEventLocksResponse{}, err + return ReceiverClientRenewEventLocksResponse{}, err } resp, err := client.renewEventLocksHandleResponse(httpResp) return resp, err } // renewEventLocksCreateRequest creates the RenewEventLocks request. -func (client *ReceiverClient) renewEventLocksCreateRequest(ctx context.Context, topicName string, eventSubscriptionName string, lockTokens []string, _ *RenewEventLocksOptions) (*policy.Request, error) { +func (client *ReceiverClient) renewEventLocksCreateRequest(ctx context.Context, topicName string, eventSubscriptionName string, lockTokens []string, _ *ReceiverClientRenewEventLocksOptions) (*policy.Request, error) { host := "{endpoint}" host = strings.ReplaceAll(host, "{endpoint}", client.endpoint) urlPath := "/topics/{topicName}/eventsubscriptions/{eventSubscriptionName}:renewLock" @@ -367,10 +364,10 @@ func (client *ReceiverClient) renewEventLocksCreateRequest(ctx context.Context, } // renewEventLocksHandleResponse handles the RenewEventLocks response. -func (client *ReceiverClient) renewEventLocksHandleResponse(resp *http.Response) (RenewEventLocksResponse, error) { - result := RenewEventLocksResponse{} - if err := runtime.UnmarshalAsJSON(resp, &result.RenewEventLocksResult); err != nil { - return RenewEventLocksResponse{}, err +func (client *ReceiverClient) renewEventLocksHandleResponse(resp *http.Response) (ReceiverClientRenewEventLocksResponse, error) { + result := ReceiverClientRenewEventLocksResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.RenewLocksResult); err != nil { + return ReceiverClientRenewEventLocksResponse{}, err } return result, nil } diff --git a/sdk/messaging/eventgrid/aznamespaces/receiver_client_custom.go b/sdk/messaging/eventgrid/aznamespaces/receiver_client_custom.go deleted file mode 100644 index 66ea3354ac6b..000000000000 --- a/sdk/messaging/eventgrid/aznamespaces/receiver_client_custom.go +++ /dev/null @@ -1,140 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. - -package aznamespaces - -import ( - "context" - - "github.com/Azure/azure-sdk-for-go/sdk/azcore" - "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" - "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" - "github.com/Azure/azure-sdk-for-go/sdk/messaging/eventgrid/aznamespaces/internal" -) - -// ReceiverClientOptions contains the optional parameters when creating a ReceiverClient. -type ReceiverClientOptions struct { - azcore.ClientOptions -} - -// NewReceiverClient creates a [ReceiverClient] which uses an azcore.TokenCredential for authentication. -// - topicName - Topic Name. -// - subscriptionName - Event Subscription Name. -func NewReceiverClient(endpoint string, topic string, subscription string, cred azcore.TokenCredential, options *ReceiverClientOptions) (*ReceiverClient, error) { - if options == nil { - options = &ReceiverClientOptions{} - } - - azc, err := azcore.NewClient(internal.ModuleName+".Client", internal.ModuleVersion, runtime.PipelineOptions{ - PerRetry: []policy.Policy{ - runtime.NewBearerTokenPolicy(cred, []string{authScope}, nil), - }, - }, &options.ClientOptions) - - if err != nil { - return nil, err - } - - return &ReceiverClient{ - internal: azc, - endpoint: endpoint, - data: receiverData{ - topic: topic, - subscription: subscription, - }, - }, nil -} - -// NewReceiverClientWithSharedKeyCredential creates a [ReceiverClient] using a shared key. -// - topicName - Topic Name. -// - subscriptionName - Event Subscription Name. -func NewReceiverClientWithSharedKeyCredential(endpoint string, topic string, subscription string, keyCred *azcore.KeyCredential, options *ReceiverClientOptions) (*ReceiverClient, error) { - if options == nil { - options = &ReceiverClientOptions{} - } - - azc, err := azcore.NewClient(internal.ModuleName+".Client", internal.ModuleVersion, runtime.PipelineOptions{ - PerRetry: []policy.Policy{ - runtime.NewKeyCredentialPolicy(keyCred, "Authorization", &runtime.KeyCredentialPolicyOptions{ - Prefix: "SharedAccessKey ", - }), - }, - }, &options.ClientOptions) - - if err != nil { - return nil, err - } - - return &ReceiverClient{ - internal: azc, - endpoint: endpoint, - data: receiverData{ - topic: topic, - subscription: subscription, - }, - }, nil -} - -// RejectEvents rejects a batch of Cloud Events. The server responds with an HTTP 200 status code if the request is successfully -// accepted. The response body will include the set of successfully rejected lockTokens, -// along with other failed lockTokens with their corresponding error information. -// If the operation fails it returns an *azcore.ResponseError type. -// -// Generated from API version 2024-06-01 -// - lockTokens - slice of lock tokens. -// - options - RejectEventsOptions contains the optional parameters for the ReceiverClient.RejectEvents method. -func (client *ReceiverClient) RejectEvents(ctx context.Context, lockTokens []string, options *RejectEventsOptions) (RejectEventsResponse, error) { - return client.internalRejectEvents(ctx, client.data.topic, client.data.subscription, lockTokens, options) -} - -// AcknowledgeEvents acknowledges a batch of Cloud Events. The server responds with an HTTP 200 status code if the request -// is successfully accepted. The response body will include the set of successfully acknowledged -// lockTokens, along with other failed lockTokens with their corresponding error information. Successfully acknowledged events -// will no longer be available to any consumer. -// If the operation fails it returns an *azcore.ResponseError type. -// -// Generated from API version 2024-06-01 -// - lockTokens - slice of lock tokens. -// - options - AcknowledgeEventsOptions contains the optional parameters for the ReceiverClient.AcknowledgeEvents method. -func (client *ReceiverClient) AcknowledgeEvents(ctx context.Context, lockTokens []string, options *AcknowledgeEventsOptions) (AcknowledgeEventsResponse, error) { - return client.internalAcknowledgeEvents(ctx, client.data.topic, client.data.subscription, lockTokens, options) -} - -// ReleaseEvents releases a batch of Cloud Events. The server responds with an HTTP 200 status code if the request is -// successfully accepted. The response body will include the set of successfully released lockTokens, -// along with other failed lockTokens with their corresponding error information. -// If the operation fails it returns an *azcore.ResponseError type. -// -// Generated from API version 2024-06-01 -// - lockTokens - slice of lock tokens. -// - options - ReleaseEventsOptions contains the optional parameters for the ReceiverClient.ReleaseEvents method. -func (client *ReceiverClient) ReleaseEvents(ctx context.Context, lockTokens []string, options *ReleaseEventsOptions) (ReleaseEventsResponse, error) { - return client.internalReleaseEvents(ctx, client.data.topic, client.data.subscription, lockTokens, options) -} - -// RenewEventLocks renews locks for batch of Cloud Events. The server responds with an HTTP 200 status code if the request -// is successfully accepted. The response body will include the set of successfully renewed -// lockTokens, along with other failed lockTokens with their corresponding error information. -// If the operation fails it returns an *azcore.ResponseError type. -// -// Generated from API version 2024-06-01 -// - lockTokens - slice of lock tokens. -// - options - RenewLocksOptions contains the optional parameters for the ReceiverClient.RenewLocks method. -func (client *ReceiverClient) RenewEventLocks(ctx context.Context, lockTokens []string, options *RenewEventLocksOptions) (RenewEventLocksResponse, error) { - return client.internalRenewEventLocks(ctx, client.data.topic, client.data.subscription, lockTokens, options) -} - -// ReceiveEvents receives a batch of Cloud Events from a subscription. -// If the operation fails it returns an *azcore.ResponseError type. -// -// Generated from API version 2024-06-01 -// - options - ReceiveEventsOptions contains the optional parameters for the ReceiverClient.ReceiveEvents method. -func (client *ReceiverClient) ReceiveEvents(ctx context.Context, options *ReceiveEventsOptions) (ReceiveEventsResponse, error) { - return client.internalReceiveEvents(ctx, client.data.topic, client.data.subscription, options) -} - -type receiverData struct { - topic string - subscription string -} diff --git a/sdk/messaging/eventgrid/aznamespaces/responses.go b/sdk/messaging/eventgrid/aznamespaces/responses.go index 55700b10b61e..c2e3e7f9f677 100644 --- a/sdk/messaging/eventgrid/aznamespaces/responses.go +++ b/sdk/messaging/eventgrid/aznamespaces/responses.go @@ -4,40 +4,44 @@ package aznamespaces -// AcknowledgeEventsResponse contains the response from method ReceiverClient.AcknowledgeEvents. -type AcknowledgeEventsResponse struct { +// ReceiverClientAcknowledgeEventsResponse contains the response from method ReceiverClient.AcknowledgeEvents. +type ReceiverClientAcknowledgeEventsResponse struct { // The result of the Acknowledge operation. - AcknowledgeEventsResult + AcknowledgeResult } -// ReceiveEventsResponse contains the response from method ReceiverClient.ReceiveEvents. -type ReceiveEventsResponse struct { +// ReceiverClientReceiveEventsResponse contains the response from method ReceiverClient.ReceiveEvents. +type ReceiverClientReceiveEventsResponse struct { // Details of the Receive operation response. - ReceiveEventsResult + ReceiveResult } -// RejectEventsResponse contains the response from method ReceiverClient.RejectEvents. -type RejectEventsResponse struct { +// ReceiverClientRejectEventsResponse contains the response from method ReceiverClient.RejectEvents. +type ReceiverClientRejectEventsResponse struct { // The result of the Reject operation. - RejectEventsResult + RejectResult } -// ReleaseEventsResponse contains the response from method ReceiverClient.ReleaseEvents. -type ReleaseEventsResponse struct { +// ReceiverClientReleaseEventsResponse contains the response from method ReceiverClient.ReleaseEvents. +type ReceiverClientReleaseEventsResponse struct { // The result of the Release operation. - ReleaseEventsResult + ReleaseResult } -// RenewEventLocksResponse contains the response from method ReceiverClient.RenewEventLocks. -type RenewEventLocksResponse struct { +// ReceiverClientRenewEventLocksResponse contains the response from method ReceiverClient.RenewEventLocks. +type ReceiverClientRenewEventLocksResponse struct { // The result of the RenewLock operation. - RenewEventLocksResult + RenewLocksResult } -// SendEventResponse contains the response from method SenderClient.SendEvent. -type SendEventResponse struct { +// SenderClientSendEventResponse contains the response from method SenderClient.SendEvent. +type SenderClientSendEventResponse struct { + // The result of the Publish operation. + PublishResult } -// SendEventsResponse contains the response from method SenderClient.SendEvents. -type SendEventsResponse struct { +// SenderClientSendEventsResponse contains the response from method SenderClient.SendEvents. +type SenderClientSendEventsResponse struct { + // The result of the Publish operation. + PublishResult } diff --git a/sdk/messaging/eventgrid/aznamespaces/sender_client.go b/sdk/messaging/eventgrid/aznamespaces/sender_client.go index 31c41ae19142..c973630383d8 100644 --- a/sdk/messaging/eventgrid/aznamespaces/sender_client.go +++ b/sdk/messaging/eventgrid/aznamespaces/sender_client.go @@ -7,21 +7,17 @@ package aznamespaces import ( "context" "errors" - "net/http" - "net/url" - "strings" - "github.com/Azure/azure-sdk-for-go/sdk/azcore" - "github.com/Azure/azure-sdk-for-go/sdk/azcore/messaging" "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" ) // SenderClient contains the methods for the Sender group. // Don't use this type directly, use a constructor function instead. type SenderClient struct { - data senderData - internal *azcore.Client endpoint string } @@ -33,26 +29,26 @@ type SenderClient struct { // - topicName - Topic Name. // - event - Single Cloud Event being published. // - options - SenderClientSendEventOptions contains the optional parameters for the SenderClient.SendEvent method. -func (client *SenderClient) internalSendEvent(ctx context.Context, topicName string, event *messaging.CloudEvent, options *SendEventOptions) (SendEventResponse, error) { +func (client *SenderClient) SendEvent(ctx context.Context, topicName string, event CloudEvent, options *SenderClientSendEventOptions) (SenderClientSendEventResponse, error) { var err error req, err := client.sendEventCreateRequest(ctx, topicName, event, options) if err != nil { - return SendEventResponse{}, err + return SenderClientSendEventResponse{}, err } httpResp, err := client.internal.Pipeline().Do(req) if err != nil { - return SendEventResponse{}, err + return SenderClientSendEventResponse{}, err } if !runtime.HasStatusCode(httpResp, http.StatusOK) { err = runtime.NewResponseError(httpResp) - return SendEventResponse{}, err + return SenderClientSendEventResponse{}, err } resp, err := client.sendEventHandleResponse(httpResp) return resp, err } // sendEventCreateRequest creates the SendEvent request. -func (client *SenderClient) sendEventCreateRequest(ctx context.Context, topicName string, event *messaging.CloudEvent, _ *SendEventOptions) (*policy.Request, error) { +func (client *SenderClient) sendEventCreateRequest(ctx context.Context, topicName string, event CloudEvent, _ *SenderClientSendEventOptions) (*policy.Request, error) { host := "{endpoint}" host = strings.ReplaceAll(host, "{endpoint}", client.endpoint) urlPath := "/topics/{topicName}:publish" @@ -76,8 +72,11 @@ func (client *SenderClient) sendEventCreateRequest(ctx context.Context, topicNam } // sendEventHandleResponse handles the SendEvent response. -func (client *SenderClient) sendEventHandleResponse(_ *http.Response) (SendEventResponse, error) { - result := SendEventResponse{} +func (client *SenderClient) sendEventHandleResponse(resp *http.Response) (SenderClientSendEventResponse, error) { + result := SenderClientSendEventResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.PublishResult); err != nil { + return SenderClientSendEventResponse{}, err + } return result, nil } @@ -88,26 +87,26 @@ func (client *SenderClient) sendEventHandleResponse(_ *http.Response) (SendEvent // - topicName - Topic Name. // - events - Array of Cloud Events being published. // - options - SenderClientSendEventsOptions contains the optional parameters for the SenderClient.SendEvents method. -func (client *SenderClient) internalSendEvents(ctx context.Context, topicName string, events []*messaging.CloudEvent, options *SendEventsOptions) (SendEventsResponse, error) { +func (client *SenderClient) SendEvents(ctx context.Context, topicName string, events []CloudEvent, options *SenderClientSendEventsOptions) (SenderClientSendEventsResponse, error) { var err error req, err := client.sendEventsCreateRequest(ctx, topicName, events, options) if err != nil { - return SendEventsResponse{}, err + return SenderClientSendEventsResponse{}, err } httpResp, err := client.internal.Pipeline().Do(req) if err != nil { - return SendEventsResponse{}, err + return SenderClientSendEventsResponse{}, err } if !runtime.HasStatusCode(httpResp, http.StatusOK) { err = runtime.NewResponseError(httpResp) - return SendEventsResponse{}, err + return SenderClientSendEventsResponse{}, err } resp, err := client.sendEventsHandleResponse(httpResp) return resp, err } // sendEventsCreateRequest creates the SendEvents request. -func (client *SenderClient) sendEventsCreateRequest(ctx context.Context, topicName string, events []*messaging.CloudEvent, _ *SendEventsOptions) (*policy.Request, error) { +func (client *SenderClient) sendEventsCreateRequest(ctx context.Context, topicName string, events []CloudEvent, _ *SenderClientSendEventsOptions) (*policy.Request, error) { host := "{endpoint}" host = strings.ReplaceAll(host, "{endpoint}", client.endpoint) urlPath := "/topics/{topicName}:publish" @@ -131,7 +130,10 @@ func (client *SenderClient) sendEventsCreateRequest(ctx context.Context, topicNa } // sendEventsHandleResponse handles the SendEvents response. -func (client *SenderClient) sendEventsHandleResponse(_ *http.Response) (SendEventsResponse, error) { - result := SendEventsResponse{} +func (client *SenderClient) sendEventsHandleResponse(resp *http.Response) (SenderClientSendEventsResponse, error) { + result := SenderClientSendEventsResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.PublishResult); err != nil { + return SenderClientSendEventsResponse{}, err + } return result, nil } diff --git a/sdk/messaging/eventgrid/aznamespaces/sender_client_custom.go b/sdk/messaging/eventgrid/aznamespaces/sender_client_custom.go deleted file mode 100644 index e2c45685d817..000000000000 --- a/sdk/messaging/eventgrid/aznamespaces/sender_client_custom.go +++ /dev/null @@ -1,96 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. - -package aznamespaces - -import ( - "context" - - "github.com/Azure/azure-sdk-for-go/sdk/azcore" - "github.com/Azure/azure-sdk-for-go/sdk/azcore/messaging" - "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" - "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" - "github.com/Azure/azure-sdk-for-go/sdk/messaging/eventgrid/aznamespaces/internal" -) - -// SenderClientOptions contains the optional parameters when creating a SenderClient. -type SenderClientOptions struct { - azcore.ClientOptions -} - -// NewSenderClient creates a [SenderClient] which uses an azcore.TokenCredential for authentication. -func NewSenderClient(endpoint string, topic string, cred azcore.TokenCredential, options *SenderClientOptions) (*SenderClient, error) { - if options == nil { - options = &SenderClientOptions{} - } - - azc, err := azcore.NewClient(internal.ModuleName+".Client", internal.ModuleVersion, runtime.PipelineOptions{ - PerRetry: []policy.Policy{ - runtime.NewBearerTokenPolicy(cred, []string{authScope}, nil), - }, - }, &options.ClientOptions) - - if err != nil { - return nil, err - } - - return &SenderClient{ - internal: azc, - endpoint: endpoint, - data: senderData{ - Topic: topic, - }, - }, nil -} - -// NewSenderClientWithSharedKeyCredential creates a [SenderClient] using a shared key. -func NewSenderClientWithSharedKeyCredential(endpoint string, topic string, keyCred *azcore.KeyCredential, options *SenderClientOptions) (*SenderClient, error) { - if options == nil { - options = &SenderClientOptions{} - } - - azc, err := azcore.NewClient(internal.ModuleName+".Client", internal.ModuleVersion, runtime.PipelineOptions{ - PerRetry: []policy.Policy{ - runtime.NewKeyCredentialPolicy(keyCred, "Authorization", &runtime.KeyCredentialPolicyOptions{ - Prefix: "SharedAccessKey ", - }), - }, - }, &options.ClientOptions) - - if err != nil { - return nil, err - } - - return &SenderClient{ - internal: azc, - endpoint: endpoint, - data: senderData{ - Topic: topic, - }, - }, nil -} - -type senderData struct { - Topic string -} - -// SendEvent publishes a single Cloud Event to a namespace topic. -// If the operation fails it returns an *azcore.ResponseError type. -// -// Generated from API version 2024-06-01 -// - event - Cloud Event to publish. -// - options - SendOptions contains the optional parameters for the SenderClient.SendEvent method. -func (client *SenderClient) SendEvent(ctx context.Context, event *messaging.CloudEvent, options *SendEventOptions) (SendEventResponse, error) { - return client.internalSendEvent(ctx, client.data.Topic, event, options) -} - -// SendEvents publishes a batch of Cloud Events to a namespace topic. -// If the operation fails it returns an *azcore.ResponseError type. -// -// Generated from API version 2024-06-01 -// - events - slice of Cloud Events to publish. -// - options - SendEventsOptions contains the optional parameters for the SenderClient.SendEvents method. -func (client *SenderClient) SendEvents(ctx context.Context, events []*messaging.CloudEvent, options *SendEventsOptions) (SendEventsResponse, error) { - return client.internalSendEvents(ctx, client.data.Topic, events, options) -} diff --git a/sdk/messaging/eventgrid/aznamespaces/time_rfc3339.go b/sdk/messaging/eventgrid/aznamespaces/time_rfc3339.go index 9fa0bee9e256..6e37ba42202d 100644 --- a/sdk/messaging/eventgrid/aznamespaces/time_rfc3339.go +++ b/sdk/messaging/eventgrid/aznamespaces/time_rfc3339.go @@ -7,12 +7,11 @@ package aznamespaces import ( "encoding/json" "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" "reflect" "regexp" "strings" "time" - - "github.com/Azure/azure-sdk-for-go/sdk/azcore" ) // Azure reports time in UTC but it doesn't include the 'Z' time zone suffix in some cases. diff --git a/sdk/messaging/eventgrid/aznamespaces/tsp-location.yaml b/sdk/messaging/eventgrid/aznamespaces/tsp-location.yaml index a9f6493d90e4..d5f30841e7ef 100644 --- a/sdk/messaging/eventgrid/aznamespaces/tsp-location.yaml +++ b/sdk/messaging/eventgrid/aznamespaces/tsp-location.yaml @@ -1,3 +1,4 @@ directory: specification/eventgrid/Azure.Messaging.EventGrid -commit: 8d6deb81acb126a071f6f7dbf18d87a49a82e7e2 +commit: 1f578543d267d08febc1bebf4e33ffe14363ddfc repo: Azure/azure-rest-api-specs +additionalDirectories: diff --git a/sdk/messaging/eventgrid/azsystemevents/CHANGELOG.md b/sdk/messaging/eventgrid/azsystemevents/CHANGELOG.md index ac40b2915569..2debe5f424e3 100644 --- a/sdk/messaging/eventgrid/azsystemevents/CHANGELOG.md +++ b/sdk/messaging/eventgrid/azsystemevents/CHANGELOG.md @@ -1,5 +1,55 @@ # Release History +## 1.0.0 (2025-04-27) +### Breaking Changes + +- Type of `ACSMessageDeliveryStatusUpdatedEventData.Error` has been changed from `*Error` to `*InternalACSMessageChannelEventError` +- Type of `ACSMessageReceivedEventData.Error` has been changed from `*Error` to `*InternalACSMessageChannelEventError` +- Type of `ACSRouterJobClassificationFailedEventData.Errors` has been changed from `[]*Error` to `[]InternalACSRouterCommunicationError` + +### Features Added + +- New value `TypeACSCallEnded`, `TypeACSCallParticipantAdded`, `TypeACSCallParticipantRemoved`, `TypeACSCallStarted`, `TypeACSChatAzureBotCommandReceivedInThread`, `TypeACSChatTypingIndicatorReceivedInThread` added to enum type `string` +- New struct `ACSChatEventBaseProperties` +- New struct `ACSChatEventInThreadBaseProperties` +- New struct `ACSChatMessageEventBaseProperties` +- New struct `ACSChatMessageEventInThreadBaseProperties` +- New struct `ACSChatThreadEventBaseProperties` +- New struct `ACSChatThreadEventInThreadBaseProperties` +- New struct `ACSMessageEventData` +- New struct `ACSRouterEventData` +- New struct `ACSRouterJobEventData` +- New struct `ACSRouterWorkerEventData` +- New struct `ACSSMSEventBaseProperties` +- New struct `APIManagementCircuitBreakerClosedEventData` +- New struct `APIManagementCircuitBreakerOpenedEventData` +- New struct `APIManagementCircuitBreakerProperties` +- New struct `APIManagementCircuitBreakerPropertiesRule` +- New struct `APIManagementExpiredGatewayTokenProperties` +- New struct `APIManagementGatewayProperties` +- New struct `APIManagementGatewayTokenExpiredEventData` +- New struct `APIManagementGatewayTokenNearExpiryEventData` +- New struct `APIManagementNearExpiryGatewayTokenProperties` +- New struct `AVSClusterEventData` +- New struct `AVSPrivateCloudEventData` +- New struct `AVSScriptExecutionEventData` +- New struct `AppConfigurationSnapshotEventData` +- New struct `ContainerRegistryArtifactEventData` +- New struct `ContainerRegistryEventData` +- New struct `ContainerServiceClusterSupportEventData` +- New struct `ContainerServiceNodePoolRollingEventData` +- New struct `DeviceConnectionStateEventProperties` +- New struct `DeviceLifeCycleEventProperties` +- New struct `DeviceTelemetryEventProperties` +- New struct `EdgeSolutionVersionPublishedEventData` +- New struct `EventGridMQTTClientEventData` +- New struct `InternalACSMessageChannelEventError` +- New struct `InternalACSRouterCommunicationError` +- New struct `MapsGeofenceEventProperties` +- New struct `ResourceNotificationsResourceDeletedEventData` +- New struct `ResourceNotificationsResourceUpdatedEventData` + + ## 0.6.2 (2025-05-06) ### Features Added diff --git a/sdk/messaging/eventgrid/azsystemevents/build.go b/sdk/messaging/eventgrid/azsystemevents/build.go deleted file mode 100644 index e22b15cc1977..000000000000 --- a/sdk/messaging/eventgrid/azsystemevents/build.go +++ /dev/null @@ -1,12 +0,0 @@ -//go:build go1.18 -// +build go1.18 - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. - -//go:generate tsp-client update -//go:generate goimports -w . -//go:generate go run ./internal/generate -//go:generate goimports -w ./.. - -package azsystemevents diff --git a/sdk/messaging/eventgrid/azsystemevents/constants.go b/sdk/messaging/eventgrid/azsystemevents/constants.go index f4437dd1f2b7..4afe33ece5ca 100644 --- a/sdk/messaging/eventgrid/azsystemevents/constants.go +++ b/sdk/messaging/eventgrid/azsystemevents/constants.go @@ -4,24 +4,6 @@ package azsystemevents -// ACSCallEndedByKind - Call ended participant kind. -type ACSCallEndedByKind string - -const ( - // ACSCallEndedByKindMicrosoftInternal - MicrosoftInternal - ACSCallEndedByKindMicrosoftInternal ACSCallEndedByKind = "MicrosoftInternal" - // ACSCallEndedByKindParticipant - Participant - ACSCallEndedByKindParticipant ACSCallEndedByKind = "Participant" -) - -// PossibleACSCallEndedByKindValues returns the possible values for the ACSCallEndedByKind const type. -func PossibleACSCallEndedByKindValues() []ACSCallEndedByKind { - return []ACSCallEndedByKind{ - ACSCallEndedByKindMicrosoftInternal, - ACSCallEndedByKindParticipant, - } -} - // ACSEmailDeliveryReportStatus - The status of the email. Any value other than Delivered is considered failed. type ACSEmailDeliveryReportStatus string diff --git a/sdk/messaging/eventgrid/azsystemevents/models.go b/sdk/messaging/eventgrid/azsystemevents/models.go index 60e62244b03b..a9f925d8cc82 100644 --- a/sdk/messaging/eventgrid/azsystemevents/models.go +++ b/sdk/messaging/eventgrid/azsystemevents/models.go @@ -6,272 +6,23 @@ package azsystemevents import "time" -// ACSCallEndReasonProperties - Schema of calling event reason properties -type ACSCallEndReasonProperties struct { - // Reason code for ending the call. - Code *int32 - - // Reason for the ending the call. - Phrase *string - - // Reason subcode for ending the call. - SubCode *int32 -} - -// ACSCallEndedByProperties - Schema of calling event endedby properties -type ACSCallEndedByProperties struct { - // REQUIRED; The communication identifier of the call ended by - CommunicationIdentifier *CommunicationIdentifierModel - - // REQUIRED; The name of the call ended by. - Name *string - - // REQUIRED; The type of call ended by. - Type *ACSCallEndedByKind -} - -// ACSCallEndedEventData - Schema of the Data property of an EventGridEvent for a Microsoft.Communication.CallEnded event. -type ACSCallEndedEventData struct { - // REQUIRED; The correlationId of calling event - CorrelationID *string - - // REQUIRED; The call id of the server - ServerCallID *string - - // REQUIRED; The call participant who initiated the call. - StartedBy *ACSCallParticipantProperties - - // Duration of the call in seconds. - CallDurationInSeconds *float64 - - // The communication identifier of the user who was disconnected - EndedBy *ACSCallEndedByProperties - - // The group metadata - Group *ACSCallGroupProperties - - // Is the calling event a room call. - IsRoomsCall *bool - - // Is two-party in calling event. - IsTwoParty *bool - - // The reason for ending the call. - Reason *ACSCallEndReasonProperties - - // The room metadata - Room *ACSCallRoomProperties -} - -// ACSCallGroupProperties - Schema of calling event group properties -type ACSCallGroupProperties struct { - // Group Id. - ID *string -} - -// ACSCallParticipantAddedEventData - Schema of the Data property of an EventGridEvent for a Microsoft.Communication.CallParticipantAdded -// event. -type ACSCallParticipantAddedEventData struct { - // REQUIRED; The correlationId of calling event - CorrelationID *string - - // REQUIRED; The call id of the server - ServerCallID *string - - // REQUIRED; The call participant who initiated the call. - StartedBy *ACSCallParticipantProperties - - // The display name of the participant. - DisplayName *string - - // The group metadata - Group *ACSCallGroupProperties - - // Is the calling event a room call. - IsRoomsCall *bool - - // Is two-party in calling event. - IsTwoParty *bool - - // The id of the participant. - ParticipantID *string - - // The room metadata - Room *ACSCallRoomProperties - - // The user of the call participant - User *ACSCallParticipantProperties - - // The user agent of the participant. - UserAgent *string -} - -// ACSCallParticipantEventProperties - Schema of common properties of all participant events -type ACSCallParticipantEventProperties struct { - // REQUIRED; The correlationId of calling event - CorrelationID *string - - // REQUIRED; The call id of the server - ServerCallID *string - - // REQUIRED; The call participant who initiated the call. - StartedBy *ACSCallParticipantProperties - - // The display name of the participant. - DisplayName *string - - // The group metadata - Group *ACSCallGroupProperties - - // Is the calling event a room call. - IsRoomsCall *bool - - // Is two-party in calling event. - IsTwoParty *bool - - // The id of the participant. - ParticipantID *string - - // The room metadata - Room *ACSCallRoomProperties - - // The user of the call participant - User *ACSCallParticipantProperties - - // The user agent of the participant. - UserAgent *string -} - -// ACSCallParticipantProperties - Schema of common properties of all participant event user -type ACSCallParticipantProperties struct { - // The communication identifier of the participant user - CommunicationIdentifier *CommunicationIdentifierModel - - // The role of the participant - Role *string -} - -// ACSCallParticipantRemovedEventData - Schema of the Data property of an EventGridEvent for a Microsoft.Communication.CallParticipantRemoved -// event. -type ACSCallParticipantRemovedEventData struct { - // REQUIRED; The correlationId of calling event - CorrelationID *string - - // REQUIRED; The call id of the server - ServerCallID *string - - // REQUIRED; The call participant who initiated the call. - StartedBy *ACSCallParticipantProperties - - // The display name of the participant. - DisplayName *string - - // The group metadata - Group *ACSCallGroupProperties - - // Is the calling event a room call. - IsRoomsCall *bool - - // Is two-party in calling event. - IsTwoParty *bool - - // The id of the participant. - ParticipantID *string - - // The room metadata - Room *ACSCallRoomProperties - - // The user of the call participant - User *ACSCallParticipantProperties - - // The user agent of the participant. - UserAgent *string -} - -// ACSCallRoomProperties - Schema of calling event room properties -type ACSCallRoomProperties struct { - // Room Id. - ID *string -} - -// ACSCallStartedEventData - Schema of the Data property of an EventGridEvent for a Microsoft.Communication.CallStarted event. -type ACSCallStartedEventData struct { - // REQUIRED; The correlationId of calling event - CorrelationID *string - - // REQUIRED; The call id of the server - ServerCallID *string - - // REQUIRED; The call participant who initiated the call. - StartedBy *ACSCallParticipantProperties - - // The group metadata - Group *ACSCallGroupProperties - - // Is the calling event a room call. - IsRoomsCall *bool - - // Is two-party in calling event. - IsTwoParty *bool - - // The room metadata - Room *ACSCallRoomProperties -} - -// ACSCallingEventProperties - Schema of common properties of all calling events -type ACSCallingEventProperties struct { - // REQUIRED; The correlationId of calling event - CorrelationID *string - - // REQUIRED; The call id of the server - ServerCallID *string - - // REQUIRED; The call participant who initiated the call. - StartedBy *ACSCallParticipantProperties - - // The group metadata - Group *ACSCallGroupProperties - - // Is the calling event a room call. - IsRoomsCall *bool +// ACSChatEventBaseProperties - Schema of common properties of all chat events +type ACSChatEventBaseProperties struct { + // REQUIRED; The communication identifier of the target user + RecipientCommunicationIdentifier *CommunicationIdentifierModel - // Is two-party in calling event. - IsTwoParty *bool + // The chat thread id + ThreadID *string - // The room metadata - Room *ACSCallRoomProperties + // The transaction id will be used as co-relation vector + TransactionID *string } -// ACSChatAzureBotCommandReceivedInThreadEventData - Schema of the Data property of an EventGridEvent for a Microsoft.Communication.ChatAzureBotCommandReceivedInThread -// event. -type ACSChatAzureBotCommandReceivedInThreadEventData struct { - // REQUIRED; The original compose time of the message - ComposeTime *time.Time - - // REQUIRED; The body of the chat message - MessageBody *string - - // REQUIRED; The chat message id - MessageID *string - - // REQUIRED; The communication identifier of the sender - SenderCommunicationIdentifier *CommunicationIdentifierModel - - // REQUIRED; The chat thread id +// ACSChatEventInThreadBaseProperties - Schema of common properties of all thread-level chat events +type ACSChatEventInThreadBaseProperties struct { + // The chat thread id ThreadID *string - // REQUIRED; The type of the message - Type *string - - // REQUIRED; The version of the message - Version *int64 - - // The chat message metadata - Metadata map[string]*string - - // The display name of the sender - SenderDisplayName *string - // The transaction id will be used as co-relation vector TransactionID *string } @@ -285,29 +36,29 @@ type ACSChatMessageDeletedEventData struct { // REQUIRED; The time at which the message was deleted DeleteTime *time.Time - // REQUIRED; The chat message id - MessageID *string - // REQUIRED; The communication identifier of the target user RecipientCommunicationIdentifier *CommunicationIdentifierModel // REQUIRED; The communication identifier of the sender SenderCommunicationIdentifier *CommunicationIdentifierModel - // REQUIRED; The chat thread id - ThreadID *string - - // REQUIRED; The type of the message - Type *string - - // REQUIRED; The version of the message - Version *int64 + // The chat message id + MessageID *string // The display name of the sender SenderDisplayName *string + // The chat thread id + ThreadID *string + // The transaction id will be used as co-relation vector TransactionID *string + + // The type of the message + Type *string + + // The version of the message + Version *int64 } // ACSChatMessageDeletedInThreadEventData - Schema of the Data property of an EventGridEvent for a Microsoft.Communication.ChatMessageDeletedInThread @@ -319,26 +70,26 @@ type ACSChatMessageDeletedInThreadEventData struct { // REQUIRED; The time at which the message was deleted DeleteTime *time.Time - // REQUIRED; The chat message id - MessageID *string - // REQUIRED; The communication identifier of the sender SenderCommunicationIdentifier *CommunicationIdentifierModel - // REQUIRED; The chat thread id - ThreadID *string - - // REQUIRED; The type of the message - Type *string - - // REQUIRED; The version of the message - Version *int64 + // The chat message id + MessageID *string // The display name of the sender SenderDisplayName *string + // The chat thread id + ThreadID *string + // The transaction id will be used as co-relation vector TransactionID *string + + // The type of the message + Type *string + + // The version of the message + Version *int64 } // ACSChatMessageEditedEventData - Schema of the Data property of an EventGridEvent for a Microsoft.Communication.ChatMessageEdited @@ -350,11 +101,8 @@ type ACSChatMessageEditedEventData struct { // REQUIRED; The time at which the message was edited EditTime *time.Time - // REQUIRED; The body of the chat message - MessageBody *string - - // REQUIRED; The chat message id - MessageID *string + // REQUIRED; The chat message metadata + Metadata map[string]*string // REQUIRED; The communication identifier of the target user RecipientCommunicationIdentifier *CommunicationIdentifierModel @@ -362,23 +110,26 @@ type ACSChatMessageEditedEventData struct { // REQUIRED; The communication identifier of the sender SenderCommunicationIdentifier *CommunicationIdentifierModel - // REQUIRED; The chat thread id - ThreadID *string - - // REQUIRED; The type of the message - Type *string - - // REQUIRED; The version of the message - Version *int64 + // The body of the chat message + MessageBody *string - // The chat message metadata - Metadata map[string]*string + // The chat message id + MessageID *string // The display name of the sender SenderDisplayName *string + // The chat thread id + ThreadID *string + // The transaction id will be used as co-relation vector TransactionID *string + + // The type of the message + Type *string + + // The version of the message + Version *int64 } // ACSChatMessageEditedInThreadEventData - Schema of the Data property of an EventGridEvent for a Microsoft.Communication.ChatMessageEditedInThread @@ -390,32 +141,89 @@ type ACSChatMessageEditedInThreadEventData struct { // REQUIRED; The time at which the message was edited EditTime *time.Time - // REQUIRED; The body of the chat message + // REQUIRED; The chat message metadata + Metadata map[string]*string + + // REQUIRED; The communication identifier of the sender + SenderCommunicationIdentifier *CommunicationIdentifierModel + + // The body of the chat message MessageBody *string - // REQUIRED; The chat message id + // The chat message id MessageID *string + // The display name of the sender + SenderDisplayName *string + + // The chat thread id + ThreadID *string + + // The transaction id will be used as co-relation vector + TransactionID *string + + // The type of the message + Type *string + + // The version of the message + Version *int64 +} + +// ACSChatMessageEventBaseProperties - Schema of common properties of all chat message events +type ACSChatMessageEventBaseProperties struct { + // REQUIRED; The original compose time of the message + ComposeTime *time.Time + + // REQUIRED; The communication identifier of the target user + RecipientCommunicationIdentifier *CommunicationIdentifierModel + // REQUIRED; The communication identifier of the sender SenderCommunicationIdentifier *CommunicationIdentifierModel - // REQUIRED; The chat thread id + // The chat message id + MessageID *string + + // The display name of the sender + SenderDisplayName *string + + // The chat thread id ThreadID *string - // REQUIRED; The type of the message + // The transaction id will be used as co-relation vector + TransactionID *string + + // The type of the message Type *string - // REQUIRED; The version of the message + // The version of the message Version *int64 +} - // The chat message metadata - Metadata map[string]*string +// ACSChatMessageEventInThreadBaseProperties - Schema of common properties of all thread-level chat message events +type ACSChatMessageEventInThreadBaseProperties struct { + // REQUIRED; The original compose time of the message + ComposeTime *time.Time + + // REQUIRED; The communication identifier of the sender + SenderCommunicationIdentifier *CommunicationIdentifierModel + + // The chat message id + MessageID *string // The display name of the sender SenderDisplayName *string + // The chat thread id + ThreadID *string + // The transaction id will be used as co-relation vector TransactionID *string + + // The type of the message + Type *string + + // The version of the message + Version *int64 } // ACSChatMessageReceivedEventData - Schema of the Data property of an EventGridEvent for a Microsoft.Communication.ChatMessageReceived @@ -424,11 +232,8 @@ type ACSChatMessageReceivedEventData struct { // REQUIRED; The original compose time of the message ComposeTime *time.Time - // REQUIRED; The body of the chat message - MessageBody *string - - // REQUIRED; The chat message id - MessageID *string + // REQUIRED; The chat message metadata + Metadata map[string]*string // REQUIRED; The communication identifier of the target user RecipientCommunicationIdentifier *CommunicationIdentifierModel @@ -436,23 +241,26 @@ type ACSChatMessageReceivedEventData struct { // REQUIRED; The communication identifier of the sender SenderCommunicationIdentifier *CommunicationIdentifierModel - // REQUIRED; The chat thread id - ThreadID *string - - // REQUIRED; The type of the message - Type *string - - // REQUIRED; The version of the message - Version *int64 + // The body of the chat message + MessageBody *string - // The chat message metadata - Metadata map[string]*string + // The chat message id + MessageID *string // The display name of the sender SenderDisplayName *string + // The chat thread id + ThreadID *string + // The transaction id will be used as co-relation vector TransactionID *string + + // The type of the message + Type *string + + // The version of the message + Version *int64 } // ACSChatMessageReceivedInThreadEventData - Schema of the Data property of an EventGridEvent for a Microsoft.Communication.ChatMessageReceivedInThread @@ -461,32 +269,32 @@ type ACSChatMessageReceivedInThreadEventData struct { // REQUIRED; The original compose time of the message ComposeTime *time.Time - // REQUIRED; The body of the chat message - MessageBody *string - - // REQUIRED; The chat message id - MessageID *string + // REQUIRED; The chat message metadata + Metadata map[string]*string // REQUIRED; The communication identifier of the sender SenderCommunicationIdentifier *CommunicationIdentifierModel - // REQUIRED; The chat thread id - ThreadID *string - - // REQUIRED; The type of the message - Type *string - - // REQUIRED; The version of the message - Version *int64 + // The body of the chat message + MessageBody *string - // The chat message metadata - Metadata map[string]*string + // The chat message id + MessageID *string // The display name of the sender SenderDisplayName *string + // The chat thread id + ThreadID *string + // The transaction id will be used as co-relation vector TransactionID *string + + // The type of the message + Type *string + + // The version of the message + Version *int64 } // ACSChatParticipantAddedToThreadEventData - Schema of the Data property of an EventGridEvent for a Microsoft.Communication.ChatThreadParticipantAdded @@ -498,12 +306,12 @@ type ACSChatParticipantAddedToThreadEventData struct { // REQUIRED; The details of the user who was added ParticipantAdded *ACSChatThreadParticipantProperties - // REQUIRED; The chat thread id - ThreadID *string - // REQUIRED; The time at which the user was added to the thread Time *time.Time + // The chat thread id + ThreadID *string + // The transaction id will be used as co-relation vector TransactionID *string @@ -526,12 +334,12 @@ type ACSChatParticipantAddedToThreadWithUserEventData struct { // REQUIRED; The communication identifier of the target user RecipientCommunicationIdentifier *CommunicationIdentifierModel - // REQUIRED; The chat thread id - ThreadID *string - // REQUIRED; The time at which the user was added to the thread Time *time.Time + // The chat thread id + ThreadID *string + // The transaction id will be used as co-relation vector TransactionID *string @@ -548,12 +356,12 @@ type ACSChatParticipantRemovedFromThreadEventData struct { // REQUIRED; The communication identifier of the user who removed the user RemovedByCommunicationIdentifier *CommunicationIdentifierModel - // REQUIRED; The chat thread id - ThreadID *string - // REQUIRED; The time at which the user was removed to the thread Time *time.Time + // The chat thread id + ThreadID *string + // The transaction id will be used as co-relation vector TransactionID *string @@ -576,12 +384,12 @@ type ACSChatParticipantRemovedFromThreadWithUserEventData struct { // REQUIRED; The communication identifier of the user who removed the user RemovedByCommunicationIdentifier *CommunicationIdentifierModel - // REQUIRED; The chat thread id - ThreadID *string - // REQUIRED; The time at which the user was removed to the thread Time *time.Time + // The chat thread id + ThreadID *string + // The transaction id will be used as co-relation vector TransactionID *string @@ -598,23 +406,23 @@ type ACSChatThreadCreatedEventData struct { // REQUIRED; The communication identifier of the user who created the thread CreatedByCommunicationIdentifier *CommunicationIdentifierModel - // REQUIRED; The list of properties of participants who are part of the thread - Participants []ACSChatThreadParticipantProperties + // REQUIRED; The thread metadata + Metadata map[string]*string // REQUIRED; The thread properties Properties map[string]any - // REQUIRED; The chat thread id + // The chat thread id ThreadID *string - // The thread metadata - Metadata map[string]*string - // The transaction id will be used as co-relation vector TransactionID *string // The version of the thread Version *int64 + + // READ-ONLY; The list of properties of participants who are part of the thread + Participants []ACSChatThreadParticipantProperties } // ACSChatThreadCreatedWithUserEventData - Schema of the Data property of an EventGridEvent for a Microsoft.Communication.ChatThreadCreatedWithUser @@ -626,21 +434,61 @@ type ACSChatThreadCreatedWithUserEventData struct { // REQUIRED; The communication identifier of the user who created the thread CreatedByCommunicationIdentifier *CommunicationIdentifierModel - // REQUIRED; The list of properties of participants who are part of the thread + // REQUIRED; The thread metadata + Metadata map[string]*string + + // REQUIRED; The thread properties + Properties map[string]any + + // REQUIRED; The communication identifier of the target user + RecipientCommunicationIdentifier *CommunicationIdentifierModel + + // The chat thread id + ThreadID *string + + // The transaction id will be used as co-relation vector + TransactionID *string + + // The version of the thread + Version *int64 + + // READ-ONLY; The list of properties of participants who are part of the thread Participants []ACSChatThreadParticipantProperties +} + +// ACSChatThreadDeletedEventData - Schema of the Data property of an EventGridEvent for a Microsoft.Communication.ChatThreadDeleted +// event. +type ACSChatThreadDeletedEventData struct { + // REQUIRED; The original creation time of the thread + CreateTime *time.Time + + // REQUIRED; The deletion time of the thread + DeleteTime *time.Time + + // REQUIRED; The communication identifier of the user who deleted the thread + DeletedByCommunicationIdentifier *CommunicationIdentifierModel + + // The chat thread id + ThreadID *string + + // The transaction id will be used as co-relation vector + TransactionID *string + + // The version of the thread + Version *int64 +} - // REQUIRED; The thread properties - Properties map[string]any +// ACSChatThreadEventBaseProperties - Schema of common properties of all chat thread events +type ACSChatThreadEventBaseProperties struct { + // REQUIRED; The original creation time of the thread + CreateTime *time.Time // REQUIRED; The communication identifier of the target user RecipientCommunicationIdentifier *CommunicationIdentifierModel - // REQUIRED; The chat thread id + // The chat thread id ThreadID *string - // The thread metadata - Metadata map[string]*string - // The transaction id will be used as co-relation vector TransactionID *string @@ -648,19 +496,12 @@ type ACSChatThreadCreatedWithUserEventData struct { Version *int64 } -// ACSChatThreadDeletedEventData - Schema of the Data property of an EventGridEvent for a Microsoft.Communication.ChatThreadDeleted -// event. -type ACSChatThreadDeletedEventData struct { +// ACSChatThreadEventInThreadBaseProperties - Schema of common properties of all chat thread events +type ACSChatThreadEventInThreadBaseProperties struct { // REQUIRED; The original creation time of the thread CreateTime *time.Time - // REQUIRED; The deletion time of the thread - DeleteTime *time.Time - - // REQUIRED; The communication identifier of the user who deleted the thread - DeletedByCommunicationIdentifier *CommunicationIdentifierModel - - // REQUIRED; The chat thread id + // The chat thread id ThreadID *string // The transaction id will be used as co-relation vector @@ -672,14 +513,14 @@ type ACSChatThreadDeletedEventData struct { // ACSChatThreadParticipantProperties - Schema of the chat thread participant type ACSChatThreadParticipantProperties struct { + // REQUIRED; The metadata of the user + Metadata map[string]*string + // REQUIRED; The communication identifier of the user ParticipantCommunicationIdentifier *CommunicationIdentifierModel // The name of the user DisplayName *string - - // The metadata of the user - Metadata map[string]*string } // ACSChatThreadPropertiesUpdatedEventData - Schema of the Data property of an EventGridEvent for a Microsoft.Communication.ChatThreadPropertiesUpdated @@ -700,7 +541,7 @@ type ACSChatThreadPropertiesUpdatedEventData struct { // REQUIRED; The updated thread properties Properties map[string]any - // REQUIRED; The chat thread id + // The chat thread id ThreadID *string // The transaction id will be used as co-relation vector @@ -722,18 +563,18 @@ type ACSChatThreadPropertiesUpdatedPerUserEventData struct { // REQUIRED; The communication identifier of the user who updated the thread properties EditedByCommunicationIdentifier *CommunicationIdentifierModel + // REQUIRED; The thread metadata + Metadata map[string]*string + // REQUIRED; The updated thread properties Properties map[string]any // REQUIRED; The communication identifier of the target user RecipientCommunicationIdentifier *CommunicationIdentifierModel - // REQUIRED; The chat thread id + // The chat thread id ThreadID *string - // The thread metadata - Metadata map[string]*string - // The transaction id will be used as co-relation vector TransactionID *string @@ -756,7 +597,7 @@ type ACSChatThreadWithUserDeletedEventData struct { // REQUIRED; The communication identifier of the target user RecipientCommunicationIdentifier *CommunicationIdentifierModel - // REQUIRED; The chat thread id + // The chat thread id ThreadID *string // The transaction id will be used as co-relation vector @@ -766,40 +607,6 @@ type ACSChatThreadWithUserDeletedEventData struct { Version *int64 } -// ACSChatTypingIndicatorReceivedInThreadEventData - Schema of the Data property of an EventGridEvent for a Microsoft.Communication.ChatTypingIndicatorReceivedInThread -// event. -type ACSChatTypingIndicatorReceivedInThreadEventData struct { - // REQUIRED; The original compose time of the message - ComposeTime *time.Time - - // REQUIRED; The body of the chat message - MessageBody *string - - // REQUIRED; The chat message id - MessageID *string - - // REQUIRED; The communication identifier of the sender - SenderCommunicationIdentifier *CommunicationIdentifierModel - - // REQUIRED; The chat thread id - ThreadID *string - - // REQUIRED; The type of the message - Type *string - - // REQUIRED; The version of the message - Version *int64 - - // The chat message metadata - Metadata map[string]*string - - // The display name of the sender - SenderDisplayName *string - - // The transaction id will be used as co-relation vector - TransactionID *string -} - // ACSEmailDeliveryReportReceivedEventData - Schema of the Data property of an EventGridEvent for a Microsoft.Communication.EmailDeliveryReportReceived // event. type ACSEmailDeliveryReportReceivedEventData struct { @@ -933,12 +740,27 @@ type ACSMessageDeliveryStatusUpdatedEventData struct { To *string // The channel event error - Error *Error + Error *InternalACSMessageChannelEventError // The message id MessageID *string } +// ACSMessageEventData - Schema of common properties of all chat thread events +type ACSMessageEventData struct { + // REQUIRED; The message sender + From *string + + // REQUIRED; The time message was received + ReceivedTimestamp *time.Time + + // REQUIRED; The message recipient + To *string + + // The channel event error + Error *InternalACSMessageChannelEventError +} + // ACSMessageInteractiveButtonReplyContent - Message Interactive button reply content for a user to business message type ACSMessageInteractiveButtonReplyContent struct { // The ID of the button @@ -1027,7 +849,7 @@ type ACSMessageReceivedEventData struct { Context *ACSMessageContext // The channel event error - Error *Error + Error *InternalACSMessageChannelEventError // Optional. The received message interactive content InteractiveContent *ACSMessageInteractiveContent @@ -1090,7 +912,7 @@ type ACSRecordingFileStatusUpdatedEventData struct { // ACSRecordingStorageInfoProperties - Schema for all properties of Recording Storage Information. type ACSRecordingStorageInfoProperties struct { - // REQUIRED; List of details of recording chunks information + // READ-ONLY; List of details of recording chunks information RecordingChunks []ACSRecordingChunkInfoProperties } @@ -1106,12 +928,21 @@ type ACSRouterChannelConfiguration struct { MaxNumberOfJobs *int32 } +// ACSRouterEventData - Schema of common properties of all Router events +type ACSRouterEventData struct { + // Router Event Channel ID + ChannelID *string + + // Router Event Channel Reference + ChannelReference *string + + // Router Event Job ID + JobID *string +} + // ACSRouterJobCancelledEventData - Schema of the Data property of an EventGridEvent for a Microsoft.Communication.RouterJobCancelled // event type ACSRouterJobCancelledEventData struct { - // REQUIRED; Router Event Job ID - JobID *string - // REQUIRED; Router Job events Labels Labels map[string]*string @@ -1127,6 +958,9 @@ type ACSRouterJobCancelledEventData struct { // Router Job Disposition Code DispositionCode *string + // Router Event Job ID + JobID *string + // Router Job Note Note *string @@ -1137,18 +971,15 @@ type ACSRouterJobCancelledEventData struct { // ACSRouterJobClassificationFailedEventData - Schema of the Data property of an EventGridEvent for a Microsoft.Communication.RouterJobClassificationFailed // event type ACSRouterJobClassificationFailedEventData struct { - // REQUIRED; Router Job Classification Failed Errors - Errors []*Error - - // REQUIRED; Router Event Job ID - JobID *string - // REQUIRED; Router Job events Labels Labels map[string]*string // REQUIRED; Router Jobs events Tags Tags map[string]*string + // READ-ONLY; Router Job Classification Failed Errors + Errors []InternalACSRouterCommunicationError + // Router Event Channel ID ChannelID *string @@ -1158,6 +989,9 @@ type ACSRouterJobClassificationFailedEventData struct { // Router Job Classification Policy Id ClassificationPolicyID *string + // Router Event Job ID + JobID *string + // Router Job events Queue Id QueueID *string } @@ -1165,12 +999,6 @@ type ACSRouterJobClassificationFailedEventData struct { // ACSRouterJobClassifiedEventData - Schema of the Data property of an EventGridEvent for a Microsoft.Communication.RouterJobClassified // event type ACSRouterJobClassifiedEventData struct { - // REQUIRED; Router Job Attached Worker Selector - AttachedWorkerSelectors []ACSRouterWorkerSelector - - // REQUIRED; Router Event Job ID - JobID *string - // REQUIRED; Router Job events Labels Labels map[string]*string @@ -1189,19 +1017,22 @@ type ACSRouterJobClassifiedEventData struct { // Router Job Classification Policy Id ClassificationPolicyID *string + // Router Event Job ID + JobID *string + // Router Job Priority Priority *int32 // Router Job events Queue Id QueueID *string + + // READ-ONLY; Router Job Attached Worker Selector + AttachedWorkerSelectors []ACSRouterWorkerSelector } // ACSRouterJobClosedEventData - Schema of the Data property of an EventGridEvent for a Microsoft.Communication.RouterJobClosed // event type ACSRouterJobClosedEventData struct { - // REQUIRED; Router Event Job ID - JobID *string - // REQUIRED; Router Job events Labels Labels map[string]*string @@ -1220,6 +1051,9 @@ type ACSRouterJobClosedEventData struct { // Router Job Closed Disposition Code DispositionCode *string + // Router Event Job ID + JobID *string + // Router Job events Queue Id QueueID *string @@ -1230,9 +1064,6 @@ type ACSRouterJobClosedEventData struct { // ACSRouterJobCompletedEventData - Schema of the Data property of an EventGridEvent for a Microsoft.Communication.RouterJobCompleted // event type ACSRouterJobCompletedEventData struct { - // REQUIRED; Router Event Job ID - JobID *string - // REQUIRED; Router Job events Labels Labels map[string]*string @@ -1248,6 +1079,9 @@ type ACSRouterJobCompletedEventData struct { // Router Event Channel Reference ChannelReference *string + // Router Event Job ID + JobID *string + // Router Job events Queue Id QueueID *string @@ -1258,9 +1092,27 @@ type ACSRouterJobCompletedEventData struct { // ACSRouterJobDeletedEventData - Schema of the Data property of an EventGridEvent for a Microsoft.Communication.RouterJobDeleted // event type ACSRouterJobDeletedEventData struct { - // REQUIRED; Router Event Job ID + // REQUIRED; Router Job events Labels + Labels map[string]*string + + // REQUIRED; Router Jobs events Tags + Tags map[string]*string + + // Router Event Channel ID + ChannelID *string + + // Router Event Channel Reference + ChannelReference *string + + // Router Event Job ID JobID *string + // Router Job events Queue Id + QueueID *string +} + +// ACSRouterJobEventData - Schema of common properties of all Router Job events +type ACSRouterJobEventData struct { // REQUIRED; Router Job events Labels Labels map[string]*string @@ -1273,6 +1125,9 @@ type ACSRouterJobDeletedEventData struct { // Router Event Channel Reference ChannelReference *string + // Router Event Job ID + JobID *string + // Router Job events Queue Id QueueID *string } @@ -1280,9 +1135,6 @@ type ACSRouterJobDeletedEventData struct { // ACSRouterJobExceptionTriggeredEventData - Schema of the Data property of an EventGridEvent for a Microsoft.Communication.RouterJobExceptionTriggered // event type ACSRouterJobExceptionTriggeredEventData struct { - // REQUIRED; Router Event Job ID - JobID *string - // REQUIRED; Router Job events Labels Labels map[string]*string @@ -1298,6 +1150,9 @@ type ACSRouterJobExceptionTriggeredEventData struct { // Router Job Exception Triggered Rule Id ExceptionRuleID *string + // Router Event Job ID + JobID *string + // Router Job events Queue Id QueueID *string @@ -1308,49 +1163,43 @@ type ACSRouterJobExceptionTriggeredEventData struct { // ACSRouterJobQueuedEventData - Schema of the Data property of an EventGridEvent for a Microsoft.Communication.RouterJobQueued // event type ACSRouterJobQueuedEventData struct { - // REQUIRED; Router Job Queued Attached Worker Selector - AttachedWorkerSelectors []ACSRouterWorkerSelector - - // REQUIRED; Router Event Job ID - JobID *string - // REQUIRED; Router Job events Labels Labels map[string]*string - // REQUIRED; Router Job Priority - Priority *int32 - - // REQUIRED; Router Job Queued Requested Worker Selector - RequestedWorkerSelectors []ACSRouterWorkerSelector - // REQUIRED; Router Jobs events Tags Tags map[string]*string + // READ-ONLY; Router Job Queued Requested Worker Selector + RequestedWorkerSelectors []ACSRouterWorkerSelector + // Router Event Channel ID ChannelID *string // Router Event Channel Reference ChannelReference *string + // Router Event Job ID + JobID *string + + // Router Job Priority + Priority *int32 + // Router Job events Queue Id QueueID *string + + // READ-ONLY; Router Job Queued Attached Worker Selector + AttachedWorkerSelectors []ACSRouterWorkerSelector } // ACSRouterJobReceivedEventData - Schema of the Data property of an EventGridEvent for a Microsoft.Communication.RouterJobReceived // event type ACSRouterJobReceivedEventData struct { - // REQUIRED; Router Event Job ID - JobID *string - // REQUIRED; Router Job Received Job Status JobStatus *ACSRouterJobStatus // REQUIRED; Router Job events Labels Labels map[string]*string - // REQUIRED; Router Job Received Requested Worker Selectors - RequestedWorkerSelectors []ACSRouterWorkerSelector - // REQUIRED; Router Job Received Scheduled Time in UTC ScheduledOn *time.Time @@ -1360,6 +1209,9 @@ type ACSRouterJobReceivedEventData struct { // REQUIRED; Unavailable For Matching for Router Job Received UnavailableForMatching *bool + // READ-ONLY; Router Job Received Requested Worker Selectors + RequestedWorkerSelectors []ACSRouterWorkerSelector + // Router Event Channel ID ChannelID *string @@ -1369,6 +1221,9 @@ type ACSRouterJobReceivedEventData struct { // Router Job Classification Policy Id ClassificationPolicyID *string + // Router Event Job ID + JobID *string + // Router Job Priority Priority *int32 @@ -1379,27 +1234,21 @@ type ACSRouterJobReceivedEventData struct { // ACSRouterJobSchedulingFailedEventData - Schema of the Data property of an EventGridEvent for a Microsoft.Communication.RouterJobSchedulingFailed // event type ACSRouterJobSchedulingFailedEventData struct { - // REQUIRED; Router Job Scheduling Failed Attached Worker Selector Expired - ExpiredAttachedWorkerSelectors []ACSRouterWorkerSelector - - // REQUIRED; Router Job Scheduling Failed Requested Worker Selector Expired - ExpiredRequestedWorkerSelectors []ACSRouterWorkerSelector - - // REQUIRED; Router Event Job ID - JobID *string - // REQUIRED; Router Job events Labels Labels map[string]*string - // REQUIRED; Router Job Priority - Priority *int32 - // REQUIRED; Router Job Scheduling Failed Scheduled Time in UTC ScheduledOn *time.Time // REQUIRED; Router Jobs events Tags Tags map[string]*string + // READ-ONLY; Router Job Scheduling Failed Attached Worker Selector Expired + ExpiredAttachedWorkerSelectors []ACSRouterWorkerSelector + + // READ-ONLY; Router Job Scheduling Failed Requested Worker Selector Expired + ExpiredRequestedWorkerSelectors []ACSRouterWorkerSelector + // Router Event Channel ID ChannelID *string @@ -1409,6 +1258,12 @@ type ACSRouterJobSchedulingFailedEventData struct { // Router Job Scheduling Failed Reason FailureReason *string + // Router Event Job ID + JobID *string + + // Router Job Priority + Priority *int32 + // Router Job events Queue Id QueueID *string } @@ -1416,9 +1271,6 @@ type ACSRouterJobSchedulingFailedEventData struct { // ACSRouterJobUnassignedEventData - Schema of the Data property of an EventGridEvent for a Microsoft.Communication.RouterJobUnassigned // event type ACSRouterJobUnassignedEventData struct { - // REQUIRED; Router Event Job ID - JobID *string - // REQUIRED; Router Job events Labels Labels map[string]*string @@ -1434,6 +1286,9 @@ type ACSRouterJobUnassignedEventData struct { // Router Event Channel Reference ChannelReference *string + // Router Event Job ID + JobID *string + // Router Job events Queue Id QueueID *string @@ -1444,21 +1299,9 @@ type ACSRouterJobUnassignedEventData struct { // ACSRouterJobWaitingForActivationEventData - Schema of the Data property of an EventGridEvent for a Microsoft.Communication.RouterJobWaitingForActivation // event type ACSRouterJobWaitingForActivationEventData struct { - // REQUIRED; Router Job Waiting For Activation Worker Selector Expired - ExpiredAttachedWorkerSelectors []ACSRouterWorkerSelector - - // REQUIRED; Router Job Waiting For Activation Requested Worker Selector Expired - ExpiredRequestedWorkerSelectors []ACSRouterWorkerSelector - - // REQUIRED; Router Event Job ID - JobID *string - // REQUIRED; Router Job events Labels Labels map[string]*string - // REQUIRED; Router Job Waiting For Activation Priority - Priority *int32 - // REQUIRED; Router Job Waiting For Activation Scheduled Time in UTC ScheduledOn *time.Time @@ -1468,12 +1311,24 @@ type ACSRouterJobWaitingForActivationEventData struct { // REQUIRED; Router Job Waiting For Activation Unavailable For Matching UnavailableForMatching *bool + // READ-ONLY; Router Job Waiting For Activation Worker Selector Expired + ExpiredAttachedWorkerSelectors []ACSRouterWorkerSelector + + // READ-ONLY; Router Job Waiting For Activation Requested Worker Selector Expired + ExpiredRequestedWorkerSelectors []ACSRouterWorkerSelector + // Router Event Channel ID ChannelID *string // Router Event Channel Reference ChannelReference *string + // Router Event Job ID + JobID *string + + // Router Job Waiting For Activation Priority + Priority *int32 + // Router Job events Queue Id QueueID *string } @@ -1481,27 +1336,27 @@ type ACSRouterJobWaitingForActivationEventData struct { // ACSRouterJobWorkerSelectorsExpiredEventData - Schema of the Data property of an EventGridEvent for a Microsoft.Communication.RouterJobWorkerSelectorsExpired // event type ACSRouterJobWorkerSelectorsExpiredEventData struct { - // REQUIRED; Router Job Worker Selectors Expired Attached Worker Selectors - ExpiredAttachedWorkerSelectors []ACSRouterWorkerSelector - - // REQUIRED; Router Job Worker Selectors Expired Requested Worker Selectors - ExpiredRequestedWorkerSelectors []ACSRouterWorkerSelector - - // REQUIRED; Router Event Job ID - JobID *string - // REQUIRED; Router Job events Labels Labels map[string]*string // REQUIRED; Router Jobs events Tags Tags map[string]*string + // READ-ONLY; Router Job Worker Selectors Expired Attached Worker Selectors + ExpiredAttachedWorkerSelectors []ACSRouterWorkerSelector + + // READ-ONLY; Router Job Worker Selectors Expired Requested Worker Selectors + ExpiredRequestedWorkerSelectors []ACSRouterWorkerSelector + // Router Event Channel ID ChannelID *string // Router Event Channel Reference ChannelReference *string + // Router Event Job ID + JobID *string + // Router Job events Queue Id QueueID *string } @@ -1521,15 +1376,15 @@ type ACSRouterQueueDetails struct { // ACSRouterWorkerDeletedEventData - Schema of the Data property of an EventGridEvent for a Microsoft.Communication.RouterWorkerDeleted // event type ACSRouterWorkerDeletedEventData struct { - // REQUIRED; Router Event Job ID - JobID *string - // Router Event Channel ID ChannelID *string // Router Event Channel Reference ChannelReference *string + // Router Event Job ID + JobID *string + // Router Worker events Worker Id WorkerID *string } @@ -1541,12 +1396,24 @@ type ACSRouterWorkerDeregisteredEventData struct { WorkerID *string } +// ACSRouterWorkerEventData - Schema of common properties of all Router Worker events +type ACSRouterWorkerEventData struct { + // Router Event Channel ID + ChannelID *string + + // Router Event Channel Reference + ChannelReference *string + + // Router Event Job ID + JobID *string + + // Router Worker events Worker Id + WorkerID *string +} + // ACSRouterWorkerOfferAcceptedEventData - Schema of the Data property of an EventGridEvent for a Microsoft.Communication.RouterWorkerOfferAccepted // event type ACSRouterWorkerOfferAcceptedEventData struct { - // REQUIRED; Router Event Job ID - JobID *string - // REQUIRED; Router Worker Offer Accepted Job Labels JobLabels map[string]*string @@ -1568,6 +1435,9 @@ type ACSRouterWorkerOfferAcceptedEventData struct { // Router Event Channel Reference ChannelReference *string + // Router Event Job ID + JobID *string + // Router Worker Offer Accepted Job Priority JobPriority *int32 @@ -1584,15 +1454,15 @@ type ACSRouterWorkerOfferAcceptedEventData struct { // ACSRouterWorkerOfferDeclinedEventData - Schema of the Data property of an EventGridEvent for a Microsoft.Communication.RouterWorkerOfferDeclined // event type ACSRouterWorkerOfferDeclinedEventData struct { - // REQUIRED; Router Event Job ID - JobID *string - // Router Event Channel ID ChannelID *string // Router Event Channel Reference ChannelReference *string + // Router Event Job ID + JobID *string + // Router Worker Offer Declined Offer Id OfferID *string @@ -1606,15 +1476,15 @@ type ACSRouterWorkerOfferDeclinedEventData struct { // ACSRouterWorkerOfferExpiredEventData - Schema of the Data property of an EventGridEvent for a Microsoft.Communication.RouterWorkerOfferExpired // event type ACSRouterWorkerOfferExpiredEventData struct { - // REQUIRED; Router Event Job ID - JobID *string - // Router Event Channel ID ChannelID *string // Router Event Channel Reference ChannelReference *string + // Router Event Job ID + JobID *string + // Router Worker Offer Expired Offer Id OfferID *string @@ -1631,9 +1501,6 @@ type ACSRouterWorkerOfferIssuedEventData struct { // REQUIRED; Router Worker Offer Issued Expiration Time in UTC ExpiresOn *time.Time - // REQUIRED; Router Event Job ID - JobID *string - // REQUIRED; Router Worker Offer Issued Job Labels JobLabels map[string]*string @@ -1655,6 +1522,9 @@ type ACSRouterWorkerOfferIssuedEventData struct { // Router Event Channel Reference ChannelReference *string + // Router Event Job ID + JobID *string + // Router Worker Offer Issued Job Priority JobPriority *int32 @@ -1671,15 +1541,15 @@ type ACSRouterWorkerOfferIssuedEventData struct { // ACSRouterWorkerOfferRevokedEventData - Schema of the Data property of an EventGridEvent for a Microsoft.Communication.RouterWorkerOfferRevoked // event type ACSRouterWorkerOfferRevokedEventData struct { - // REQUIRED; Router Event Job ID - JobID *string - // Router Event Channel ID ChannelID *string // Router Event Channel Reference ChannelReference *string + // Router Event Job ID + JobID *string + // Router Worker Offer Revoked Offer Id OfferID *string @@ -1693,15 +1563,9 @@ type ACSRouterWorkerOfferRevokedEventData struct { // ACSRouterWorkerRegisteredEventData - Schema of the Data property of an EventGridEvent for a Microsoft.Communication.RouterWorkerRegistered // event type ACSRouterWorkerRegisteredEventData struct { - // REQUIRED; Router Worker Registered Channel Configuration - ChannelConfigurations []ACSRouterChannelConfiguration - // REQUIRED; Router Worker Registered Labels Labels map[string]*string - // REQUIRED; Router Worker Registered Queue Info - QueueAssignments []ACSRouterQueueDetails - // REQUIRED; Router Worker Registered Tags Tags map[string]*string @@ -1710,6 +1574,12 @@ type ACSRouterWorkerRegisteredEventData struct { // Router Worker Registered Worker Id WorkerID *string + + // READ-ONLY; Router Worker Registered Channel Configuration + ChannelConfigurations []ACSRouterChannelConfiguration + + // READ-ONLY; Router Worker Registered Queue Info + QueueAssignments []ACSRouterQueueDetails } // ACSRouterWorkerSelector - Router Job Worker Selector @@ -1736,19 +1606,13 @@ type ACSRouterWorkerSelector struct { // ACSRouterWorkerUpdatedEventData - Schema of the Data property of an EventGridEvent for a Microsoft.Communication.RouterWorkerUpdated // event. type ACSRouterWorkerUpdatedEventData struct { - // REQUIRED; Router Worker Updated Channel Configuration - ChannelConfigurations []ACSRouterChannelConfiguration - // REQUIRED; Router Worker Updated Labels Labels map[string]*string - // REQUIRED; Router Worker Updated Queue Info - QueueAssignments []ACSRouterQueueDetails - // REQUIRED; Router Worker Updated Tags Tags map[string]*string - // REQUIRED; Router Worker Properties Updated + // READ-ONLY; Router Worker Properties Updated UpdatedWorkerProperties []ACSRouterUpdatedWorkerProperty // Router Worker Updated Total Capacity @@ -1756,66 +1620,84 @@ type ACSRouterWorkerUpdatedEventData struct { // Router Worker Updated Worker Id WorkerID *string + + // READ-ONLY; Router Worker Updated Channel Configuration + ChannelConfigurations []ACSRouterChannelConfiguration + + // READ-ONLY; Router Worker Updated Queue Info + QueueAssignments []ACSRouterQueueDetails } // ACSSMSDeliveryAttemptProperties - Schema for details of a delivery attempt type ACSSMSDeliveryAttemptProperties struct { - // REQUIRED; Number of segments whose delivery failed + // REQUIRED; TimeStamp when delivery was attempted + Timestamp *time.Time + + // Number of segments whose delivery failed SegmentsFailed *int32 - // REQUIRED; Number of segments that were successfully delivered + // Number of segments that were successfully delivered SegmentsSucceeded *int32 - - // REQUIRED; TimeStamp when delivery was attempted - Timestamp *time.Time } // ACSSMSDeliveryReportReceivedEventData - Schema of the Data property of an EventGridEvent for a Microsoft.Communication.SMSDeliveryReportReceived // event. type ACSSMSDeliveryReportReceivedEventData struct { - // REQUIRED; List of details of delivery attempts made - DeliveryAttempts []ACSSMSDeliveryAttemptProperties + // REQUIRED; The time at which the SMS delivery report was received + ReceivedTimestamp *time.Time - // REQUIRED; Status of Delivery + // Status of Delivery DeliveryStatus *string - // REQUIRED; Details about Delivery Status + // Details about Delivery Status DeliveryStatusDetails *string - // REQUIRED; The identity of SMS message sender + // The identity of SMS message sender From *string - // REQUIRED; The identity of the SMS message + // The identity of the SMS message MessageID *string - // REQUIRED; The time at which the SMS delivery report was received - ReceivedTimestamp *time.Time + // Customer Content + Tag *string - // REQUIRED; The identity of SMS message receiver + // The identity of SMS message receiver To *string - // Customer Content - Tag *string + // READ-ONLY; List of details of delivery attempts made + DeliveryAttempts []ACSSMSDeliveryAttemptProperties } -// ACSSMSReceivedEventData - Schema of the Data property of an EventGridEvent for a Microsoft.Communication.SMSReceived event. -type ACSSMSReceivedEventData struct { - // REQUIRED; The identity of SMS message sender +// ACSSMSEventBaseProperties - Schema of common properties of all SMS events +type ACSSMSEventBaseProperties struct { + // The identity of SMS message sender From *string - // REQUIRED; The SMS content - Message *string - - // REQUIRED; The identity of the SMS message + // The identity of the SMS message MessageID *string + // The identity of SMS message receiver + To *string +} + +// ACSSMSReceivedEventData - Schema of the Data property of an EventGridEvent for a Microsoft.Communication.SMSReceived event. +type ACSSMSReceivedEventData struct { // REQUIRED; The time at which the SMS was received ReceivedTimestamp *time.Time // REQUIRED; Number of segments in the message SegmentCount *int32 - // REQUIRED; The identity of SMS message receiver + // The identity of SMS message sender + From *string + + // The SMS content + Message *string + + // The identity of the SMS message + MessageID *string + + // The identity of SMS message receiver To *string } @@ -1909,6 +1791,42 @@ type APIManagementAPIUpdatedEventData struct { ResourceURI *string } +// APIManagementCircuitBreakerClosedEventData - Schema of the Data property of an EventGridEvent for a Microsoft.ApiManagement.CircuitBreaker.Closed +// event. +type APIManagementCircuitBreakerClosedEventData struct { + // REQUIRED; Name of the backend for which the circuit has closed. + BackendName *string + + // REQUIRED; Information related to the circuit breaker configured on the backend. + CircuitBreaker *APIManagementCircuitBreakerProperties +} + +// APIManagementCircuitBreakerOpenedEventData - Schema of the Data property of an EventGridEvent for a Microsoft.ApiManagement.CircuitBreaker.Opened +// event. +type APIManagementCircuitBreakerOpenedEventData struct { + // REQUIRED; Name of the backend for which the circuit has opened. + BackendName *string + + // REQUIRED; Information related to the circuit breaker configured on the backend. + CircuitBreaker *APIManagementCircuitBreakerProperties +} + +// APIManagementCircuitBreakerProperties - Information related to the circuit breaker configured on the backend. +type APIManagementCircuitBreakerProperties struct { + // REQUIRED; Overview of all configured rules and respective details. + Rules map[string]*APIManagementCircuitBreakerPropertiesRule +} + +type APIManagementCircuitBreakerPropertiesRule struct { +} + +// APIManagementExpiredGatewayTokenProperties - Information related to a gateway token that has expired for a self-hosted +// gateway deployment. +type APIManagementExpiredGatewayTokenProperties struct { + // REQUIRED; Timestamp when the gateway token has expired. + ExpiredAtUTC *time.Time +} + // APIManagementGatewayAPIAddedEventData - Schema of the Data property of an EventGridEvent for a Microsoft.ApiManagement.GatewayAPIAdded // event. type APIManagementGatewayAPIAddedEventData struct { @@ -1989,6 +1907,36 @@ type APIManagementGatewayHostnameConfigurationUpdatedEventData struct { ResourceURI *string } +// APIManagementGatewayProperties - Information related to a given self-hosted gateway deployment. +type APIManagementGatewayProperties struct { + // REQUIRED; Id of Gateway that is used to deploy the gateway to get the configuration for. This is the ARM resource ID referenced + // in the Azure API Management instance. Uses the format, `/subscriptions//resourceGroups//Microsoft.ApiManagement/service//gateway/` + GatewayID *string + + // REQUIRED; Unique instance ID of the deployed gateway + InstanceID *string +} + +// APIManagementGatewayTokenExpiredEventData - Schema of the Data property of an EventGridEvent for a Microsoft.ApiManagement.GatewayTokenExpired +// event. +type APIManagementGatewayTokenExpiredEventData struct { + // REQUIRED; Information related to a given self-hosted gateway deployment. + GatewayInfo *APIManagementGatewayProperties + + // REQUIRED; Information related to a an expired gateway token for a self-hosted gateway deployment. + TokenInfo *APIManagementExpiredGatewayTokenProperties +} + +// APIManagementGatewayTokenNearExpiryEventData - Schema of the Data property of an EventGridEvent for a Microsoft.ApiManagement.GatewayTokenNearExpiry +// event. +type APIManagementGatewayTokenNearExpiryEventData struct { + // REQUIRED; Information related to a given self-hosted gateway deployment. + GatewayInfo *APIManagementGatewayProperties + + // REQUIRED; Information related to a an expired gateway token for a self-hosted gateway deployment. + TokenInfo *APIManagementNearExpiryGatewayTokenProperties +} + // APIManagementGatewayUpdatedEventData - Schema of the Data property of an EventGridEvent for a Microsoft.ApiManagement.GatewayUpdated // event. type APIManagementGatewayUpdatedEventData struct { @@ -1997,6 +1945,13 @@ type APIManagementGatewayUpdatedEventData struct { ResourceURI *string } +// APIManagementNearExpiryGatewayTokenProperties - Information related to a gateway token that is near expiry for a self-hosted +// gateway deployment. +type APIManagementNearExpiryGatewayTokenProperties struct { + // REQUIRED; Timestamp when the gateway token will expire. + ExpiredAtUTC *time.Time +} + // APIManagementProductCreatedEventData - Schema of the Data property of an EventGridEvent for a Microsoft.ApiManagement.ProductCreated // event. type APIManagementProductCreatedEventData struct { @@ -2074,13 +2029,13 @@ type AVSClusterCreatedEventData struct { // REQUIRED; Id of the operation that caused this event. OperationID *string - // Hosts added to the cluster in this event, if any. + // READ-ONLY; Hosts added to the cluster in this event, if any. AddedHostNames []string - // Hosts in Maintenance mode in the cluster, if any. + // READ-ONLY; Hosts in Maintenance mode in the cluster, if any. InMaintenanceHostNames []string - // Hosts removed from the cluster in this event, if any. + // READ-ONLY; Hosts removed from the cluster in this event, if any. RemovedHostNames []string } @@ -2089,31 +2044,46 @@ type AVSClusterDeletedEventData struct { // REQUIRED; Id of the operation that caused this event. OperationID *string - // Hosts added to the cluster in this event, if any. + // READ-ONLY; Hosts added to the cluster in this event, if any. AddedHostNames []string - // Hosts in Maintenance mode in the cluster, if any. + // READ-ONLY; Hosts in Maintenance mode in the cluster, if any. InMaintenanceHostNames []string - // Hosts removed from the cluster in this event, if any. + // READ-ONLY; Hosts removed from the cluster in this event, if any. RemovedHostNames []string } -// AVSClusterFailedEventData - Schema of the Data property of an EventGridEvent for a Microsoft.AVS.ClusterFailed event. -type AVSClusterFailedEventData struct { +// AVSClusterEventData - Schema of the Data property of an EventGridEvent for Microsoft.AVS/clusters events. +type AVSClusterEventData struct { // REQUIRED; Id of the operation that caused this event. OperationID *string - // Hosts added to the cluster in this event, if any. + // READ-ONLY; Hosts added to the cluster in this event, if any. AddedHostNames []string + // READ-ONLY; Hosts in Maintenance mode in the cluster, if any. + InMaintenanceHostNames []string + + // READ-ONLY; Hosts removed from the cluster in this event, if any. + RemovedHostNames []string +} + +// AVSClusterFailedEventData - Schema of the Data property of an EventGridEvent for a Microsoft.AVS.ClusterFailed event. +type AVSClusterFailedEventData struct { + // REQUIRED; Id of the operation that caused this event. + OperationID *string + // Failure reason of an event. FailureMessage *string - // Hosts in Maintenance mode in the cluster, if any. + // READ-ONLY; Hosts added to the cluster in this event, if any. + AddedHostNames []string + + // READ-ONLY; Hosts in Maintenance mode in the cluster, if any. InMaintenanceHostNames []string - // Hosts removed from the cluster in this event, if any. + // READ-ONLY; Hosts removed from the cluster in this event, if any. RemovedHostNames []string } @@ -2122,13 +2092,13 @@ type AVSClusterUpdatedEventData struct { // REQUIRED; Id of the operation that caused this event. OperationID *string - // Hosts added to the cluster in this event, if any. + // READ-ONLY; Hosts added to the cluster in this event, if any. AddedHostNames []string - // Hosts in Maintenance mode in the cluster, if any. + // READ-ONLY; Hosts in Maintenance mode in the cluster, if any. InMaintenanceHostNames []string - // Hosts removed from the cluster in this event, if any. + // READ-ONLY; Hosts removed from the cluster in this event, if any. RemovedHostNames []string } @@ -2137,16 +2107,22 @@ type AVSClusterUpdatingEventData struct { // REQUIRED; Id of the operation that caused this event. OperationID *string - // Hosts added to the cluster in this event, if any. + // READ-ONLY; Hosts added to the cluster in this event, if any. AddedHostNames []string - // Hosts in Maintenance mode in the cluster, if any. + // READ-ONLY; Hosts in Maintenance mode in the cluster, if any. InMaintenanceHostNames []string - // Hosts removed from the cluster in this event, if any. + // READ-ONLY; Hosts removed from the cluster in this event, if any. RemovedHostNames []string } +// AVSPrivateCloudEventData - Schema of the Data property of an EventGridEvent for Microsoft.AVS/privateClouds events. +type AVSPrivateCloudEventData struct { + // REQUIRED; Id of the operation that caused this event. + OperationID *string +} + // AVSPrivateCloudFailedEventData - Schema of the Data property of an EventGridEvent for a Microsoft.AVS.PrivateCloudFailed // event. type AVSPrivateCloudFailedEventData struct { @@ -2180,7 +2156,19 @@ type AVSScriptExecutionCancelledEventData struct { // REQUIRED; Id of the operation that caused this event. OperationID *string - // Stdout outputs from the execution, if any. + // READ-ONLY; Stdout outputs from the execution, if any. + Output []string +} + +// AVSScriptExecutionEventData - Schema of the Data property of an EventGridEvent for Microsoft.AVS/scriptExecutions events. +type AVSScriptExecutionEventData struct { + // REQUIRED; Cmdlet referenced in the execution that caused this event. + CmdletID *string + + // REQUIRED; Id of the operation that caused this event. + OperationID *string + + // READ-ONLY; Stdout outputs from the execution, if any. Output []string } @@ -2196,7 +2184,7 @@ type AVSScriptExecutionFailedEventData struct { // Failure reason of an event. FailureMessage *string - // Stdout outputs from the execution, if any. + // READ-ONLY; Stdout outputs from the execution, if any. Output []string } @@ -2212,7 +2200,7 @@ type AVSScriptExecutionFinishedEventData struct { // REQUIRED; Id of the operation that caused this event. OperationID *string - // Stdout outputs from the execution, if any. + // READ-ONLY; Stdout outputs from the execution, if any. Output []string } @@ -2225,7 +2213,7 @@ type AVSScriptExecutionStartedEventData struct { // REQUIRED; Id of the operation that caused this event. OperationID *string - // Stdout outputs from the execution, if any. + // READ-ONLY; Stdout outputs from the execution, if any. Output []string } @@ -2274,6 +2262,18 @@ type AppConfigurationSnapshotCreatedEventData struct { SyncToken *string } +// AppConfigurationSnapshotEventData - Schema of common properties of snapshot events +type AppConfigurationSnapshotEventData struct { + // REQUIRED; The etag representing the new state of the snapshot. + Etag *string + + // REQUIRED; The name of the snapshot. + Name *string + + // REQUIRED; The sync token representing the server state after the event. + SyncToken *string +} + // AppConfigurationSnapshotModifiedEventData - Schema of the Data property of an EventGridEvent for a Microsoft.AppConfiguration.SnapshotModified // event. type AppConfigurationSnapshotModifiedEventData struct { @@ -2312,20 +2312,20 @@ type CommunicationIdentifierModel struct { // REQUIRED; The communication user. CommunicationUser *CommunicationUserIdentifierModel - // REQUIRED; Raw Id of the identifier. Optional in requests, required in responses. - RawID *string - - // The identifier kind. Only required in responses. + // REQUIRED; The identifier kind. Only required in responses. Kind *CommunicationIdentifierModelKind - // The Microsoft Teams application. + // REQUIRED; The Microsoft Teams application. MicrosoftTeamsApp *MicrosoftTeamsAppIdentifierModel - // The Microsoft Teams user. + // REQUIRED; The Microsoft Teams user. MicrosoftTeamsUser *MicrosoftTeamsUserIdentifierModel - // The phone number. + // REQUIRED; The phone number. PhoneNumber *PhoneNumberIdentifierModel + + // Raw Id of the identifier. Optional in requests, required in responses. + RawID *string } // CommunicationUserIdentifierModel - A user that got created with an Azure Communication Services resource. @@ -2334,6 +2334,27 @@ type CommunicationUserIdentifierModel struct { ID *string } +// ContainerRegistryArtifactEventData - The content of the event request message. +type ContainerRegistryArtifactEventData struct { + // REQUIRED; The action that encompasses the provided event. + Action *string + + // REQUIRED; The event ID. + ID *string + + // REQUIRED; The location of the event. + Location *string + + // REQUIRED; The target of the event. + Target *ContainerRegistryArtifactEventTarget + + // REQUIRED; The time at which the event occurred. + Timestamp *time.Time + + // The connected registry information if the event is generated by a connected registry. + ConnectedRegistry *ContainerRegistryEventConnectedRegistry +} + // ContainerRegistryArtifactEventTarget - The target of the event. type ContainerRegistryArtifactEventTarget struct { // REQUIRED; The MIME type of the artifact. @@ -2415,6 +2436,37 @@ type ContainerRegistryEventConnectedRegistry struct { Name *string } +// ContainerRegistryEventData - The content of the event request message. +type ContainerRegistryEventData struct { + // REQUIRED; The action that encompasses the provided event. + Action *string + + // REQUIRED; The event ID. + ID *string + + // REQUIRED; The location of the event. + Location *string + + // REQUIRED; The target of the event. + Target *ContainerRegistryEventTarget + + // REQUIRED; The time at which the event occurred. + Timestamp *time.Time + + // The agent that initiated the event. For most situations, this could be from the authorization context of the request. + Actor *ContainerRegistryEventActor + + // The connected registry information if the event is generated by a connected registry. + ConnectedRegistry *ContainerRegistryEventConnectedRegistry + + // The request that generated the event. + Request *ContainerRegistryEventRequest + + // The registry node that generated the event. Put differently, while the actor initiates the event, the source generates + // it. + Source *ContainerRegistryEventSource +} + // ContainerRegistryEventRequest - The request that generated the event. type ContainerRegistryEventRequest struct { // REQUIRED; The externally accessible hostname of the registry instance, as specified by the http host header on incoming @@ -2548,6 +2600,12 @@ type ContainerServiceClusterSupportEndingEventData struct { KubernetesVersion *string } +// ContainerServiceClusterSupportEventData - Schema of common properties of cluster support events +type ContainerServiceClusterSupportEventData struct { + // REQUIRED; The Kubernetes version of the ManagedCluster resource + KubernetesVersion *string +} + // ContainerServiceNewKubernetesVersionAvailableEventData - Schema of the Data property of an EventGridEvent for a Microsoft.ContainerService.NewKubernetesVersionAvailable // event type ContainerServiceNewKubernetesVersionAvailableEventData struct { @@ -2566,6 +2624,12 @@ type ContainerServiceNewKubernetesVersionAvailableEventData struct { LatestPreviewKubernetesVersion *string } +// ContainerServiceNodePoolRollingEventData - Schema of common properties of node pool rolling events +type ContainerServiceNodePoolRollingEventData struct { + // REQUIRED; The name of the node pool in the ManagedCluster resource + NodePoolName *string +} + // ContainerServiceNodePoolRollingFailedEventData - Schema of the Data property of an EventGridEvent for a Microsoft.ContainerService.NodePoolRollingFailed // event type ContainerServiceNodePoolRollingFailedEventData struct { @@ -2636,6 +2700,50 @@ type DeviceConnectionStateEventInfo struct { SequenceNumber *string } +// DeviceConnectionStateEventProperties - Schema of the Data property of an EventGridEvent for a device connection state event +// (DeviceConnected, DeviceDisconnected). +type DeviceConnectionStateEventProperties struct { + // REQUIRED; Information about the device connection state event. + DeviceConnectionStateEventInfo *DeviceConnectionStateEventInfo + + // REQUIRED; The unique identifier of the device. This case-sensitive string can be up to 128 characters long, and supports + // ASCII 7-bit alphanumeric characters plus the following special characters: - : . + % _ # * ? ! ( ) , = `@` ; $ '. + DeviceID *string + + // REQUIRED; Name of the IoT Hub where the device was created or deleted. + HubName *string + + // The unique identifier of the module. This case-sensitive string can be up to 128 characters long, and supports ASCII 7-bit + // alphanumeric characters plus the following special characters: - : . + % _ # * ? ! ( ) , = `@` ; $ '. + ModuleID *string +} + +// DeviceLifeCycleEventProperties - Schema of the Data property of an EventGridEvent for a device life cycle event (DeviceCreated, +// DeviceDeleted). +type DeviceLifeCycleEventProperties struct { + // REQUIRED; The unique identifier of the device. This case-sensitive string can be up to 128 characters long, and supports + // ASCII 7-bit alphanumeric characters plus the following special characters: - : . + % _ # * ? ! ( ) , = `@` ; $ '. + DeviceID *string + + // REQUIRED; Name of the IoT Hub where the device was created or deleted. + HubName *string + + // REQUIRED; Information about the device twin, which is the cloud representation of application device metadata. + Twin *DeviceTwinInfo +} + +// DeviceTelemetryEventProperties - Schema of the Data property of an EventGridEvent for a device telemetry event (DeviceTelemetry). +type DeviceTelemetryEventProperties struct { + // REQUIRED; The content of the message from the device. + Body map[string]any + + // REQUIRED; Application properties are user-defined strings that can be added to the message. These fields are optional. + Properties map[string]*string + + // REQUIRED; System properties help identify contents and source of the messages. + SystemProperties map[string]*string +} + // DeviceTwinInfo - Information about the device twin, which is the cloud representation of application device metadata. type DeviceTwinInfo struct { // REQUIRED; Authentication type used for this device: either SAS, SelfSigned, or CertificateAuthority. @@ -2711,6 +2819,31 @@ type DeviceTwinProperties struct { Version *float32 } +// EdgeSolutionVersionPublishedEventData - Schema of the Data property of an EventGridEvent for a Microsoft.Edge.SolutionVersionPublished +// event. +type EdgeSolutionVersionPublishedEventData struct { + // REQUIRED; API Version supported for the resources + APIVersion *string + + // REQUIRED; Direct URL to callback for updating validation status + CallbackURL *string + + // REQUIRED; A GUID to uniquely track External Solution Validation + ExternalValidationID *string + + // REQUIRED; ARM ID of the Solution Template resource + SolutionTemplateID *string + + // REQUIRED; ARM ID of the Solution Template Version resource + SolutionTemplateVersionID *string + + // REQUIRED; ARM ID of the Solution Version resource + SolutionVersionID *string + + // REQUIRED; ARM ID of the Target resource + TargetID *string +} + // EventGridMQTTClientCreatedOrUpdatedEventData - Event data for Microsoft.EventGrid.MQTTClientCreatedOrUpdated event. type EventGridMQTTClientCreatedOrUpdatedEventData struct { // REQUIRED; The key-value attributes that are assigned to the client resource. @@ -2753,6 +2886,20 @@ type EventGridMQTTClientDeletedEventData struct { NamespaceName *string } +// EventGridMQTTClientEventData - Schema of the Data property of an EventGridEvent for MQTT Client state changes. +type EventGridMQTTClientEventData struct { + // REQUIRED; Unique identifier for the MQTT client that the client presents to the service + // for authentication. This case-sensitive string can be up to 128 characters + // long, and supports UTF-8 characters. + ClientAuthenticationName *string + + // REQUIRED; Name of the client resource in the Event Grid namespace. + ClientName *string + + // REQUIRED; Name of the Event Grid namespace where the MQTT client was created or updated. + NamespaceName *string +} + // EventGridMQTTClientSessionConnectedEventData - Event data for Microsoft.EventGrid.MQTTClientSessionConnected event. type EventGridMQTTClientSessionConnectedEventData struct { // REQUIRED; Unique identifier for the MQTT client that the client presents to the service @@ -3023,8 +3170,8 @@ type IOTHubDeviceTelemetryEventData struct { SystemProperties map[string]*string } -// internalACSMessageChannelEventError - Message Channel Event Error -type internalACSMessageChannelEventError struct { +// InternalACSMessageChannelEventError - Message Channel Event Error +type InternalACSMessageChannelEventError struct { // The channel error code ChannelCode *string @@ -3032,22 +3179,22 @@ type internalACSMessageChannelEventError struct { ChannelMessage *string } -// internalACSRouterCommunicationError - Router Communication Error -type internalACSRouterCommunicationError struct { - // REQUIRED; List of Router Communication Errors - Details []internalACSRouterCommunicationError - +// InternalACSRouterCommunicationError - Router Communication Error +type InternalACSRouterCommunicationError struct { // REQUIRED; Router Communication Inner Error - Innererror *internalACSRouterCommunicationError - - // Router Communication Error Code - Code *string + Innererror *InternalACSRouterCommunicationError // Router Communication Error Message Message *string // Router Communication Error Target Target *string + + // READ-ONLY; List of Router Communication Errors + Errors []InternalACSRouterCommunicationError + + // Router Communication Error Code + Code *string } // KeyVaultAccessPolicyChangedEventData - Schema of the Data property of an EventGridEvent for a Microsoft.KeyVault.VaultAccessPolicyChanged @@ -3411,36 +3558,54 @@ type MachineLearningServicesRunStatusChangedEventData struct { // MapsGeofenceEnteredEventData - Schema of the Data property of an EventGridEvent for a Microsoft.Maps.GeofenceEntered event. type MapsGeofenceEnteredEventData struct { - // REQUIRED; Lists of the geometry ID of the geofence which is expired relative to the user time in the request. + // REQUIRED; True if at least one event is published to the Azure Maps event subscriber, false if no event is published to + // the Azure Maps event subscriber. + IsEventPublished *bool + + // READ-ONLY; Lists of the geometry ID of the geofence which is expired relative to the user time in the request. ExpiredGeofenceGeometryID []string - // REQUIRED; Lists the fence geometries that either fully contain the coordinate position or have an overlap with the searchBuffer + // READ-ONLY; Lists the fence geometries that either fully contain the coordinate position or have an overlap with the searchBuffer // around the fence. Geometries []MapsGeofenceGeometry - // REQUIRED; Lists of the geometry ID of the geofence which is in invalid period relative to the user time in the request. + // READ-ONLY; Lists of the geometry ID of the geofence which is in invalid period relative to the user time in the request. InvalidPeriodGeofenceGeometryID []string +} +// MapsGeofenceEventProperties - Schema of the Data property of an EventGridEvent for a Geofence event (GeofenceEntered, GeofenceExited, +// GeofenceResult). +type MapsGeofenceEventProperties struct { // REQUIRED; True if at least one event is published to the Azure Maps event subscriber, false if no event is published to // the Azure Maps event subscriber. IsEventPublished *bool -} -// MapsGeofenceExitedEventData - Schema of the Data property of an EventGridEvent for a Microsoft.Maps.GeofenceExited event. -type MapsGeofenceExitedEventData struct { - // REQUIRED; Lists of the geometry ID of the geofence which is expired relative to the user time in the request. + // READ-ONLY; Lists of the geometry ID of the geofence which is expired relative to the user time in the request. ExpiredGeofenceGeometryID []string - // REQUIRED; Lists the fence geometries that either fully contain the coordinate position or have an overlap with the searchBuffer + // READ-ONLY; Lists the fence geometries that either fully contain the coordinate position or have an overlap with the searchBuffer // around the fence. Geometries []MapsGeofenceGeometry - // REQUIRED; Lists of the geometry ID of the geofence which is in invalid period relative to the user time in the request. + // READ-ONLY; Lists of the geometry ID of the geofence which is in invalid period relative to the user time in the request. InvalidPeriodGeofenceGeometryID []string +} +// MapsGeofenceExitedEventData - Schema of the Data property of an EventGridEvent for a Microsoft.Maps.GeofenceExited event. +type MapsGeofenceExitedEventData struct { // REQUIRED; True if at least one event is published to the Azure Maps event subscriber, false if no event is published to // the Azure Maps event subscriber. IsEventPublished *bool + + // READ-ONLY; Lists of the geometry ID of the geofence which is expired relative to the user time in the request. + ExpiredGeofenceGeometryID []string + + // READ-ONLY; Lists the fence geometries that either fully contain the coordinate position or have an overlap with the searchBuffer + // around the fence. + Geometries []MapsGeofenceGeometry + + // READ-ONLY; Lists of the geometry ID of the geofence which is in invalid period relative to the user time in the request. + InvalidPeriodGeofenceGeometryID []string } // MapsGeofenceGeometry - The geofence geometry. @@ -3471,19 +3636,19 @@ type MapsGeofenceGeometry struct { // MapsGeofenceResultEventData - Schema of the Data property of an EventGridEvent for a Microsoft.Maps.GeofenceResult event. type MapsGeofenceResultEventData struct { - // REQUIRED; Lists of the geometry ID of the geofence which is expired relative to the user time in the request. + // REQUIRED; True if at least one event is published to the Azure Maps event subscriber, false if no event is published to + // the Azure Maps event subscriber. + IsEventPublished *bool + + // READ-ONLY; Lists of the geometry ID of the geofence which is expired relative to the user time in the request. ExpiredGeofenceGeometryID []string - // REQUIRED; Lists the fence geometries that either fully contain the coordinate position or have an overlap with the searchBuffer + // READ-ONLY; Lists the fence geometries that either fully contain the coordinate position or have an overlap with the searchBuffer // around the fence. Geometries []MapsGeofenceGeometry - // REQUIRED; Lists of the geometry ID of the geofence which is in invalid period relative to the user time in the request. + // READ-ONLY; Lists of the geometry ID of the geofence which is in invalid period relative to the user time in the request. InvalidPeriodGeofenceGeometryID []string - - // REQUIRED; True if at least one event is published to the Azure Maps event subscriber, false if no event is published to - // the Azure Maps event subscriber. - IsEventPublished *bool } // MicrosoftTeamsAppIdentifierModel - A Microsoft Teams application. @@ -3952,6 +4117,16 @@ type ResourceNotificationsResourceDeletedDetails struct { Type *string } +// ResourceNotificationsResourceDeletedEventData - Describes the schema of the common properties across all ARN system topic +// delete events +type ResourceNotificationsResourceDeletedEventData struct { + // REQUIRED; details about operational info + OperationalDetails *ResourceNotificationsOperationalDetails + + // REQUIRED; resourceInfo details for delete event + ResourceDetails *ResourceNotificationsResourceDeletedDetails +} + // ResourceNotificationsResourceManagementCreatedOrUpdatedEventData - Schema of the Data property of an EventGridEvent for // a // Microsoft.ResourceNotifications.Resources.CreatedOrUpdated event. @@ -3998,6 +4173,19 @@ type ResourceNotificationsResourceUpdatedDetails struct { Tags map[string]*string } +// ResourceNotificationsResourceUpdatedEventData - Describes the schema of the common properties across all ARN system topic +// events +type ResourceNotificationsResourceUpdatedEventData struct { + // REQUIRED; api version of the resource properties bag + APIVersion *string + + // REQUIRED; details about operational info + OperationalDetails *ResourceNotificationsOperationalDetails + + // REQUIRED; resourceInfo details for update event + ResourceDetails *ResourceNotificationsResourceUpdatedDetails +} + // ResourceWriteCancelEventData - Schema of the Data property of an EventGridEvent for a Microsoft.Resources.ResourceWriteCancel // event. This is raised when a resource create or update operation is canceled. type ResourceWriteCancelEventData struct { diff --git a/sdk/messaging/eventgrid/azsystemevents/models_serde.go b/sdk/messaging/eventgrid/azsystemevents/models_serde.go index f235e882c25b..8aca33bd16a4 100644 --- a/sdk/messaging/eventgrid/azsystemevents/models_serde.go +++ b/sdk/messaging/eventgrid/azsystemevents/models_serde.go @@ -7,355 +7,21 @@ package azsystemevents import ( "encoding/json" "fmt" - "reflect" - "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "reflect" ) -// MarshalJSON implements the json.Marshaller interface for type ACSCallEndReasonProperties. -func (a ACSCallEndReasonProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]any) - populate(objectMap, "code", a.Code) - populate(objectMap, "phrase", a.Phrase) - populate(objectMap, "subCode", a.SubCode) - return json.Marshal(objectMap) -} - -// UnmarshalJSON implements the json.Unmarshaller interface for type ACSCallEndReasonProperties. -func (a *ACSCallEndReasonProperties) 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 "code": - err = unpopulate(val, "Code", &a.Code) - delete(rawMsg, key) - case "phrase": - err = unpopulate(val, "Phrase", &a.Phrase) - delete(rawMsg, key) - case "subCode": - err = unpopulate(val, "SubCode", &a.SubCode) - 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 ACSCallEndedByProperties. -func (a ACSCallEndedByProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]any) - populate(objectMap, "communicationIdentifier", a.CommunicationIdentifier) - populate(objectMap, "name", a.Name) - populate(objectMap, "type", a.Type) - return json.Marshal(objectMap) -} - -// UnmarshalJSON implements the json.Unmarshaller interface for type ACSCallEndedByProperties. -func (a *ACSCallEndedByProperties) 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 "communicationIdentifier": - err = unpopulate(val, "CommunicationIdentifier", &a.CommunicationIdentifier) - delete(rawMsg, key) - case "name": - err = unpopulate(val, "Name", &a.Name) - 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 ACSCallEndedEventData. -func (a ACSCallEndedEventData) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]any) - populate(objectMap, "callDurationInSeconds", a.CallDurationInSeconds) - populate(objectMap, "correlationId", a.CorrelationID) - populate(objectMap, "endedBy", a.EndedBy) - populate(objectMap, "group", a.Group) - populate(objectMap, "isRoomsCall", a.IsRoomsCall) - populate(objectMap, "isTwoParty", a.IsTwoParty) - populate(objectMap, "reason", a.Reason) - populate(objectMap, "room", a.Room) - populate(objectMap, "serverCallId", a.ServerCallID) - populate(objectMap, "startedBy", a.StartedBy) - return json.Marshal(objectMap) -} - -// UnmarshalJSON implements the json.Unmarshaller interface for type ACSCallEndedEventData. -func (a *ACSCallEndedEventData) 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 "callDurationInSeconds": - err = unpopulate(val, "CallDurationInSeconds", &a.CallDurationInSeconds) - delete(rawMsg, key) - case "correlationId": - err = unpopulate(val, "CorrelationID", &a.CorrelationID) - delete(rawMsg, key) - case "endedBy": - err = unpopulate(val, "EndedBy", &a.EndedBy) - delete(rawMsg, key) - case "group": - err = unpopulate(val, "Group", &a.Group) - delete(rawMsg, key) - case "isRoomsCall": - err = unpopulate(val, "IsRoomsCall", &a.IsRoomsCall) - delete(rawMsg, key) - case "isTwoParty": - err = unpopulate(val, "IsTwoParty", &a.IsTwoParty) - delete(rawMsg, key) - case "reason": - err = unpopulate(val, "Reason", &a.Reason) - delete(rawMsg, key) - case "room": - err = unpopulate(val, "Room", &a.Room) - delete(rawMsg, key) - case "serverCallId": - err = unpopulate(val, "ServerCallID", &a.ServerCallID) - delete(rawMsg, key) - case "startedBy": - err = unpopulate(val, "StartedBy", &a.StartedBy) - 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 ACSCallGroupProperties. -func (a ACSCallGroupProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]any) - populate(objectMap, "id", a.ID) - return json.Marshal(objectMap) -} - -// UnmarshalJSON implements the json.Unmarshaller interface for type ACSCallGroupProperties. -func (a *ACSCallGroupProperties) 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) - } - if err != nil { - return fmt.Errorf("unmarshalling type %T: %v", a, err) - } - } - return nil -} - -// MarshalJSON implements the json.Marshaller interface for type ACSCallParticipantAddedEventData. -func (a ACSCallParticipantAddedEventData) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]any) - populate(objectMap, "correlationId", a.CorrelationID) - populate(objectMap, "displayName", a.DisplayName) - populate(objectMap, "group", a.Group) - populate(objectMap, "isRoomsCall", a.IsRoomsCall) - populate(objectMap, "isTwoParty", a.IsTwoParty) - populate(objectMap, "participantId", a.ParticipantID) - populate(objectMap, "room", a.Room) - populate(objectMap, "serverCallId", a.ServerCallID) - populate(objectMap, "startedBy", a.StartedBy) - populate(objectMap, "user", a.User) - populate(objectMap, "userAgent", a.UserAgent) - return json.Marshal(objectMap) -} - -// UnmarshalJSON implements the json.Unmarshaller interface for type ACSCallParticipantAddedEventData. -func (a *ACSCallParticipantAddedEventData) 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 "correlationId": - err = unpopulate(val, "CorrelationID", &a.CorrelationID) - delete(rawMsg, key) - case "displayName": - err = unpopulate(val, "DisplayName", &a.DisplayName) - delete(rawMsg, key) - case "group": - err = unpopulate(val, "Group", &a.Group) - delete(rawMsg, key) - case "isRoomsCall": - err = unpopulate(val, "IsRoomsCall", &a.IsRoomsCall) - delete(rawMsg, key) - case "isTwoParty": - err = unpopulate(val, "IsTwoParty", &a.IsTwoParty) - delete(rawMsg, key) - case "participantId": - err = unpopulate(val, "ParticipantID", &a.ParticipantID) - delete(rawMsg, key) - case "room": - err = unpopulate(val, "Room", &a.Room) - delete(rawMsg, key) - case "serverCallId": - err = unpopulate(val, "ServerCallID", &a.ServerCallID) - delete(rawMsg, key) - case "startedBy": - err = unpopulate(val, "StartedBy", &a.StartedBy) - delete(rawMsg, key) - case "user": - err = unpopulate(val, "User", &a.User) - delete(rawMsg, key) - case "userAgent": - err = unpopulate(val, "UserAgent", &a.UserAgent) - 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 ACSCallParticipantEventProperties. -func (a ACSCallParticipantEventProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]any) - populate(objectMap, "correlationId", a.CorrelationID) - populate(objectMap, "displayName", a.DisplayName) - populate(objectMap, "group", a.Group) - populate(objectMap, "isRoomsCall", a.IsRoomsCall) - populate(objectMap, "isTwoParty", a.IsTwoParty) - populate(objectMap, "participantId", a.ParticipantID) - populate(objectMap, "room", a.Room) - populate(objectMap, "serverCallId", a.ServerCallID) - populate(objectMap, "startedBy", a.StartedBy) - populate(objectMap, "user", a.User) - populate(objectMap, "userAgent", a.UserAgent) - return json.Marshal(objectMap) -} - -// UnmarshalJSON implements the json.Unmarshaller interface for type ACSCallParticipantEventProperties. -func (a *ACSCallParticipantEventProperties) 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 "correlationId": - err = unpopulate(val, "CorrelationID", &a.CorrelationID) - delete(rawMsg, key) - case "displayName": - err = unpopulate(val, "DisplayName", &a.DisplayName) - delete(rawMsg, key) - case "group": - err = unpopulate(val, "Group", &a.Group) - delete(rawMsg, key) - case "isRoomsCall": - err = unpopulate(val, "IsRoomsCall", &a.IsRoomsCall) - delete(rawMsg, key) - case "isTwoParty": - err = unpopulate(val, "IsTwoParty", &a.IsTwoParty) - delete(rawMsg, key) - case "participantId": - err = unpopulate(val, "ParticipantID", &a.ParticipantID) - delete(rawMsg, key) - case "room": - err = unpopulate(val, "Room", &a.Room) - delete(rawMsg, key) - case "serverCallId": - err = unpopulate(val, "ServerCallID", &a.ServerCallID) - delete(rawMsg, key) - case "startedBy": - err = unpopulate(val, "StartedBy", &a.StartedBy) - delete(rawMsg, key) - case "user": - err = unpopulate(val, "User", &a.User) - delete(rawMsg, key) - case "userAgent": - err = unpopulate(val, "UserAgent", &a.UserAgent) - 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 ACSCallParticipantProperties. -func (a ACSCallParticipantProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]any) - populate(objectMap, "communicationIdentifier", a.CommunicationIdentifier) - populate(objectMap, "role", a.Role) - return json.Marshal(objectMap) -} - -// UnmarshalJSON implements the json.Unmarshaller interface for type ACSCallParticipantProperties. -func (a *ACSCallParticipantProperties) 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 "communicationIdentifier": - err = unpopulate(val, "CommunicationIdentifier", &a.CommunicationIdentifier) - delete(rawMsg, key) - case "role": - err = unpopulate(val, "Role", &a.Role) - 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 ACSCallParticipantRemovedEventData. -func (a ACSCallParticipantRemovedEventData) MarshalJSON() ([]byte, error) { +// MarshalJSON implements the json.Marshaller interface for type ACSChatEventBaseProperties. +func (a ACSChatEventBaseProperties) MarshalJSON() ([]byte, error) { objectMap := make(map[string]any) - populate(objectMap, "correlationId", a.CorrelationID) - populate(objectMap, "displayName", a.DisplayName) - populate(objectMap, "group", a.Group) - populate(objectMap, "isRoomsCall", a.IsRoomsCall) - populate(objectMap, "isTwoParty", a.IsTwoParty) - populate(objectMap, "participantId", a.ParticipantID) - populate(objectMap, "room", a.Room) - populate(objectMap, "serverCallId", a.ServerCallID) - populate(objectMap, "startedBy", a.StartedBy) - populate(objectMap, "user", a.User) - populate(objectMap, "userAgent", a.UserAgent) + populate(objectMap, "recipientCommunicationIdentifier", a.RecipientCommunicationIdentifier) + populate(objectMap, "threadId", a.ThreadID) + populate(objectMap, "transactionId", a.TransactionID) return json.Marshal(objectMap) } -// UnmarshalJSON implements the json.Unmarshaller interface for type ACSCallParticipantRemovedEventData. -func (a *ACSCallParticipantRemovedEventData) UnmarshalJSON(data []byte) error { +// UnmarshalJSON implements the json.Unmarshaller interface for type ACSChatEventBaseProperties. +func (a *ACSChatEventBaseProperties) 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) @@ -363,65 +29,14 @@ func (a *ACSCallParticipantRemovedEventData) UnmarshalJSON(data []byte) error { for key, val := range rawMsg { var err error switch key { - case "correlationId": - err = unpopulate(val, "CorrelationID", &a.CorrelationID) - delete(rawMsg, key) - case "displayName": - err = unpopulate(val, "DisplayName", &a.DisplayName) - delete(rawMsg, key) - case "group": - err = unpopulate(val, "Group", &a.Group) - delete(rawMsg, key) - case "isRoomsCall": - err = unpopulate(val, "IsRoomsCall", &a.IsRoomsCall) - delete(rawMsg, key) - case "isTwoParty": - err = unpopulate(val, "IsTwoParty", &a.IsTwoParty) - delete(rawMsg, key) - case "participantId": - err = unpopulate(val, "ParticipantID", &a.ParticipantID) - delete(rawMsg, key) - case "room": - err = unpopulate(val, "Room", &a.Room) - delete(rawMsg, key) - case "serverCallId": - err = unpopulate(val, "ServerCallID", &a.ServerCallID) - delete(rawMsg, key) - case "startedBy": - err = unpopulate(val, "StartedBy", &a.StartedBy) - delete(rawMsg, key) - case "user": - err = unpopulate(val, "User", &a.User) + case "recipientCommunicationIdentifier": + err = unpopulate(val, "RecipientCommunicationIdentifier", &a.RecipientCommunicationIdentifier) delete(rawMsg, key) - case "userAgent": - err = unpopulate(val, "UserAgent", &a.UserAgent) + case "threadId": + err = unpopulate(val, "ThreadID", &a.ThreadID) 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 ACSCallRoomProperties. -func (a ACSCallRoomProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]any) - populate(objectMap, "id", a.ID) - return json.Marshal(objectMap) -} - -// UnmarshalJSON implements the json.Unmarshaller interface for type ACSCallRoomProperties. -func (a *ACSCallRoomProperties) 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) + case "transactionId": + err = unpopulate(val, "TransactionID", &a.TransactionID) delete(rawMsg, key) } if err != nil { @@ -431,48 +46,28 @@ func (a *ACSCallRoomProperties) UnmarshalJSON(data []byte) error { return nil } -// MarshalJSON implements the json.Marshaller interface for type ACSCallStartedEventData. -func (a ACSCallStartedEventData) MarshalJSON() ([]byte, error) { +// MarshalJSON implements the json.Marshaller interface for type ACSChatEventInThreadBaseProperties. +func (a ACSChatEventInThreadBaseProperties) MarshalJSON() ([]byte, error) { objectMap := make(map[string]any) - populate(objectMap, "correlationId", a.CorrelationID) - populate(objectMap, "group", a.Group) - populate(objectMap, "isRoomsCall", a.IsRoomsCall) - populate(objectMap, "isTwoParty", a.IsTwoParty) - populate(objectMap, "room", a.Room) - populate(objectMap, "serverCallId", a.ServerCallID) - populate(objectMap, "startedBy", a.StartedBy) + populate(objectMap, "threadId", a.ThreadID) + populate(objectMap, "transactionId", a.TransactionID) return json.Marshal(objectMap) } -// UnmarshalJSON implements the json.Unmarshaller interface for type ACSCallStartedEventData. -func (a *ACSCallStartedEventData) UnmarshalJSON(data []byte) error { +// UnmarshalJSON implements the json.Unmarshaller interface for type ACSChatEventInThreadBaseProperties. +func (a *ACSChatEventInThreadBaseProperties) 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 "correlationId": - err = unpopulate(val, "CorrelationID", &a.CorrelationID) - delete(rawMsg, key) - case "group": - err = unpopulate(val, "Group", &a.Group) - delete(rawMsg, key) - case "isRoomsCall": - err = unpopulate(val, "IsRoomsCall", &a.IsRoomsCall) - delete(rawMsg, key) - case "isTwoParty": - err = unpopulate(val, "IsTwoParty", &a.IsTwoParty) - delete(rawMsg, key) - case "room": - err = unpopulate(val, "Room", &a.Room) - delete(rawMsg, key) - case "serverCallId": - err = unpopulate(val, "ServerCallID", &a.ServerCallID) + var err error + switch key { + case "threadId": + err = unpopulate(val, "ThreadID", &a.ThreadID) delete(rawMsg, key) - case "startedBy": - err = unpopulate(val, "StartedBy", &a.StartedBy) + case "transactionId": + err = unpopulate(val, "TransactionID", &a.TransactionID) delete(rawMsg, key) } if err != nil { @@ -482,21 +77,24 @@ func (a *ACSCallStartedEventData) UnmarshalJSON(data []byte) error { return nil } -// MarshalJSON implements the json.Marshaller interface for type ACSCallingEventProperties. -func (a ACSCallingEventProperties) MarshalJSON() ([]byte, error) { +// MarshalJSON implements the json.Marshaller interface for type ACSChatMessageDeletedEventData. +func (a ACSChatMessageDeletedEventData) MarshalJSON() ([]byte, error) { objectMap := make(map[string]any) - populate(objectMap, "correlationId", a.CorrelationID) - populate(objectMap, "group", a.Group) - populate(objectMap, "isRoomsCall", a.IsRoomsCall) - populate(objectMap, "isTwoParty", a.IsTwoParty) - populate(objectMap, "room", a.Room) - populate(objectMap, "serverCallId", a.ServerCallID) - populate(objectMap, "startedBy", a.StartedBy) + populateDateTimeRFC3339(objectMap, "composeTime", a.ComposeTime) + populateDateTimeRFC3339(objectMap, "deleteTime", a.DeleteTime) + populate(objectMap, "messageId", a.MessageID) + populate(objectMap, "recipientCommunicationIdentifier", a.RecipientCommunicationIdentifier) + populate(objectMap, "senderCommunicationIdentifier", a.SenderCommunicationIdentifier) + populate(objectMap, "senderDisplayName", a.SenderDisplayName) + populate(objectMap, "threadId", a.ThreadID) + populate(objectMap, "transactionId", a.TransactionID) + populate(objectMap, "type", a.Type) + populate(objectMap, "version", a.Version) return json.Marshal(objectMap) } -// UnmarshalJSON implements the json.Unmarshaller interface for type ACSCallingEventProperties. -func (a *ACSCallingEventProperties) UnmarshalJSON(data []byte) error { +// UnmarshalJSON implements the json.Unmarshaller interface for type ACSChatMessageDeletedEventData. +func (a *ACSChatMessageDeletedEventData) 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) @@ -504,26 +102,35 @@ func (a *ACSCallingEventProperties) UnmarshalJSON(data []byte) error { for key, val := range rawMsg { var err error switch key { - case "correlationId": - err = unpopulate(val, "CorrelationID", &a.CorrelationID) + case "composeTime": + err = unpopulateDateTimeRFC3339(val, "ComposeTime", &a.ComposeTime) + delete(rawMsg, key) + case "deleteTime": + err = unpopulateDateTimeRFC3339(val, "DeleteTime", &a.DeleteTime) + delete(rawMsg, key) + case "messageId": + err = unpopulate(val, "MessageID", &a.MessageID) delete(rawMsg, key) - case "group": - err = unpopulate(val, "Group", &a.Group) + case "recipientCommunicationIdentifier": + err = unpopulate(val, "RecipientCommunicationIdentifier", &a.RecipientCommunicationIdentifier) + delete(rawMsg, key) + case "senderCommunicationIdentifier": + err = unpopulate(val, "SenderCommunicationIdentifier", &a.SenderCommunicationIdentifier) delete(rawMsg, key) - case "isRoomsCall": - err = unpopulate(val, "IsRoomsCall", &a.IsRoomsCall) + case "senderDisplayName": + err = unpopulate(val, "SenderDisplayName", &a.SenderDisplayName) delete(rawMsg, key) - case "isTwoParty": - err = unpopulate(val, "IsTwoParty", &a.IsTwoParty) + case "threadId": + err = unpopulate(val, "ThreadID", &a.ThreadID) delete(rawMsg, key) - case "room": - err = unpopulate(val, "Room", &a.Room) + case "transactionId": + err = unpopulate(val, "TransactionID", &a.TransactionID) delete(rawMsg, key) - case "serverCallId": - err = unpopulate(val, "ServerCallID", &a.ServerCallID) + case "type": + err = unpopulate(val, "Type", &a.Type) delete(rawMsg, key) - case "startedBy": - err = unpopulate(val, "StartedBy", &a.StartedBy) + case "version": + err = unpopulate(val, "Version", &a.Version) delete(rawMsg, key) } if err != nil { @@ -533,13 +140,12 @@ func (a *ACSCallingEventProperties) UnmarshalJSON(data []byte) error { return nil } -// MarshalJSON implements the json.Marshaller interface for type ACSChatAzureBotCommandReceivedInThreadEventData. -func (a ACSChatAzureBotCommandReceivedInThreadEventData) MarshalJSON() ([]byte, error) { +// MarshalJSON implements the json.Marshaller interface for type ACSChatMessageDeletedInThreadEventData. +func (a ACSChatMessageDeletedInThreadEventData) MarshalJSON() ([]byte, error) { objectMap := make(map[string]any) populateDateTimeRFC3339(objectMap, "composeTime", a.ComposeTime) - populate(objectMap, "messageBody", a.MessageBody) + populateDateTimeRFC3339(objectMap, "deleteTime", a.DeleteTime) populate(objectMap, "messageId", a.MessageID) - populate(objectMap, "metadata", a.Metadata) populate(objectMap, "senderCommunicationIdentifier", a.SenderCommunicationIdentifier) populate(objectMap, "senderDisplayName", a.SenderDisplayName) populate(objectMap, "threadId", a.ThreadID) @@ -549,8 +155,8 @@ func (a ACSChatAzureBotCommandReceivedInThreadEventData) MarshalJSON() ([]byte, return json.Marshal(objectMap) } -// UnmarshalJSON implements the json.Unmarshaller interface for type ACSChatAzureBotCommandReceivedInThreadEventData. -func (a *ACSChatAzureBotCommandReceivedInThreadEventData) UnmarshalJSON(data []byte) error { +// UnmarshalJSON implements the json.Unmarshaller interface for type ACSChatMessageDeletedInThreadEventData. +func (a *ACSChatMessageDeletedInThreadEventData) 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) @@ -561,15 +167,12 @@ func (a *ACSChatAzureBotCommandReceivedInThreadEventData) UnmarshalJSON(data []b case "composeTime": err = unpopulateDateTimeRFC3339(val, "ComposeTime", &a.ComposeTime) delete(rawMsg, key) - case "messageBody": - err = unpopulate(val, "MessageBody", &a.MessageBody) + case "deleteTime": + err = unpopulateDateTimeRFC3339(val, "DeleteTime", &a.DeleteTime) delete(rawMsg, key) case "messageId": err = unpopulate(val, "MessageID", &a.MessageID) delete(rawMsg, key) - case "metadata": - err = unpopulate(val, "Metadata", &a.Metadata) - delete(rawMsg, key) case "senderCommunicationIdentifier": err = unpopulate(val, "SenderCommunicationIdentifier", &a.SenderCommunicationIdentifier) delete(rawMsg, key) @@ -596,12 +199,14 @@ func (a *ACSChatAzureBotCommandReceivedInThreadEventData) UnmarshalJSON(data []b return nil } -// MarshalJSON implements the json.Marshaller interface for type ACSChatMessageDeletedEventData. -func (a ACSChatMessageDeletedEventData) MarshalJSON() ([]byte, error) { +// MarshalJSON implements the json.Marshaller interface for type ACSChatMessageEditedEventData. +func (a ACSChatMessageEditedEventData) MarshalJSON() ([]byte, error) { objectMap := make(map[string]any) populateDateTimeRFC3339(objectMap, "composeTime", a.ComposeTime) - populateDateTimeRFC3339(objectMap, "deleteTime", a.DeleteTime) + populateDateTimeRFC3339(objectMap, "editTime", a.EditTime) + populate(objectMap, "messageBody", a.MessageBody) populate(objectMap, "messageId", a.MessageID) + populate(objectMap, "metadata", a.Metadata) populate(objectMap, "recipientCommunicationIdentifier", a.RecipientCommunicationIdentifier) populate(objectMap, "senderCommunicationIdentifier", a.SenderCommunicationIdentifier) populate(objectMap, "senderDisplayName", a.SenderDisplayName) @@ -612,8 +217,8 @@ func (a ACSChatMessageDeletedEventData) MarshalJSON() ([]byte, error) { return json.Marshal(objectMap) } -// UnmarshalJSON implements the json.Unmarshaller interface for type ACSChatMessageDeletedEventData. -func (a *ACSChatMessageDeletedEventData) UnmarshalJSON(data []byte) error { +// UnmarshalJSON implements the json.Unmarshaller interface for type ACSChatMessageEditedEventData. +func (a *ACSChatMessageEditedEventData) 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) @@ -624,12 +229,18 @@ func (a *ACSChatMessageDeletedEventData) UnmarshalJSON(data []byte) error { case "composeTime": err = unpopulateDateTimeRFC3339(val, "ComposeTime", &a.ComposeTime) delete(rawMsg, key) - case "deleteTime": - err = unpopulateDateTimeRFC3339(val, "DeleteTime", &a.DeleteTime) + case "editTime": + err = unpopulateDateTimeRFC3339(val, "EditTime", &a.EditTime) + delete(rawMsg, key) + case "messageBody": + err = unpopulate(val, "MessageBody", &a.MessageBody) delete(rawMsg, key) case "messageId": err = unpopulate(val, "MessageID", &a.MessageID) delete(rawMsg, key) + case "metadata": + err = unpopulate(val, "Metadata", &a.Metadata) + delete(rawMsg, key) case "recipientCommunicationIdentifier": err = unpopulate(val, "RecipientCommunicationIdentifier", &a.RecipientCommunicationIdentifier) delete(rawMsg, key) @@ -659,12 +270,14 @@ func (a *ACSChatMessageDeletedEventData) UnmarshalJSON(data []byte) error { return nil } -// MarshalJSON implements the json.Marshaller interface for type ACSChatMessageDeletedInThreadEventData. -func (a ACSChatMessageDeletedInThreadEventData) MarshalJSON() ([]byte, error) { +// MarshalJSON implements the json.Marshaller interface for type ACSChatMessageEditedInThreadEventData. +func (a ACSChatMessageEditedInThreadEventData) MarshalJSON() ([]byte, error) { objectMap := make(map[string]any) populateDateTimeRFC3339(objectMap, "composeTime", a.ComposeTime) - populateDateTimeRFC3339(objectMap, "deleteTime", a.DeleteTime) + populateDateTimeRFC3339(objectMap, "editTime", a.EditTime) + populate(objectMap, "messageBody", a.MessageBody) populate(objectMap, "messageId", a.MessageID) + populate(objectMap, "metadata", a.Metadata) populate(objectMap, "senderCommunicationIdentifier", a.SenderCommunicationIdentifier) populate(objectMap, "senderDisplayName", a.SenderDisplayName) populate(objectMap, "threadId", a.ThreadID) @@ -674,8 +287,8 @@ func (a ACSChatMessageDeletedInThreadEventData) MarshalJSON() ([]byte, error) { return json.Marshal(objectMap) } -// UnmarshalJSON implements the json.Unmarshaller interface for type ACSChatMessageDeletedInThreadEventData. -func (a *ACSChatMessageDeletedInThreadEventData) UnmarshalJSON(data []byte) error { +// UnmarshalJSON implements the json.Unmarshaller interface for type ACSChatMessageEditedInThreadEventData. +func (a *ACSChatMessageEditedInThreadEventData) 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) @@ -686,12 +299,18 @@ func (a *ACSChatMessageDeletedInThreadEventData) UnmarshalJSON(data []byte) erro case "composeTime": err = unpopulateDateTimeRFC3339(val, "ComposeTime", &a.ComposeTime) delete(rawMsg, key) - case "deleteTime": - err = unpopulateDateTimeRFC3339(val, "DeleteTime", &a.DeleteTime) + case "editTime": + err = unpopulateDateTimeRFC3339(val, "EditTime", &a.EditTime) + delete(rawMsg, key) + case "messageBody": + err = unpopulate(val, "MessageBody", &a.MessageBody) delete(rawMsg, key) case "messageId": err = unpopulate(val, "MessageID", &a.MessageID) delete(rawMsg, key) + case "metadata": + err = unpopulate(val, "Metadata", &a.Metadata) + delete(rawMsg, key) case "senderCommunicationIdentifier": err = unpopulate(val, "SenderCommunicationIdentifier", &a.SenderCommunicationIdentifier) delete(rawMsg, key) @@ -718,14 +337,11 @@ func (a *ACSChatMessageDeletedInThreadEventData) UnmarshalJSON(data []byte) erro return nil } -// MarshalJSON implements the json.Marshaller interface for type ACSChatMessageEditedEventData. -func (a ACSChatMessageEditedEventData) MarshalJSON() ([]byte, error) { +// MarshalJSON implements the json.Marshaller interface for type ACSChatMessageEventBaseProperties. +func (a ACSChatMessageEventBaseProperties) MarshalJSON() ([]byte, error) { objectMap := make(map[string]any) populateDateTimeRFC3339(objectMap, "composeTime", a.ComposeTime) - populateDateTimeRFC3339(objectMap, "editTime", a.EditTime) - populate(objectMap, "messageBody", a.MessageBody) populate(objectMap, "messageId", a.MessageID) - populate(objectMap, "metadata", a.Metadata) populate(objectMap, "recipientCommunicationIdentifier", a.RecipientCommunicationIdentifier) populate(objectMap, "senderCommunicationIdentifier", a.SenderCommunicationIdentifier) populate(objectMap, "senderDisplayName", a.SenderDisplayName) @@ -736,8 +352,8 @@ func (a ACSChatMessageEditedEventData) MarshalJSON() ([]byte, error) { return json.Marshal(objectMap) } -// UnmarshalJSON implements the json.Unmarshaller interface for type ACSChatMessageEditedEventData. -func (a *ACSChatMessageEditedEventData) UnmarshalJSON(data []byte) error { +// UnmarshalJSON implements the json.Unmarshaller interface for type ACSChatMessageEventBaseProperties. +func (a *ACSChatMessageEventBaseProperties) 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) @@ -748,18 +364,9 @@ func (a *ACSChatMessageEditedEventData) UnmarshalJSON(data []byte) error { case "composeTime": err = unpopulateDateTimeRFC3339(val, "ComposeTime", &a.ComposeTime) delete(rawMsg, key) - case "editTime": - err = unpopulateDateTimeRFC3339(val, "EditTime", &a.EditTime) - delete(rawMsg, key) - case "messageBody": - err = unpopulate(val, "MessageBody", &a.MessageBody) - delete(rawMsg, key) case "messageId": err = unpopulate(val, "MessageID", &a.MessageID) delete(rawMsg, key) - case "metadata": - err = unpopulate(val, "Metadata", &a.Metadata) - delete(rawMsg, key) case "recipientCommunicationIdentifier": err = unpopulate(val, "RecipientCommunicationIdentifier", &a.RecipientCommunicationIdentifier) delete(rawMsg, key) @@ -789,14 +396,11 @@ func (a *ACSChatMessageEditedEventData) UnmarshalJSON(data []byte) error { return nil } -// MarshalJSON implements the json.Marshaller interface for type ACSChatMessageEditedInThreadEventData. -func (a ACSChatMessageEditedInThreadEventData) MarshalJSON() ([]byte, error) { +// MarshalJSON implements the json.Marshaller interface for type ACSChatMessageEventInThreadBaseProperties. +func (a ACSChatMessageEventInThreadBaseProperties) MarshalJSON() ([]byte, error) { objectMap := make(map[string]any) populateDateTimeRFC3339(objectMap, "composeTime", a.ComposeTime) - populateDateTimeRFC3339(objectMap, "editTime", a.EditTime) - populate(objectMap, "messageBody", a.MessageBody) populate(objectMap, "messageId", a.MessageID) - populate(objectMap, "metadata", a.Metadata) populate(objectMap, "senderCommunicationIdentifier", a.SenderCommunicationIdentifier) populate(objectMap, "senderDisplayName", a.SenderDisplayName) populate(objectMap, "threadId", a.ThreadID) @@ -806,8 +410,8 @@ func (a ACSChatMessageEditedInThreadEventData) MarshalJSON() ([]byte, error) { return json.Marshal(objectMap) } -// UnmarshalJSON implements the json.Unmarshaller interface for type ACSChatMessageEditedInThreadEventData. -func (a *ACSChatMessageEditedInThreadEventData) UnmarshalJSON(data []byte) error { +// UnmarshalJSON implements the json.Unmarshaller interface for type ACSChatMessageEventInThreadBaseProperties. +func (a *ACSChatMessageEventInThreadBaseProperties) 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) @@ -818,18 +422,9 @@ func (a *ACSChatMessageEditedInThreadEventData) UnmarshalJSON(data []byte) error case "composeTime": err = unpopulateDateTimeRFC3339(val, "ComposeTime", &a.ComposeTime) delete(rawMsg, key) - case "editTime": - err = unpopulateDateTimeRFC3339(val, "EditTime", &a.EditTime) - delete(rawMsg, key) - case "messageBody": - err = unpopulate(val, "MessageBody", &a.MessageBody) - delete(rawMsg, key) case "messageId": err = unpopulate(val, "MessageID", &a.MessageID) delete(rawMsg, key) - case "metadata": - err = unpopulate(val, "Metadata", &a.Metadata) - delete(rawMsg, key) case "senderCommunicationIdentifier": err = unpopulate(val, "SenderCommunicationIdentifier", &a.SenderCommunicationIdentifier) delete(rawMsg, key) @@ -1167,15 +762,129 @@ func (a *ACSChatParticipantRemovedFromThreadWithUserEventData) UnmarshalJSON(dat case "recipientCommunicationIdentifier": err = unpopulate(val, "RecipientCommunicationIdentifier", &a.RecipientCommunicationIdentifier) delete(rawMsg, key) - case "removedByCommunicationIdentifier": - err = unpopulate(val, "RemovedByCommunicationIdentifier", &a.RemovedByCommunicationIdentifier) - delete(rawMsg, key) + case "removedByCommunicationIdentifier": + err = unpopulate(val, "RemovedByCommunicationIdentifier", &a.RemovedByCommunicationIdentifier) + delete(rawMsg, key) + case "threadId": + err = unpopulate(val, "ThreadID", &a.ThreadID) + delete(rawMsg, key) + case "time": + err = unpopulateDateTimeRFC3339(val, "Time", &a.Time) + delete(rawMsg, key) + case "transactionId": + err = unpopulate(val, "TransactionID", &a.TransactionID) + delete(rawMsg, key) + case "version": + err = unpopulate(val, "Version", &a.Version) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ACSChatThreadCreatedEventData. +func (a ACSChatThreadCreatedEventData) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateDateTimeRFC3339(objectMap, "createTime", a.CreateTime) + populate(objectMap, "createdByCommunicationIdentifier", a.CreatedByCommunicationIdentifier) + populate(objectMap, "metadata", a.Metadata) + populate(objectMap, "participants", a.Participants) + populate(objectMap, "properties", a.Properties) + populate(objectMap, "threadId", a.ThreadID) + populate(objectMap, "transactionId", a.TransactionID) + populate(objectMap, "version", a.Version) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ACSChatThreadCreatedEventData. +func (a *ACSChatThreadCreatedEventData) 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 "createTime": + err = unpopulateDateTimeRFC3339(val, "CreateTime", &a.CreateTime) + delete(rawMsg, key) + case "createdByCommunicationIdentifier": + err = unpopulate(val, "CreatedByCommunicationIdentifier", &a.CreatedByCommunicationIdentifier) + delete(rawMsg, key) + case "metadata": + err = unpopulate(val, "Metadata", &a.Metadata) + delete(rawMsg, key) + case "participants": + err = unpopulate(val, "Participants", &a.Participants) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &a.Properties) + delete(rawMsg, key) + case "threadId": + err = unpopulate(val, "ThreadID", &a.ThreadID) + delete(rawMsg, key) + case "transactionId": + err = unpopulate(val, "TransactionID", &a.TransactionID) + delete(rawMsg, key) + case "version": + err = unpopulate(val, "Version", &a.Version) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ACSChatThreadCreatedWithUserEventData. +func (a ACSChatThreadCreatedWithUserEventData) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateDateTimeRFC3339(objectMap, "createTime", a.CreateTime) + populate(objectMap, "createdByCommunicationIdentifier", a.CreatedByCommunicationIdentifier) + populate(objectMap, "metadata", a.Metadata) + populate(objectMap, "participants", a.Participants) + populate(objectMap, "properties", a.Properties) + populate(objectMap, "recipientCommunicationIdentifier", a.RecipientCommunicationIdentifier) + populate(objectMap, "threadId", a.ThreadID) + populate(objectMap, "transactionId", a.TransactionID) + populate(objectMap, "version", a.Version) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ACSChatThreadCreatedWithUserEventData. +func (a *ACSChatThreadCreatedWithUserEventData) 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 "createTime": + err = unpopulateDateTimeRFC3339(val, "CreateTime", &a.CreateTime) + delete(rawMsg, key) + case "createdByCommunicationIdentifier": + err = unpopulate(val, "CreatedByCommunicationIdentifier", &a.CreatedByCommunicationIdentifier) + delete(rawMsg, key) + case "metadata": + err = unpopulate(val, "Metadata", &a.Metadata) + delete(rawMsg, key) + case "participants": + err = unpopulate(val, "Participants", &a.Participants) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &a.Properties) + delete(rawMsg, key) + case "recipientCommunicationIdentifier": + err = unpopulate(val, "RecipientCommunicationIdentifier", &a.RecipientCommunicationIdentifier) + delete(rawMsg, key) case "threadId": err = unpopulate(val, "ThreadID", &a.ThreadID) delete(rawMsg, key) - case "time": - err = unpopulateDateTimeRFC3339(val, "Time", &a.Time) - delete(rawMsg, key) case "transactionId": err = unpopulate(val, "TransactionID", &a.TransactionID) delete(rawMsg, key) @@ -1190,22 +899,20 @@ func (a *ACSChatParticipantRemovedFromThreadWithUserEventData) UnmarshalJSON(dat return nil } -// MarshalJSON implements the json.Marshaller interface for type ACSChatThreadCreatedEventData. -func (a ACSChatThreadCreatedEventData) MarshalJSON() ([]byte, error) { +// MarshalJSON implements the json.Marshaller interface for type ACSChatThreadDeletedEventData. +func (a ACSChatThreadDeletedEventData) MarshalJSON() ([]byte, error) { objectMap := make(map[string]any) populateDateTimeRFC3339(objectMap, "createTime", a.CreateTime) - populate(objectMap, "createdByCommunicationIdentifier", a.CreatedByCommunicationIdentifier) - populate(objectMap, "metadata", a.Metadata) - populate(objectMap, "participants", a.Participants) - populate(objectMap, "properties", a.Properties) + populateDateTimeRFC3339(objectMap, "deleteTime", a.DeleteTime) + populate(objectMap, "deletedByCommunicationIdentifier", a.DeletedByCommunicationIdentifier) populate(objectMap, "threadId", a.ThreadID) populate(objectMap, "transactionId", a.TransactionID) populate(objectMap, "version", a.Version) return json.Marshal(objectMap) } -// UnmarshalJSON implements the json.Unmarshaller interface for type ACSChatThreadCreatedEventData. -func (a *ACSChatThreadCreatedEventData) UnmarshalJSON(data []byte) error { +// UnmarshalJSON implements the json.Unmarshaller interface for type ACSChatThreadDeletedEventData. +func (a *ACSChatThreadDeletedEventData) 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) @@ -1216,17 +923,11 @@ func (a *ACSChatThreadCreatedEventData) UnmarshalJSON(data []byte) error { case "createTime": err = unpopulateDateTimeRFC3339(val, "CreateTime", &a.CreateTime) delete(rawMsg, key) - case "createdByCommunicationIdentifier": - err = unpopulate(val, "CreatedByCommunicationIdentifier", &a.CreatedByCommunicationIdentifier) - delete(rawMsg, key) - case "metadata": - err = unpopulate(val, "Metadata", &a.Metadata) - delete(rawMsg, key) - case "participants": - err = unpopulate(val, "Participants", &a.Participants) + case "deleteTime": + err = unpopulateDateTimeRFC3339(val, "DeleteTime", &a.DeleteTime) delete(rawMsg, key) - case "properties": - err = unpopulate(val, "Properties", &a.Properties) + case "deletedByCommunicationIdentifier": + err = unpopulate(val, "DeletedByCommunicationIdentifier", &a.DeletedByCommunicationIdentifier) delete(rawMsg, key) case "threadId": err = unpopulate(val, "ThreadID", &a.ThreadID) @@ -1245,14 +946,10 @@ func (a *ACSChatThreadCreatedEventData) UnmarshalJSON(data []byte) error { return nil } -// MarshalJSON implements the json.Marshaller interface for type ACSChatThreadCreatedWithUserEventData. -func (a ACSChatThreadCreatedWithUserEventData) MarshalJSON() ([]byte, error) { +// MarshalJSON implements the json.Marshaller interface for type ACSChatThreadEventBaseProperties. +func (a ACSChatThreadEventBaseProperties) MarshalJSON() ([]byte, error) { objectMap := make(map[string]any) populateDateTimeRFC3339(objectMap, "createTime", a.CreateTime) - populate(objectMap, "createdByCommunicationIdentifier", a.CreatedByCommunicationIdentifier) - populate(objectMap, "metadata", a.Metadata) - populate(objectMap, "participants", a.Participants) - populate(objectMap, "properties", a.Properties) populate(objectMap, "recipientCommunicationIdentifier", a.RecipientCommunicationIdentifier) populate(objectMap, "threadId", a.ThreadID) populate(objectMap, "transactionId", a.TransactionID) @@ -1260,8 +957,8 @@ func (a ACSChatThreadCreatedWithUserEventData) MarshalJSON() ([]byte, error) { return json.Marshal(objectMap) } -// UnmarshalJSON implements the json.Unmarshaller interface for type ACSChatThreadCreatedWithUserEventData. -func (a *ACSChatThreadCreatedWithUserEventData) UnmarshalJSON(data []byte) error { +// UnmarshalJSON implements the json.Unmarshaller interface for type ACSChatThreadEventBaseProperties. +func (a *ACSChatThreadEventBaseProperties) 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) @@ -1272,18 +969,6 @@ func (a *ACSChatThreadCreatedWithUserEventData) UnmarshalJSON(data []byte) error case "createTime": err = unpopulateDateTimeRFC3339(val, "CreateTime", &a.CreateTime) delete(rawMsg, key) - case "createdByCommunicationIdentifier": - err = unpopulate(val, "CreatedByCommunicationIdentifier", &a.CreatedByCommunicationIdentifier) - delete(rawMsg, key) - case "metadata": - err = unpopulate(val, "Metadata", &a.Metadata) - delete(rawMsg, key) - case "participants": - err = unpopulate(val, "Participants", &a.Participants) - delete(rawMsg, key) - case "properties": - err = unpopulate(val, "Properties", &a.Properties) - delete(rawMsg, key) case "recipientCommunicationIdentifier": err = unpopulate(val, "RecipientCommunicationIdentifier", &a.RecipientCommunicationIdentifier) delete(rawMsg, key) @@ -1304,20 +989,18 @@ func (a *ACSChatThreadCreatedWithUserEventData) UnmarshalJSON(data []byte) error return nil } -// MarshalJSON implements the json.Marshaller interface for type ACSChatThreadDeletedEventData. -func (a ACSChatThreadDeletedEventData) MarshalJSON() ([]byte, error) { +// MarshalJSON implements the json.Marshaller interface for type ACSChatThreadEventInThreadBaseProperties. +func (a ACSChatThreadEventInThreadBaseProperties) MarshalJSON() ([]byte, error) { objectMap := make(map[string]any) populateDateTimeRFC3339(objectMap, "createTime", a.CreateTime) - populateDateTimeRFC3339(objectMap, "deleteTime", a.DeleteTime) - populate(objectMap, "deletedByCommunicationIdentifier", a.DeletedByCommunicationIdentifier) populate(objectMap, "threadId", a.ThreadID) populate(objectMap, "transactionId", a.TransactionID) populate(objectMap, "version", a.Version) return json.Marshal(objectMap) } -// UnmarshalJSON implements the json.Unmarshaller interface for type ACSChatThreadDeletedEventData. -func (a *ACSChatThreadDeletedEventData) UnmarshalJSON(data []byte) error { +// UnmarshalJSON implements the json.Unmarshaller interface for type ACSChatThreadEventInThreadBaseProperties. +func (a *ACSChatThreadEventInThreadBaseProperties) 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) @@ -1328,12 +1011,6 @@ func (a *ACSChatThreadDeletedEventData) UnmarshalJSON(data []byte) error { case "createTime": err = unpopulateDateTimeRFC3339(val, "CreateTime", &a.CreateTime) delete(rawMsg, key) - case "deleteTime": - err = unpopulateDateTimeRFC3339(val, "DeleteTime", &a.DeleteTime) - delete(rawMsg, key) - case "deletedByCommunicationIdentifier": - err = unpopulate(val, "DeletedByCommunicationIdentifier", &a.DeletedByCommunicationIdentifier) - delete(rawMsg, key) case "threadId": err = unpopulate(val, "ThreadID", &a.ThreadID) delete(rawMsg, key) @@ -1551,69 +1228,6 @@ func (a *ACSChatThreadWithUserDeletedEventData) UnmarshalJSON(data []byte) error return nil } -// MarshalJSON implements the json.Marshaller interface for type ACSChatTypingIndicatorReceivedInThreadEventData. -func (a ACSChatTypingIndicatorReceivedInThreadEventData) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]any) - populateDateTimeRFC3339(objectMap, "composeTime", a.ComposeTime) - populate(objectMap, "messageBody", a.MessageBody) - populate(objectMap, "messageId", a.MessageID) - populate(objectMap, "metadata", a.Metadata) - populate(objectMap, "senderCommunicationIdentifier", a.SenderCommunicationIdentifier) - populate(objectMap, "senderDisplayName", a.SenderDisplayName) - populate(objectMap, "threadId", a.ThreadID) - populate(objectMap, "transactionId", a.TransactionID) - populate(objectMap, "type", a.Type) - populate(objectMap, "version", a.Version) - return json.Marshal(objectMap) -} - -// UnmarshalJSON implements the json.Unmarshaller interface for type ACSChatTypingIndicatorReceivedInThreadEventData. -func (a *ACSChatTypingIndicatorReceivedInThreadEventData) 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 "composeTime": - err = unpopulateDateTimeRFC3339(val, "ComposeTime", &a.ComposeTime) - delete(rawMsg, key) - case "messageBody": - err = unpopulate(val, "MessageBody", &a.MessageBody) - delete(rawMsg, key) - case "messageId": - err = unpopulate(val, "MessageID", &a.MessageID) - delete(rawMsg, key) - case "metadata": - err = unpopulate(val, "Metadata", &a.Metadata) - delete(rawMsg, key) - case "senderCommunicationIdentifier": - err = unpopulate(val, "SenderCommunicationIdentifier", &a.SenderCommunicationIdentifier) - delete(rawMsg, key) - case "senderDisplayName": - err = unpopulate(val, "SenderDisplayName", &a.SenderDisplayName) - delete(rawMsg, key) - case "threadId": - err = unpopulate(val, "ThreadID", &a.ThreadID) - delete(rawMsg, key) - case "transactionId": - err = unpopulate(val, "TransactionID", &a.TransactionID) - delete(rawMsg, key) - case "type": - err = unpopulate(val, "Type", &a.Type) - delete(rawMsg, key) - case "version": - err = unpopulate(val, "Version", &a.Version) - delete(rawMsg, key) - } - if err != nil { - return fmt.Errorf("unmarshalling type %T: %v", a, err) - } - } - return nil -} - // MarshalJSON implements the json.Marshaller interface for type ACSEmailDeliveryReportReceivedEventData. func (a ACSEmailDeliveryReportReceivedEventData) MarshalJSON() ([]byte, error) { objectMap := make(map[string]any) @@ -1921,7 +1535,7 @@ func (a *ACSMessageDeliveryStatusUpdatedEventData) UnmarshalJSON(data []byte) er err = unpopulate(val, "ChannelKind", &a.ChannelKind) delete(rawMsg, key) case "error": - err = unmarshalInternalACSMessageChannelEventError(val, "Error", &a.Error) + err = unpopulate(val, "Error", &a.Error) delete(rawMsg, key) case "from": err = unpopulate(val, "From", &a.From) @@ -1946,6 +1560,45 @@ func (a *ACSMessageDeliveryStatusUpdatedEventData) UnmarshalJSON(data []byte) er return nil } +// MarshalJSON implements the json.Marshaller interface for type ACSMessageEventData. +func (a ACSMessageEventData) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "error", a.Error) + populate(objectMap, "from", a.From) + populateDateTimeRFC3339(objectMap, "receivedTimeStamp", a.ReceivedTimestamp) + populate(objectMap, "to", a.To) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ACSMessageEventData. +func (a *ACSMessageEventData) 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 "error": + err = unpopulate(val, "Error", &a.Error) + delete(rawMsg, key) + case "from": + err = unpopulate(val, "From", &a.From) + delete(rawMsg, key) + case "receivedTimeStamp": + err = unpopulateDateTimeRFC3339(val, "ReceivedTimestamp", &a.ReceivedTimestamp) + delete(rawMsg, key) + case "to": + err = unpopulate(val, "To", &a.To) + 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 ACSMessageInteractiveButtonReplyContent. func (a ACSMessageInteractiveButtonReplyContent) MarshalJSON() ([]byte, error) { objectMap := make(map[string]any) @@ -2162,7 +1815,7 @@ func (a *ACSMessageReceivedEventData) UnmarshalJSON(data []byte) error { err = unpopulate(val, "Context", &a.Context) delete(rawMsg, key) case "error": - err = unmarshalInternalACSMessageChannelEventError(val, "Error", &a.Error) + err = unpopulate(val, "Error", &a.Error) delete(rawMsg, key) case "from": err = unpopulate(val, "From", &a.From) @@ -2356,6 +2009,41 @@ func (a *ACSRouterChannelConfiguration) UnmarshalJSON(data []byte) error { return nil } +// MarshalJSON implements the json.Marshaller interface for type ACSRouterEventData. +func (a ACSRouterEventData) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "channelId", a.ChannelID) + populate(objectMap, "channelReference", a.ChannelReference) + populate(objectMap, "jobId", a.JobID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ACSRouterEventData. +func (a *ACSRouterEventData) 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 "channelId": + err = unpopulate(val, "ChannelID", &a.ChannelID) + delete(rawMsg, key) + case "channelReference": + err = unpopulate(val, "ChannelReference", &a.ChannelReference) + delete(rawMsg, key) + case "jobId": + err = unpopulate(val, "JobID", &a.JobID) + 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 ACSRouterJobCancelledEventData. func (a ACSRouterJobCancelledEventData) MarshalJSON() ([]byte, error) { objectMap := make(map[string]any) @@ -2444,7 +2132,7 @@ func (a *ACSRouterJobClassificationFailedEventData) UnmarshalJSON(data []byte) e err = unpopulate(val, "ClassificationPolicyID", &a.ClassificationPolicyID) delete(rawMsg, key) case "errors": - err = unmarshalInternalACSRouterCommunicationError(val, "Errors", &a.Errors) + err = unpopulate(val, "Errors", &a.Errors) delete(rawMsg, key) case "jobId": err = unpopulate(val, "JobID", &a.JobID) @@ -2690,6 +2378,53 @@ func (a *ACSRouterJobDeletedEventData) UnmarshalJSON(data []byte) error { return nil } +// MarshalJSON implements the json.Marshaller interface for type ACSRouterJobEventData. +func (a ACSRouterJobEventData) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "channelId", a.ChannelID) + populate(objectMap, "channelReference", a.ChannelReference) + populate(objectMap, "jobId", a.JobID) + populate(objectMap, "labels", a.Labels) + populate(objectMap, "queueId", a.QueueID) + populate(objectMap, "tags", a.Tags) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ACSRouterJobEventData. +func (a *ACSRouterJobEventData) 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 "channelId": + err = unpopulate(val, "ChannelID", &a.ChannelID) + delete(rawMsg, key) + case "channelReference": + err = unpopulate(val, "ChannelReference", &a.ChannelReference) + delete(rawMsg, key) + case "jobId": + err = unpopulate(val, "JobID", &a.JobID) + delete(rawMsg, key) + case "labels": + err = unpopulate(val, "Labels", &a.Labels) + delete(rawMsg, key) + case "queueId": + err = unpopulate(val, "QueueID", &a.QueueID) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &a.Tags) + 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 ACSRouterJobExceptionTriggeredEventData. func (a ACSRouterJobExceptionTriggeredEventData) MarshalJSON() ([]byte, error) { objectMap := make(map[string]any) @@ -3193,15 +2928,45 @@ func (a *ACSRouterWorkerDeletedEventData) UnmarshalJSON(data []byte) error { return nil } -// MarshalJSON implements the json.Marshaller interface for type ACSRouterWorkerDeregisteredEventData. -func (a ACSRouterWorkerDeregisteredEventData) MarshalJSON() ([]byte, error) { +// MarshalJSON implements the json.Marshaller interface for type ACSRouterWorkerDeregisteredEventData. +func (a ACSRouterWorkerDeregisteredEventData) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "workerId", a.WorkerID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ACSRouterWorkerDeregisteredEventData. +func (a *ACSRouterWorkerDeregisteredEventData) 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 "workerId": + err = unpopulate(val, "WorkerID", &a.WorkerID) + 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 ACSRouterWorkerEventData. +func (a ACSRouterWorkerEventData) MarshalJSON() ([]byte, error) { objectMap := make(map[string]any) + populate(objectMap, "channelId", a.ChannelID) + populate(objectMap, "channelReference", a.ChannelReference) + populate(objectMap, "jobId", a.JobID) populate(objectMap, "workerId", a.WorkerID) return json.Marshal(objectMap) } -// UnmarshalJSON implements the json.Unmarshaller interface for type ACSRouterWorkerDeregisteredEventData. -func (a *ACSRouterWorkerDeregisteredEventData) UnmarshalJSON(data []byte) error { +// UnmarshalJSON implements the json.Unmarshaller interface for type ACSRouterWorkerEventData. +func (a *ACSRouterWorkerEventData) 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) @@ -3209,6 +2974,15 @@ func (a *ACSRouterWorkerDeregisteredEventData) UnmarshalJSON(data []byte) error for key, val := range rawMsg { var err error switch key { + case "channelId": + err = unpopulate(val, "ChannelID", &a.ChannelID) + delete(rawMsg, key) + case "channelReference": + err = unpopulate(val, "ChannelReference", &a.ChannelReference) + delete(rawMsg, key) + case "jobId": + err = unpopulate(val, "JobID", &a.JobID) + delete(rawMsg, key) case "workerId": err = unpopulate(val, "WorkerID", &a.WorkerID) delete(rawMsg, key) @@ -3742,6 +3516,41 @@ func (a *ACSSMSDeliveryReportReceivedEventData) UnmarshalJSON(data []byte) error return nil } +// MarshalJSON implements the json.Marshaller interface for type ACSSMSEventBaseProperties. +func (a ACSSMSEventBaseProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "from", a.From) + populate(objectMap, "messageId", a.MessageID) + populate(objectMap, "to", a.To) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ACSSMSEventBaseProperties. +func (a *ACSSMSEventBaseProperties) 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 "from": + err = unpopulate(val, "From", &a.From) + delete(rawMsg, key) + case "messageId": + err = unpopulate(val, "MessageID", &a.MessageID) + delete(rawMsg, key) + case "to": + err = unpopulate(val, "To", &a.To) + 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 ACSSMSReceivedEventData. func (a ACSSMSReceivedEventData) MarshalJSON() ([]byte, error) { objectMap := make(map[string]any) @@ -4079,6 +3888,122 @@ func (a *APIManagementAPIUpdatedEventData) UnmarshalJSON(data []byte) error { return nil } +// MarshalJSON implements the json.Marshaller interface for type APIManagementCircuitBreakerClosedEventData. +func (a APIManagementCircuitBreakerClosedEventData) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "backendName", a.BackendName) + populate(objectMap, "circuitBreaker", a.CircuitBreaker) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type APIManagementCircuitBreakerClosedEventData. +func (a *APIManagementCircuitBreakerClosedEventData) 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 "backendName": + err = unpopulate(val, "BackendName", &a.BackendName) + delete(rawMsg, key) + case "circuitBreaker": + err = unpopulate(val, "CircuitBreaker", &a.CircuitBreaker) + 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 APIManagementCircuitBreakerOpenedEventData. +func (a APIManagementCircuitBreakerOpenedEventData) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "backendName", a.BackendName) + populate(objectMap, "circuitBreaker", a.CircuitBreaker) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type APIManagementCircuitBreakerOpenedEventData. +func (a *APIManagementCircuitBreakerOpenedEventData) 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 "backendName": + err = unpopulate(val, "BackendName", &a.BackendName) + delete(rawMsg, key) + case "circuitBreaker": + err = unpopulate(val, "CircuitBreaker", &a.CircuitBreaker) + 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 APIManagementCircuitBreakerProperties. +func (a APIManagementCircuitBreakerProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "rules", a.Rules) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type APIManagementCircuitBreakerProperties. +func (a *APIManagementCircuitBreakerProperties) 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 "rules": + err = unpopulate(val, "Rules", &a.Rules) + 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 APIManagementExpiredGatewayTokenProperties. +func (a APIManagementExpiredGatewayTokenProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateDateTimeRFC3339(objectMap, "expiredAtUtc", a.ExpiredAtUTC) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type APIManagementExpiredGatewayTokenProperties. +func (a *APIManagementExpiredGatewayTokenProperties) 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 "expiredAtUtc": + err = unpopulateDateTimeRFC3339(val, "ExpiredAtUTC", &a.ExpiredAtUTC) + 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 APIManagementGatewayAPIAddedEventData. func (a APIManagementGatewayAPIAddedEventData) MarshalJSON() ([]byte, error) { objectMap := make(map[string]any) @@ -4349,6 +4274,99 @@ func (a *APIManagementGatewayHostnameConfigurationUpdatedEventData) UnmarshalJSO return nil } +// MarshalJSON implements the json.Marshaller interface for type APIManagementGatewayProperties. +func (a APIManagementGatewayProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "gatewayId", a.GatewayID) + populate(objectMap, "instanceId", a.InstanceID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type APIManagementGatewayProperties. +func (a *APIManagementGatewayProperties) 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 "gatewayId": + err = unpopulate(val, "GatewayID", &a.GatewayID) + delete(rawMsg, key) + case "instanceId": + err = unpopulate(val, "InstanceID", &a.InstanceID) + 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 APIManagementGatewayTokenExpiredEventData. +func (a APIManagementGatewayTokenExpiredEventData) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "gatewayInfo", a.GatewayInfo) + populate(objectMap, "tokenInfo", a.TokenInfo) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type APIManagementGatewayTokenExpiredEventData. +func (a *APIManagementGatewayTokenExpiredEventData) 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 "gatewayInfo": + err = unpopulate(val, "GatewayInfo", &a.GatewayInfo) + delete(rawMsg, key) + case "tokenInfo": + err = unpopulate(val, "TokenInfo", &a.TokenInfo) + 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 APIManagementGatewayTokenNearExpiryEventData. +func (a APIManagementGatewayTokenNearExpiryEventData) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "gatewayInfo", a.GatewayInfo) + populate(objectMap, "tokenInfo", a.TokenInfo) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type APIManagementGatewayTokenNearExpiryEventData. +func (a *APIManagementGatewayTokenNearExpiryEventData) 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 "gatewayInfo": + err = unpopulate(val, "GatewayInfo", &a.GatewayInfo) + delete(rawMsg, key) + case "tokenInfo": + err = unpopulate(val, "TokenInfo", &a.TokenInfo) + 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 APIManagementGatewayUpdatedEventData. func (a APIManagementGatewayUpdatedEventData) MarshalJSON() ([]byte, error) { objectMap := make(map[string]any) @@ -4376,6 +4394,33 @@ func (a *APIManagementGatewayUpdatedEventData) UnmarshalJSON(data []byte) error return nil } +// MarshalJSON implements the json.Marshaller interface for type APIManagementNearExpiryGatewayTokenProperties. +func (a APIManagementNearExpiryGatewayTokenProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateDateTimeRFC3339(objectMap, "expiredAtUtc", a.ExpiredAtUTC) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type APIManagementNearExpiryGatewayTokenProperties. +func (a *APIManagementNearExpiryGatewayTokenProperties) 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 "expiredAtUtc": + err = unpopulateDateTimeRFC3339(val, "ExpiredAtUTC", &a.ExpiredAtUTC) + 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 APIManagementProductCreatedEventData. func (a APIManagementProductCreatedEventData) MarshalJSON() ([]byte, error) { objectMap := make(map[string]any) @@ -4619,8 +4664,47 @@ func (a *APIManagementUserUpdatedEventData) UnmarshalJSON(data []byte) error { return nil } -// MarshalJSON implements the json.Marshaller interface for type AVSClusterCreatedEventData. -func (a AVSClusterCreatedEventData) MarshalJSON() ([]byte, error) { +// MarshalJSON implements the json.Marshaller interface for type AVSClusterCreatedEventData. +func (a AVSClusterCreatedEventData) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "addedHostNames", a.AddedHostNames) + populate(objectMap, "inMaintenanceHostNames", a.InMaintenanceHostNames) + populate(objectMap, "operationId", a.OperationID) + populate(objectMap, "removedHostNames", a.RemovedHostNames) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AVSClusterCreatedEventData. +func (a *AVSClusterCreatedEventData) 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 "addedHostNames": + err = unpopulate(val, "AddedHostNames", &a.AddedHostNames) + delete(rawMsg, key) + case "inMaintenanceHostNames": + err = unpopulate(val, "InMaintenanceHostNames", &a.InMaintenanceHostNames) + delete(rawMsg, key) + case "operationId": + err = unpopulate(val, "OperationID", &a.OperationID) + delete(rawMsg, key) + case "removedHostNames": + err = unpopulate(val, "RemovedHostNames", &a.RemovedHostNames) + 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 AVSClusterDeletedEventData. +func (a AVSClusterDeletedEventData) MarshalJSON() ([]byte, error) { objectMap := make(map[string]any) populate(objectMap, "addedHostNames", a.AddedHostNames) populate(objectMap, "inMaintenanceHostNames", a.InMaintenanceHostNames) @@ -4629,8 +4713,8 @@ func (a AVSClusterCreatedEventData) MarshalJSON() ([]byte, error) { return json.Marshal(objectMap) } -// UnmarshalJSON implements the json.Unmarshaller interface for type AVSClusterCreatedEventData. -func (a *AVSClusterCreatedEventData) UnmarshalJSON(data []byte) error { +// UnmarshalJSON implements the json.Unmarshaller interface for type AVSClusterDeletedEventData. +func (a *AVSClusterDeletedEventData) 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) @@ -4658,8 +4742,8 @@ func (a *AVSClusterCreatedEventData) UnmarshalJSON(data []byte) error { return nil } -// MarshalJSON implements the json.Marshaller interface for type AVSClusterDeletedEventData. -func (a AVSClusterDeletedEventData) MarshalJSON() ([]byte, error) { +// MarshalJSON implements the json.Marshaller interface for type AVSClusterEventData. +func (a AVSClusterEventData) MarshalJSON() ([]byte, error) { objectMap := make(map[string]any) populate(objectMap, "addedHostNames", a.AddedHostNames) populate(objectMap, "inMaintenanceHostNames", a.InMaintenanceHostNames) @@ -4668,8 +4752,8 @@ func (a AVSClusterDeletedEventData) MarshalJSON() ([]byte, error) { return json.Marshal(objectMap) } -// UnmarshalJSON implements the json.Unmarshaller interface for type AVSClusterDeletedEventData. -func (a *AVSClusterDeletedEventData) UnmarshalJSON(data []byte) error { +// UnmarshalJSON implements the json.Unmarshaller interface for type AVSClusterEventData. +func (a *AVSClusterEventData) 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) @@ -4818,6 +4902,33 @@ func (a *AVSClusterUpdatingEventData) UnmarshalJSON(data []byte) error { return nil } +// MarshalJSON implements the json.Marshaller interface for type AVSPrivateCloudEventData. +func (a AVSPrivateCloudEventData) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "operationId", a.OperationID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AVSPrivateCloudEventData. +func (a *AVSPrivateCloudEventData) 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 "operationId": + err = unpopulate(val, "OperationID", &a.OperationID) + 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 AVSPrivateCloudFailedEventData. func (a AVSPrivateCloudFailedEventData) MarshalJSON() ([]byte, error) { objectMap := make(map[string]any) @@ -4938,6 +5049,41 @@ func (a *AVSScriptExecutionCancelledEventData) UnmarshalJSON(data []byte) error return nil } +// MarshalJSON implements the json.Marshaller interface for type AVSScriptExecutionEventData. +func (a AVSScriptExecutionEventData) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "cmdletId", a.CmdletID) + populate(objectMap, "operationId", a.OperationID) + populate(objectMap, "output", a.Output) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AVSScriptExecutionEventData. +func (a *AVSScriptExecutionEventData) 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 "cmdletId": + err = unpopulate(val, "CmdletID", &a.CmdletID) + delete(rawMsg, key) + case "operationId": + err = unpopulate(val, "OperationID", &a.OperationID) + delete(rawMsg, key) + case "output": + err = unpopulate(val, "Output", &a.Output) + 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 AVSScriptExecutionFailedEventData. func (a AVSScriptExecutionFailedEventData) MarshalJSON() ([]byte, error) { objectMap := make(map[string]any) @@ -5164,6 +5310,41 @@ func (a *AppConfigurationSnapshotCreatedEventData) UnmarshalJSON(data []byte) er return nil } +// MarshalJSON implements the json.Marshaller interface for type AppConfigurationSnapshotEventData. +func (a AppConfigurationSnapshotEventData) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", a.Etag) + populate(objectMap, "name", a.Name) + populate(objectMap, "syncToken", a.SyncToken) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AppConfigurationSnapshotEventData. +func (a *AppConfigurationSnapshotEventData) 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 "etag": + err = unpopulate(val, "Etag", &a.Etag) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &a.Name) + delete(rawMsg, key) + case "syncToken": + err = unpopulate(val, "SyncToken", &a.SyncToken) + 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 AppConfigurationSnapshotModifiedEventData. func (a AppConfigurationSnapshotModifiedEventData) MarshalJSON() ([]byte, error) { objectMap := make(map[string]any) @@ -5335,6 +5516,53 @@ func (c *CommunicationUserIdentifierModel) UnmarshalJSON(data []byte) error { return nil } +// MarshalJSON implements the json.Marshaller interface for type ContainerRegistryArtifactEventData. +func (c ContainerRegistryArtifactEventData) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "action", c.Action) + populate(objectMap, "connectedRegistry", c.ConnectedRegistry) + populate(objectMap, "id", c.ID) + populate(objectMap, "location", c.Location) + populate(objectMap, "target", c.Target) + populateDateTimeRFC3339(objectMap, "timestamp", c.Timestamp) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ContainerRegistryArtifactEventData. +func (c *ContainerRegistryArtifactEventData) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "action": + err = unpopulate(val, "Action", &c.Action) + delete(rawMsg, key) + case "connectedRegistry": + err = unpopulate(val, "ConnectedRegistry", &c.ConnectedRegistry) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &c.ID) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &c.Location) + delete(rawMsg, key) + case "target": + err = unpopulate(val, "Target", &c.Target) + delete(rawMsg, key) + case "timestamp": + err = unpopulateDateTimeRFC3339(val, "Timestamp", &c.Timestamp) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + // MarshalJSON implements the json.Marshaller interface for type ContainerRegistryArtifactEventTarget. func (c ContainerRegistryArtifactEventTarget) MarshalJSON() ([]byte, error) { objectMap := make(map[string]any) @@ -5534,6 +5762,65 @@ func (c *ContainerRegistryEventConnectedRegistry) UnmarshalJSON(data []byte) err return nil } +// MarshalJSON implements the json.Marshaller interface for type ContainerRegistryEventData. +func (c ContainerRegistryEventData) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "action", c.Action) + populate(objectMap, "actor", c.Actor) + populate(objectMap, "connectedRegistry", c.ConnectedRegistry) + populate(objectMap, "id", c.ID) + populate(objectMap, "location", c.Location) + populate(objectMap, "request", c.Request) + populate(objectMap, "source", c.Source) + populate(objectMap, "target", c.Target) + populateDateTimeRFC3339(objectMap, "timestamp", c.Timestamp) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ContainerRegistryEventData. +func (c *ContainerRegistryEventData) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "action": + err = unpopulate(val, "Action", &c.Action) + delete(rawMsg, key) + case "actor": + err = unpopulate(val, "Actor", &c.Actor) + delete(rawMsg, key) + case "connectedRegistry": + err = unpopulate(val, "ConnectedRegistry", &c.ConnectedRegistry) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &c.ID) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &c.Location) + delete(rawMsg, key) + case "request": + err = unpopulate(val, "Request", &c.Request) + delete(rawMsg, key) + case "source": + err = unpopulate(val, "Source", &c.Source) + delete(rawMsg, key) + case "target": + err = unpopulate(val, "Target", &c.Target) + delete(rawMsg, key) + case "timestamp": + err = unpopulateDateTimeRFC3339(val, "Timestamp", &c.Timestamp) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + // MarshalJSON implements the json.Marshaller interface for type ContainerRegistryEventRequest. func (c ContainerRegistryEventRequest) MarshalJSON() ([]byte, error) { objectMap := make(map[string]any) @@ -5831,18 +6118,81 @@ func (c *ContainerServiceClusterSupportEndingEventData) UnmarshalJSON(data []byt return nil } +// MarshalJSON implements the json.Marshaller interface for type ContainerServiceClusterSupportEventData. +func (c ContainerServiceClusterSupportEventData) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "kubernetesVersion", c.KubernetesVersion) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ContainerServiceClusterSupportEventData. +func (c *ContainerServiceClusterSupportEventData) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "kubernetesVersion": + err = unpopulate(val, "KubernetesVersion", &c.KubernetesVersion) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + // MarshalJSON implements the json.Marshaller interface for type ContainerServiceNewKubernetesVersionAvailableEventData. func (c ContainerServiceNewKubernetesVersionAvailableEventData) MarshalJSON() ([]byte, error) { objectMap := make(map[string]any) - populate(objectMap, "latestPreviewKubernetesVersion", c.LatestPreviewKubernetesVersion) - populate(objectMap, "latestStableKubernetesVersion", c.LatestStableKubernetesVersion) - populate(objectMap, "latestSupportedKubernetesVersion", c.LatestSupportedKubernetesVersion) - populate(objectMap, "lowestMinorKubernetesVersion", c.LowestMinorKubernetesVersion) + populate(objectMap, "latestPreviewKubernetesVersion", c.LatestPreviewKubernetesVersion) + populate(objectMap, "latestStableKubernetesVersion", c.LatestStableKubernetesVersion) + populate(objectMap, "latestSupportedKubernetesVersion", c.LatestSupportedKubernetesVersion) + populate(objectMap, "lowestMinorKubernetesVersion", c.LowestMinorKubernetesVersion) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ContainerServiceNewKubernetesVersionAvailableEventData. +func (c *ContainerServiceNewKubernetesVersionAvailableEventData) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "latestPreviewKubernetesVersion": + err = unpopulate(val, "LatestPreviewKubernetesVersion", &c.LatestPreviewKubernetesVersion) + delete(rawMsg, key) + case "latestStableKubernetesVersion": + err = unpopulate(val, "LatestStableKubernetesVersion", &c.LatestStableKubernetesVersion) + delete(rawMsg, key) + case "latestSupportedKubernetesVersion": + err = unpopulate(val, "LatestSupportedKubernetesVersion", &c.LatestSupportedKubernetesVersion) + delete(rawMsg, key) + case "lowestMinorKubernetesVersion": + err = unpopulate(val, "LowestMinorKubernetesVersion", &c.LowestMinorKubernetesVersion) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ContainerServiceNodePoolRollingEventData. +func (c ContainerServiceNodePoolRollingEventData) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nodePoolName", c.NodePoolName) return json.Marshal(objectMap) } -// UnmarshalJSON implements the json.Unmarshaller interface for type ContainerServiceNewKubernetesVersionAvailableEventData. -func (c *ContainerServiceNewKubernetesVersionAvailableEventData) UnmarshalJSON(data []byte) error { +// UnmarshalJSON implements the json.Unmarshaller interface for type ContainerServiceNodePoolRollingEventData. +func (c *ContainerServiceNodePoolRollingEventData) UnmarshalJSON(data []byte) error { var rawMsg map[string]json.RawMessage if err := json.Unmarshal(data, &rawMsg); err != nil { return fmt.Errorf("unmarshalling type %T: %v", c, err) @@ -5850,17 +6200,8 @@ func (c *ContainerServiceNewKubernetesVersionAvailableEventData) UnmarshalJSON(d for key, val := range rawMsg { var err error switch key { - case "latestPreviewKubernetesVersion": - err = unpopulate(val, "LatestPreviewKubernetesVersion", &c.LatestPreviewKubernetesVersion) - delete(rawMsg, key) - case "latestStableKubernetesVersion": - err = unpopulate(val, "LatestStableKubernetesVersion", &c.LatestStableKubernetesVersion) - delete(rawMsg, key) - case "latestSupportedKubernetesVersion": - err = unpopulate(val, "LatestSupportedKubernetesVersion", &c.LatestSupportedKubernetesVersion) - delete(rawMsg, key) - case "lowestMinorKubernetesVersion": - err = unpopulate(val, "LowestMinorKubernetesVersion", &c.LowestMinorKubernetesVersion) + case "nodePoolName": + err = unpopulate(val, "NodePoolName", &c.NodePoolName) delete(rawMsg, key) } if err != nil { @@ -6083,6 +6424,115 @@ func (d *DeviceConnectionStateEventInfo) UnmarshalJSON(data []byte) error { return nil } +// MarshalJSON implements the json.Marshaller interface for type DeviceConnectionStateEventProperties. +func (d DeviceConnectionStateEventProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "deviceConnectionStateEventInfo", d.DeviceConnectionStateEventInfo) + populate(objectMap, "deviceId", d.DeviceID) + populate(objectMap, "hubName", d.HubName) + populate(objectMap, "moduleId", d.ModuleID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DeviceConnectionStateEventProperties. +func (d *DeviceConnectionStateEventProperties) 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 "deviceConnectionStateEventInfo": + err = unpopulate(val, "DeviceConnectionStateEventInfo", &d.DeviceConnectionStateEventInfo) + delete(rawMsg, key) + case "deviceId": + err = unpopulate(val, "DeviceID", &d.DeviceID) + delete(rawMsg, key) + case "hubName": + err = unpopulate(val, "HubName", &d.HubName) + delete(rawMsg, key) + case "moduleId": + err = unpopulate(val, "ModuleID", &d.ModuleID) + 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 DeviceLifeCycleEventProperties. +func (d DeviceLifeCycleEventProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "deviceId", d.DeviceID) + populate(objectMap, "hubName", d.HubName) + populate(objectMap, "twin", d.Twin) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DeviceLifeCycleEventProperties. +func (d *DeviceLifeCycleEventProperties) 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 "deviceId": + err = unpopulate(val, "DeviceID", &d.DeviceID) + delete(rawMsg, key) + case "hubName": + err = unpopulate(val, "HubName", &d.HubName) + delete(rawMsg, key) + case "twin": + err = unpopulate(val, "Twin", &d.Twin) + 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 DeviceTelemetryEventProperties. +func (d DeviceTelemetryEventProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "body", d.Body) + populate(objectMap, "properties", d.Properties) + populate(objectMap, "systemProperties", d.SystemProperties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DeviceTelemetryEventProperties. +func (d *DeviceTelemetryEventProperties) 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 "body": + err = unpopulate(val, "Body", &d.Body) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &d.Properties) + delete(rawMsg, key) + case "systemProperties": + err = unpopulate(val, "SystemProperties", &d.SystemProperties) + 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 DeviceTwinInfo. func (d DeviceTwinInfo) MarshalJSON() ([]byte, error) { objectMap := make(map[string]any) @@ -6270,6 +6720,57 @@ func (d *DeviceTwinProperties) UnmarshalJSON(data []byte) error { return nil } +// MarshalJSON implements the json.Marshaller interface for type EdgeSolutionVersionPublishedEventData. +func (e EdgeSolutionVersionPublishedEventData) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "apiVersion", e.APIVersion) + populate(objectMap, "callbackUrl", e.CallbackURL) + populate(objectMap, "externalValidationId", e.ExternalValidationID) + populate(objectMap, "solutionTemplateId", e.SolutionTemplateID) + populate(objectMap, "solutionTemplateVersionId", e.SolutionTemplateVersionID) + populate(objectMap, "solutionVersionId", e.SolutionVersionID) + populate(objectMap, "targetId", e.TargetID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type EdgeSolutionVersionPublishedEventData. +func (e *EdgeSolutionVersionPublishedEventData) 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 "apiVersion": + err = unpopulate(val, "APIVersion", &e.APIVersion) + delete(rawMsg, key) + case "callbackUrl": + err = unpopulate(val, "CallbackURL", &e.CallbackURL) + delete(rawMsg, key) + case "externalValidationId": + err = unpopulate(val, "ExternalValidationID", &e.ExternalValidationID) + delete(rawMsg, key) + case "solutionTemplateId": + err = unpopulate(val, "SolutionTemplateID", &e.SolutionTemplateID) + delete(rawMsg, key) + case "solutionTemplateVersionId": + err = unpopulate(val, "SolutionTemplateVersionID", &e.SolutionTemplateVersionID) + delete(rawMsg, key) + case "solutionVersionId": + err = unpopulate(val, "SolutionVersionID", &e.SolutionVersionID) + delete(rawMsg, key) + case "targetId": + err = unpopulate(val, "TargetID", &e.TargetID) + 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 EventGridMQTTClientCreatedOrUpdatedEventData. func (e EventGridMQTTClientCreatedOrUpdatedEventData) MarshalJSON() ([]byte, error) { objectMap := make(map[string]any) @@ -6356,6 +6857,41 @@ func (e *EventGridMQTTClientDeletedEventData) UnmarshalJSON(data []byte) error { return nil } +// MarshalJSON implements the json.Marshaller interface for type EventGridMQTTClientEventData. +func (e EventGridMQTTClientEventData) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "clientAuthenticationName", e.ClientAuthenticationName) + populate(objectMap, "clientName", e.ClientName) + populate(objectMap, "namespaceName", e.NamespaceName) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type EventGridMQTTClientEventData. +func (e *EventGridMQTTClientEventData) 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 "clientAuthenticationName": + err = unpopulate(val, "ClientAuthenticationName", &e.ClientAuthenticationName) + delete(rawMsg, key) + case "clientName": + err = unpopulate(val, "ClientName", &e.ClientName) + delete(rawMsg, key) + case "namespaceName": + err = unpopulate(val, "NamespaceName", &e.NamespaceName) + 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 EventGridMQTTClientSessionConnectedEventData. func (e EventGridMQTTClientSessionConnectedEventData) MarshalJSON() ([]byte, error) { objectMap := make(map[string]any) @@ -6947,7 +7483,7 @@ func (i *IOTHubDeviceTelemetryEventData) UnmarshalJSON(data []byte) error { } // MarshalJSON implements the json.Marshaller interface for type InternalACSMessageChannelEventError. -func (i internalACSMessageChannelEventError) MarshalJSON() ([]byte, error) { +func (i InternalACSMessageChannelEventError) MarshalJSON() ([]byte, error) { objectMap := make(map[string]any) populate(objectMap, "channelCode", i.ChannelCode) populate(objectMap, "channelMessage", i.ChannelMessage) @@ -6955,7 +7491,7 @@ func (i internalACSMessageChannelEventError) MarshalJSON() ([]byte, error) { } // UnmarshalJSON implements the json.Unmarshaller interface for type InternalACSMessageChannelEventError. -func (i *internalACSMessageChannelEventError) UnmarshalJSON(data []byte) error { +func (i *InternalACSMessageChannelEventError) 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) @@ -6978,10 +7514,10 @@ func (i *internalACSMessageChannelEventError) UnmarshalJSON(data []byte) error { } // MarshalJSON implements the json.Marshaller interface for type InternalACSRouterCommunicationError. -func (i internalACSRouterCommunicationError) MarshalJSON() ([]byte, error) { +func (i InternalACSRouterCommunicationError) MarshalJSON() ([]byte, error) { objectMap := make(map[string]any) populate(objectMap, "code", i.Code) - populate(objectMap, "details", i.Details) + populate(objectMap, "errors", i.Errors) populate(objectMap, "innererror", i.Innererror) populate(objectMap, "message", i.Message) populate(objectMap, "target", i.Target) @@ -6989,7 +7525,7 @@ func (i internalACSRouterCommunicationError) MarshalJSON() ([]byte, error) { } // UnmarshalJSON implements the json.Unmarshaller interface for type InternalACSRouterCommunicationError. -func (i *internalACSRouterCommunicationError) UnmarshalJSON(data []byte) error { +func (i *InternalACSRouterCommunicationError) 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) @@ -7000,8 +7536,8 @@ func (i *internalACSRouterCommunicationError) UnmarshalJSON(data []byte) error { case "code": err = unpopulate(val, "Code", &i.Code) delete(rawMsg, key) - case "details": - err = unpopulate(val, "Details", &i.Details) + case "errors": + err = unpopulate(val, "Errors", &i.Errors) delete(rawMsg, key) case "innererror": err = unpopulate(val, "Innererror", &i.Innererror) @@ -7804,6 +8340,45 @@ func (m *MapsGeofenceEnteredEventData) UnmarshalJSON(data []byte) error { return nil } +// MarshalJSON implements the json.Marshaller interface for type MapsGeofenceEventProperties. +func (m MapsGeofenceEventProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "expiredGeofenceGeometryId", m.ExpiredGeofenceGeometryID) + populate(objectMap, "geometries", m.Geometries) + populate(objectMap, "invalidPeriodGeofenceGeometryId", m.InvalidPeriodGeofenceGeometryID) + populate(objectMap, "isEventPublished", m.IsEventPublished) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type MapsGeofenceEventProperties. +func (m *MapsGeofenceEventProperties) 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 "expiredGeofenceGeometryId": + err = unpopulate(val, "ExpiredGeofenceGeometryID", &m.ExpiredGeofenceGeometryID) + delete(rawMsg, key) + case "geometries": + err = unpopulate(val, "Geometries", &m.Geometries) + delete(rawMsg, key) + case "invalidPeriodGeofenceGeometryId": + err = unpopulate(val, "InvalidPeriodGeofenceGeometryID", &m.InvalidPeriodGeofenceGeometryID) + delete(rawMsg, key) + case "isEventPublished": + err = unpopulate(val, "IsEventPublished", &m.IsEventPublished) + 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 MapsGeofenceExitedEventData. func (m MapsGeofenceExitedEventData) MarshalJSON() ([]byte, error) { objectMap := make(map[string]any) @@ -8958,6 +9533,37 @@ func (r *ResourceNotificationsResourceDeletedDetails) UnmarshalJSON(data []byte) return nil } +// MarshalJSON implements the json.Marshaller interface for type ResourceNotificationsResourceDeletedEventData. +func (r ResourceNotificationsResourceDeletedEventData) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "operationalInfo", r.OperationalDetails) + populate(objectMap, "resourceInfo", r.ResourceDetails) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ResourceNotificationsResourceDeletedEventData. +func (r *ResourceNotificationsResourceDeletedEventData) 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 "operationalInfo": + err = unpopulate(val, "OperationalDetails", &r.OperationalDetails) + delete(rawMsg, key) + case "resourceInfo": + err = unpopulate(val, "ResourceDetails", &r.ResourceDetails) + 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 ResourceNotificationsResourceManagementCreatedOrUpdatedEventData. func (r ResourceNotificationsResourceManagementCreatedOrUpdatedEventData) MarshalJSON() ([]byte, error) { objectMap := make(map[string]any) @@ -9071,6 +9677,41 @@ func (r *ResourceNotificationsResourceUpdatedDetails) UnmarshalJSON(data []byte) return nil } +// MarshalJSON implements the json.Marshaller interface for type ResourceNotificationsResourceUpdatedEventData. +func (r ResourceNotificationsResourceUpdatedEventData) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "apiVersion", r.APIVersion) + populate(objectMap, "operationalInfo", r.OperationalDetails) + populate(objectMap, "resourceInfo", r.ResourceDetails) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ResourceNotificationsResourceUpdatedEventData. +func (r *ResourceNotificationsResourceUpdatedEventData) 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 "apiVersion": + err = unpopulate(val, "APIVersion", &r.APIVersion) + delete(rawMsg, key) + case "operationalInfo": + err = unpopulate(val, "OperationalDetails", &r.OperationalDetails) + delete(rawMsg, key) + case "resourceInfo": + err = unpopulate(val, "ResourceDetails", &r.ResourceDetails) + 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 ResourceWriteCancelEventData. func (r ResourceWriteCancelEventData) MarshalJSON() ([]byte, error) { objectMap := make(map[string]any) diff --git a/sdk/messaging/eventgrid/azsystemevents/time_rfc1123.go b/sdk/messaging/eventgrid/azsystemevents/time_rfc1123.go deleted file mode 100644 index c3039fc970bf..000000000000 --- a/sdk/messaging/eventgrid/azsystemevents/time_rfc1123.go +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. - -package azsystemevents - -import ( - "encoding/json" - "fmt" - "reflect" - "strings" - "time" - - "github.com/Azure/azure-sdk-for-go/sdk/azcore" -) - -const ( - dateTimeRFC1123JSON = `"` + time.RFC1123 + `"` -) - -type dateTimeRFC1123 time.Time - -func (t dateTimeRFC1123) MarshalJSON() ([]byte, error) { - b := []byte(time.Time(t).Format(dateTimeRFC1123JSON)) - return b, nil -} - -func (t dateTimeRFC1123) MarshalText() ([]byte, error) { - b := []byte(time.Time(t).Format(time.RFC1123)) - return b, nil -} - -func (t *dateTimeRFC1123) UnmarshalJSON(data []byte) error { - p, err := time.Parse(dateTimeRFC1123JSON, strings.ToUpper(string(data))) - *t = dateTimeRFC1123(p) - return err -} - -func (t *dateTimeRFC1123) UnmarshalText(data []byte) error { - if len(data) == 0 { - return nil - } - p, err := time.Parse(time.RFC1123, string(data)) - *t = dateTimeRFC1123(p) - return err -} - -func (t dateTimeRFC1123) String() string { - return time.Time(t).Format(time.RFC1123) -} - -func populateDateTimeRFC1123(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] = (*dateTimeRFC1123)(t) -} - -func unpopulateDateTimeRFC1123(data json.RawMessage, fn string, t **time.Time) error { - if data == nil || string(data) == "null" { - return nil - } - var aux dateTimeRFC1123 - if err := json.Unmarshal(data, &aux); err != nil { - return fmt.Errorf("struct field %s: %v", fn, err) - } - *t = (*time.Time)(&aux) - return nil -} diff --git a/sdk/messaging/eventgrid/azsystemevents/time_rfc3339.go b/sdk/messaging/eventgrid/azsystemevents/time_rfc3339.go index 11a0123184b4..8a459a317ff0 100644 --- a/sdk/messaging/eventgrid/azsystemevents/time_rfc3339.go +++ b/sdk/messaging/eventgrid/azsystemevents/time_rfc3339.go @@ -7,12 +7,11 @@ package azsystemevents import ( "encoding/json" "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" "reflect" "regexp" "strings" "time" - - "github.com/Azure/azure-sdk-for-go/sdk/azcore" ) // Azure reports time in UTC but it doesn't include the 'Z' time zone suffix in some cases. diff --git a/sdk/messaging/eventgrid/azsystemevents/tsp-location.yaml b/sdk/messaging/eventgrid/azsystemevents/tsp-location.yaml index bded21a43c24..286e8cd681d2 100644 --- a/sdk/messaging/eventgrid/azsystemevents/tsp-location.yaml +++ b/sdk/messaging/eventgrid/azsystemevents/tsp-location.yaml @@ -1,3 +1,4 @@ directory: specification/eventgrid/Azure.Messaging.EventGrid.SystemEvents -commit: a2676eccfc3db4abecc73519206d6ef3ff5826c9 +commit: 1f578543d267d08febc1bebf4e33ffe14363ddfc repo: Azure/azure-rest-api-specs +additionalDirectories: diff --git a/sdk/resourcemanager/agricultureplatform/armagricultureplatform/CHANGELOG.md b/sdk/resourcemanager/agricultureplatform/armagricultureplatform/CHANGELOG.md new file mode 100644 index 000000000000..f872b534dc96 --- /dev/null +++ b/sdk/resourcemanager/agricultureplatform/armagricultureplatform/CHANGELOG.md @@ -0,0 +1,8 @@ +# Release History + +## 0.1.0 (2025-04-27) +### Other Changes + +The package of `github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/agricultureplatform/armagricultureplatform` 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/agricultureplatform/armagricultureplatform/LICENSE.txt b/sdk/resourcemanager/agricultureplatform/armagricultureplatform/LICENSE.txt new file mode 100644 index 000000000000..dc0c2ffb3dc1 --- /dev/null +++ b/sdk/resourcemanager/agricultureplatform/armagricultureplatform/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/agricultureplatform/armagricultureplatform/README.md b/sdk/resourcemanager/agricultureplatform/armagricultureplatform/README.md new file mode 100644 index 000000000000..9520481a19d4 --- /dev/null +++ b/sdk/resourcemanager/agricultureplatform/armagricultureplatform/README.md @@ -0,0 +1,90 @@ +# Azure Agricultureplatform Module for Go + +The `armagricultureplatform` module provides operations for working with Azure Agricultureplatform. + +[Source code](https://github.com/Azure/azure-sdk-for-go/tree/main/sdk/resourcemanager/agricultureplatform/armagricultureplatform) + +# 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 Agricultureplatform module: + +```sh +go get github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/agricultureplatform/armagricultureplatform +``` + +## Authorization + +When creating a client, you will need to provide a credential for authenticating with Azure Agricultureplatform. 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 Agricultureplatform 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 := armagricultureplatform.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 := armagricultureplatform.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.NewAgriServiceClient() +``` + +## 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 `Agricultureplatform` 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/agricultureplatform/armagricultureplatform/agriservice_client.go b/sdk/resourcemanager/agricultureplatform/armagricultureplatform/agriservice_client.go new file mode 100644 index 000000000000..dab322d1ad7e --- /dev/null +++ b/sdk/resourcemanager/agricultureplatform/armagricultureplatform/agriservice_client.go @@ -0,0 +1,520 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armagricultureplatform + +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" +) + +// AgriServiceClient contains the methods for the AgriService group. +// Don't use this type directly, use NewAgriServiceClient() instead. +type AgriServiceClient struct { + internal *arm.Client + subscriptionID string +} + +// NewAgriServiceClient creates a new instance of AgriServiceClient 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 NewAgriServiceClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*AgriServiceClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &AgriServiceClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Create a AgriServiceResource +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-06-01-preview +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - agriServiceResourceName - The name of the AgriService resource. +// - resource - Resource create parameters. +// - options - AgriServiceClientBeginCreateOrUpdateOptions contains the optional parameters for the AgriServiceClient.BeginCreateOrUpdate +// method. +func (client *AgriServiceClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, agriServiceResourceName string, resource AgriServiceResource, options *AgriServiceClientBeginCreateOrUpdateOptions) (*runtime.Poller[AgriServiceClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, agriServiceResourceName, resource, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[AgriServiceClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[AgriServiceClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Create a AgriServiceResource +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-06-01-preview +func (client *AgriServiceClient) createOrUpdate(ctx context.Context, resourceGroupName string, agriServiceResourceName string, resource AgriServiceResource, options *AgriServiceClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "AgriServiceClient.BeginCreateOrUpdate" + 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, agriServiceResourceName, 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 +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *AgriServiceClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, agriServiceResourceName string, resource AgriServiceResource, _ *AgriServiceClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AgriculturePlatform/agriServices/{agriServiceResourceName}" + 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 agriServiceResourceName == "" { + return nil, errors.New("parameter agriServiceResourceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{agriServiceResourceName}", url.PathEscape(agriServiceResourceName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2024-06-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, resource); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Delete a AgriServiceResource +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-06-01-preview +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - agriServiceResourceName - The name of the AgriService resource. +// - options - AgriServiceClientBeginDeleteOptions contains the optional parameters for the AgriServiceClient.BeginDelete method. +func (client *AgriServiceClient) BeginDelete(ctx context.Context, resourceGroupName string, agriServiceResourceName string, options *AgriServiceClientBeginDeleteOptions) (*runtime.Poller[AgriServiceClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, agriServiceResourceName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[AgriServiceClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[AgriServiceClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Delete a AgriServiceResource +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-06-01-preview +func (client *AgriServiceClient) deleteOperation(ctx context.Context, resourceGroupName string, agriServiceResourceName string, options *AgriServiceClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "AgriServiceClient.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, agriServiceResourceName, 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 *AgriServiceClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, agriServiceResourceName string, _ *AgriServiceClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AgriculturePlatform/agriServices/{agriServiceResourceName}" + 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 agriServiceResourceName == "" { + return nil, errors.New("parameter agriServiceResourceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{agriServiceResourceName}", url.PathEscape(agriServiceResourceName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2024-06-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Get a AgriServiceResource +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-06-01-preview +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - agriServiceResourceName - The name of the AgriService resource. +// - options - AgriServiceClientGetOptions contains the optional parameters for the AgriServiceClient.Get method. +func (client *AgriServiceClient) Get(ctx context.Context, resourceGroupName string, agriServiceResourceName string, options *AgriServiceClientGetOptions) (AgriServiceClientGetResponse, error) { + var err error + const operationName = "AgriServiceClient.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, agriServiceResourceName, options) + if err != nil { + return AgriServiceClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return AgriServiceClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return AgriServiceClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *AgriServiceClient) getCreateRequest(ctx context.Context, resourceGroupName string, agriServiceResourceName string, _ *AgriServiceClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AgriculturePlatform/agriServices/{agriServiceResourceName}" + 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 agriServiceResourceName == "" { + return nil, errors.New("parameter agriServiceResourceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{agriServiceResourceName}", url.PathEscape(agriServiceResourceName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2024-06-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 *AgriServiceClient) getHandleResponse(resp *http.Response) (AgriServiceClientGetResponse, error) { + result := AgriServiceClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.AgriServiceResource); err != nil { + return AgriServiceClientGetResponse{}, err + } + return result, nil +} + +// ListAvailableSolutions - Returns the list of available agri solutions. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-06-01-preview +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - agriServiceResourceName - The name of the AgriService resource. +// - options - AgriServiceClientListAvailableSolutionsOptions contains the optional parameters for the AgriServiceClient.ListAvailableSolutions +// method. +func (client *AgriServiceClient) ListAvailableSolutions(ctx context.Context, resourceGroupName string, agriServiceResourceName string, options *AgriServiceClientListAvailableSolutionsOptions) (AgriServiceClientListAvailableSolutionsResponse, error) { + var err error + const operationName = "AgriServiceClient.ListAvailableSolutions" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.listAvailableSolutionsCreateRequest(ctx, resourceGroupName, agriServiceResourceName, options) + if err != nil { + return AgriServiceClientListAvailableSolutionsResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return AgriServiceClientListAvailableSolutionsResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return AgriServiceClientListAvailableSolutionsResponse{}, err + } + resp, err := client.listAvailableSolutionsHandleResponse(httpResp) + return resp, err +} + +// listAvailableSolutionsCreateRequest creates the ListAvailableSolutions request. +func (client *AgriServiceClient) listAvailableSolutionsCreateRequest(ctx context.Context, resourceGroupName string, agriServiceResourceName string, _ *AgriServiceClientListAvailableSolutionsOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AgriculturePlatform/agriServices/{agriServiceResourceName}/listAvailableSolutions" + 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 agriServiceResourceName == "" { + return nil, errors.New("parameter agriServiceResourceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{agriServiceResourceName}", url.PathEscape(agriServiceResourceName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2024-06-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listAvailableSolutionsHandleResponse handles the ListAvailableSolutions response. +func (client *AgriServiceClient) listAvailableSolutionsHandleResponse(resp *http.Response) (AgriServiceClientListAvailableSolutionsResponse, error) { + result := AgriServiceClientListAvailableSolutionsResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.AvailableAgriSolutionListResult); err != nil { + return AgriServiceClientListAvailableSolutionsResponse{}, err + } + return result, nil +} + +// NewListByResourceGroupPager - List AgriServiceResource resources by resource group +// +// Generated from API version 2024-06-01-preview +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - options - AgriServiceClientListByResourceGroupOptions contains the optional parameters for the AgriServiceClient.NewListByResourceGroupPager +// method. +func (client *AgriServiceClient) NewListByResourceGroupPager(resourceGroupName string, options *AgriServiceClientListByResourceGroupOptions) *runtime.Pager[AgriServiceClientListByResourceGroupResponse] { + return runtime.NewPager(runtime.PagingHandler[AgriServiceClientListByResourceGroupResponse]{ + More: func(page AgriServiceClientListByResourceGroupResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *AgriServiceClientListByResourceGroupResponse) (AgriServiceClientListByResourceGroupResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "AgriServiceClient.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 AgriServiceClientListByResourceGroupResponse{}, err + } + return client.listByResourceGroupHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByResourceGroupCreateRequest creates the ListByResourceGroup request. +func (client *AgriServiceClient) listByResourceGroupCreateRequest(ctx context.Context, resourceGroupName string, _ *AgriServiceClientListByResourceGroupOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AgriculturePlatform/agriServices" + 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", "2024-06-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 *AgriServiceClient) listByResourceGroupHandleResponse(resp *http.Response) (AgriServiceClientListByResourceGroupResponse, error) { + result := AgriServiceClientListByResourceGroupResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.AgriServiceResourceListResult); err != nil { + return AgriServiceClientListByResourceGroupResponse{}, err + } + return result, nil +} + +// NewListBySubscriptionPager - List AgriServiceResource resources by subscription ID +// +// Generated from API version 2024-06-01-preview +// - options - AgriServiceClientListBySubscriptionOptions contains the optional parameters for the AgriServiceClient.NewListBySubscriptionPager +// method. +func (client *AgriServiceClient) NewListBySubscriptionPager(options *AgriServiceClientListBySubscriptionOptions) *runtime.Pager[AgriServiceClientListBySubscriptionResponse] { + return runtime.NewPager(runtime.PagingHandler[AgriServiceClientListBySubscriptionResponse]{ + More: func(page AgriServiceClientListBySubscriptionResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *AgriServiceClientListBySubscriptionResponse) (AgriServiceClientListBySubscriptionResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "AgriServiceClient.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 AgriServiceClientListBySubscriptionResponse{}, err + } + return client.listBySubscriptionHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listBySubscriptionCreateRequest creates the ListBySubscription request. +func (client *AgriServiceClient) listBySubscriptionCreateRequest(ctx context.Context, _ *AgriServiceClientListBySubscriptionOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.AgriculturePlatform/agriServices" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2024-06-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 *AgriServiceClient) listBySubscriptionHandleResponse(resp *http.Response) (AgriServiceClientListBySubscriptionResponse, error) { + result := AgriServiceClientListBySubscriptionResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.AgriServiceResourceListResult); err != nil { + return AgriServiceClientListBySubscriptionResponse{}, err + } + return result, nil +} + +// BeginUpdate - Update a AgriServiceResource +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-06-01-preview +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - agriServiceResourceName - The name of the AgriService resource. +// - properties - The resource properties to be updated. +// - options - AgriServiceClientBeginUpdateOptions contains the optional parameters for the AgriServiceClient.BeginUpdate method. +func (client *AgriServiceClient) BeginUpdate(ctx context.Context, resourceGroupName string, agriServiceResourceName string, properties AgriServiceResourceUpdate, options *AgriServiceClientBeginUpdateOptions) (*runtime.Poller[AgriServiceClientUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.update(ctx, resourceGroupName, agriServiceResourceName, properties, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[AgriServiceClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[AgriServiceClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Update - Update a AgriServiceResource +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-06-01-preview +func (client *AgriServiceClient) update(ctx context.Context, resourceGroupName string, agriServiceResourceName string, properties AgriServiceResourceUpdate, options *AgriServiceClientBeginUpdateOptions) (*http.Response, error) { + var err error + const operationName = "AgriServiceClient.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, agriServiceResourceName, 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 *AgriServiceClient) updateCreateRequest(ctx context.Context, resourceGroupName string, agriServiceResourceName string, properties AgriServiceResourceUpdate, _ *AgriServiceClientBeginUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AgriculturePlatform/agriServices/{agriServiceResourceName}" + 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 agriServiceResourceName == "" { + return nil, errors.New("parameter agriServiceResourceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{agriServiceResourceName}", url.PathEscape(agriServiceResourceName)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2024-06-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, properties); err != nil { + return nil, err + } + return req, nil +} diff --git a/sdk/resourcemanager/agricultureplatform/armagricultureplatform/agriservice_client_example_test.go b/sdk/resourcemanager/agricultureplatform/armagricultureplatform/agriservice_client_example_test.go new file mode 100644 index 000000000000..6708e8a302dd --- /dev/null +++ b/sdk/resourcemanager/agricultureplatform/armagricultureplatform/agriservice_client_example_test.go @@ -0,0 +1,638 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armagricultureplatform_test + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/Azure/azure-sdk-for-go/sdk/azidentity" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/agricultureplatform/armagricultureplatform" + "log" +) + +// Generated from example definition: 2024-06-01-preview/AgriService_CreateOrUpdate_MaximumSet_Gen.json +func ExampleAgriServiceClient_BeginCreateOrUpdate() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armagricultureplatform.NewClientFactory("83D293F5-DEFD-4D48-B120-1DC713BE338A", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + poller, err := clientFactory.NewAgriServiceClient().BeginCreateOrUpdate(ctx, "rgopenapi", "abc123", armagricultureplatform.AgriServiceResource{ + Properties: &armagricultureplatform.AgriServiceResourceProperties{ + Config: &armagricultureplatform.AgriServiceConfig{}, + ManagedOnBehalfOfConfiguration: &armagricultureplatform.ManagedOnBehalfOfConfiguration{}, + DataConnectorCredentials: []*armagricultureplatform.DataConnectorCredentialMap{ + { + Key: to.Ptr("BackendAADApplicationCredentials"), + Value: &armagricultureplatform.DataConnectorCredentials{ + ClientID: to.Ptr("dce298a8-1eec-481a-a8f9-a3cd5a8257b2"), + }, + }, + }, + InstalledSolutions: []*armagricultureplatform.InstalledSolutionMap{ + { + Key: to.Ptr("bayerAgPowered.cwum"), + Value: &armagricultureplatform.Solution{ + ApplicationName: to.Ptr("bayerAgPowered.cwum"), + }, + }, + }, + }, + Identity: &armagricultureplatform.ManagedServiceIdentity{ + Type: to.Ptr(armagricultureplatform.ManagedServiceIdentityTypeNone), + UserAssignedIdentities: map[string]*armagricultureplatform.UserAssignedIdentity{ + "key4955": {}, + }, + }, + SKU: &armagricultureplatform.SKU{ + Name: to.Ptr("kfl"), + Tier: to.Ptr(armagricultureplatform.SKUTierFree), + Size: to.Ptr("r"), + Family: to.Ptr("xerdhxyjwrypvxphavgrtjphtohf"), + Capacity: to.Ptr[int32](20), + }, + Tags: map[string]*string{ + "key137": to.Ptr("oxwansfetzzgdwl"), + }, + Location: to.Ptr("pkneuknooprpqirnugzwbkiie"), + }, nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + res, err := poller.PollUntilDone(ctx, nil) + if err != nil { + log.Fatalf("failed to pull the result: %v", err) + } + // You could use response here. We use blank identifier for just demo purposes. + _ = res + // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // res = armagricultureplatform.AgriServiceClientCreateOrUpdateResponse{ + // AgriServiceResource: &armagricultureplatform.AgriServiceResource{ + // Properties: &armagricultureplatform.AgriServiceResourceProperties{ + // ProvisioningState: to.Ptr(armagricultureplatform.ProvisioningStateSucceeded), + // Config: &armagricultureplatform.AgriServiceConfig{ + // InstanceURI: to.Ptr("zwjvrpcyzxrsizerkzhwkergjrmxqe"), + // Version: to.Ptr("cwhczenyyxtmslccbv"), + // AppServiceResourceID: to.Ptr("icecbrltkdsresejoidqvlybwsbomotnbnmfa"), + // CosmosDbResourceID: to.Ptr("ygzwcdwitjqshybczyukwhaxkomgimvqdmqsdsx"), + // StorageAccountResourceID: to.Ptr("vdruhddgygpkcwngnvbstyitkzocrwnidpeowekohvisiprcmjzpe"), + // KeyVaultResourceID: to.Ptr("egw"), + // RedisCacheResourceID: to.Ptr("fxhznzcilbmqilgnryyazmhkssbhk"), + // }, + // ManagedOnBehalfOfConfiguration: &armagricultureplatform.ManagedOnBehalfOfConfiguration{ + // MoboBrokerResources: []*armagricultureplatform.MoboBrokerResource{ + // { + // ID: to.Ptr("bnthrkwfkfeorrzvtdxbfz"), + // }, + // }, + // }, + // DataConnectorCredentials: []*armagricultureplatform.DataConnectorCredentialMap{ + // { + // Key: to.Ptr("BackendAADApplicationCredentials"), + // Value: &armagricultureplatform.DataConnectorCredentials{ + // ClientID: to.Ptr("dce298a8-1eec-481a-a8f9-a3cd5a8257b2"), + // }, + // }, + // }, + // InstalledSolutions: []*armagricultureplatform.InstalledSolutionMap{ + // { + // Key: to.Ptr("bayerAgPowered.cwum"), + // Value: &armagricultureplatform.Solution{ + // ApplicationName: to.Ptr("bayerAgPowered.cwum"), + // }, + // }, + // }, + // }, + // Identity: &armagricultureplatform.ManagedServiceIdentity{ + // PrincipalID: to.Ptr("16763be4-6022-406e-a950-fcd5018633ca"), + // TenantID: to.Ptr("16763be4-6022-406e-a950-fcd5018633ca"), + // Type: to.Ptr(armagricultureplatform.ManagedServiceIdentityTypeNone), + // UserAssignedIdentities: map[string]*armagricultureplatform.UserAssignedIdentity{ + // "key4955": &armagricultureplatform.UserAssignedIdentity{ + // PrincipalID: to.Ptr("16763be4-6022-406e-a950-fcd5018633ca"), + // ClientID: to.Ptr("16763be4-6022-406e-a950-fcd5018633ca"), + // }, + // }, + // }, + // SKU: &armagricultureplatform.SKU{ + // Name: to.Ptr("kfl"), + // Tier: to.Ptr(armagricultureplatform.SKUTierFree), + // Size: to.Ptr("r"), + // Family: to.Ptr("xerdhxyjwrypvxphavgrtjphtohf"), + // Capacity: to.Ptr[int32](20), + // }, + // Tags: map[string]*string{ + // "key137": to.Ptr("oxwansfetzzgdwl"), + // }, + // Location: to.Ptr("pkneuknooprpqirnugzwbkiie"), + // ID: to.Ptr("/subscriptions/12345678-1234-1234-1234-123456789abc/resourceGroups/myResourceGroup/providers/Microsoft.Storage/storageAccounts/myStorageAccount"), + // Name: to.Ptr("mnvxvlitiwbndijhbmgiejz"), + // Type: to.Ptr("fvvidjmentwsi"), + // SystemData: &armagricultureplatform.SystemData{ + // CreatedBy: to.Ptr("gthxegufst"), + // CreatedByType: to.Ptr(armagricultureplatform.CreatedByTypeUser), + // CreatedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2024-12-16T11:47:57.784Z"); return t}()), + // LastModifiedBy: to.Ptr("ovgqctuakdgemocstvwqmhyufe"), + // LastModifiedByType: to.Ptr(armagricultureplatform.CreatedByTypeUser), + // LastModifiedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2024-12-16T11:47:57.784Z"); return t}()), + // }, + // }, + // } +} + +// Generated from example definition: 2024-06-01-preview/AgriService_Delete_MaximumSet_Gen.json +func ExampleAgriServiceClient_BeginDelete() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armagricultureplatform.NewClientFactory("83D293F5-DEFD-4D48-B120-1DC713BE338A", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + poller, err := clientFactory.NewAgriServiceClient().BeginDelete(ctx, "rgopenapi", "abc123", nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + _, err = poller.PollUntilDone(ctx, nil) + if err != nil { + log.Fatalf("failed to pull the result: %v", err) + } +} + +// Generated from example definition: 2024-06-01-preview/AgriService_Get_MaximumSet_Gen.json +func ExampleAgriServiceClient_Get() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armagricultureplatform.NewClientFactory("83D293F5-DEFD-4D48-B120-1DC713BE338A", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + res, err := clientFactory.NewAgriServiceClient().Get(ctx, "rgopenapi", "abc123", nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + // You could use response here. We use blank identifier for just demo purposes. + _ = res + // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // res = armagricultureplatform.AgriServiceClientGetResponse{ + // AgriServiceResource: &armagricultureplatform.AgriServiceResource{ + // Properties: &armagricultureplatform.AgriServiceResourceProperties{ + // ProvisioningState: to.Ptr(armagricultureplatform.ProvisioningStateSucceeded), + // Config: &armagricultureplatform.AgriServiceConfig{ + // InstanceURI: to.Ptr("zwjvrpcyzxrsizerkzhwkergjrmxqe"), + // Version: to.Ptr("cwhczenyyxtmslccbv"), + // AppServiceResourceID: to.Ptr("icecbrltkdsresejoidqvlybwsbomotnbnmfa"), + // CosmosDbResourceID: to.Ptr("ygzwcdwitjqshybczyukwhaxkomgimvqdmqsdsx"), + // StorageAccountResourceID: to.Ptr("vdruhddgygpkcwngnvbstyitkzocrwnidpeowekohvisiprcmjzpe"), + // KeyVaultResourceID: to.Ptr("egw"), + // RedisCacheResourceID: to.Ptr("fxhznzcilbmqilgnryyazmhkssbhk"), + // }, + // ManagedOnBehalfOfConfiguration: &armagricultureplatform.ManagedOnBehalfOfConfiguration{ + // MoboBrokerResources: []*armagricultureplatform.MoboBrokerResource{ + // { + // ID: to.Ptr("bnthrkwfkfeorrzvtdxbfz"), + // }, + // }, + // }, + // DataConnectorCredentials: []*armagricultureplatform.DataConnectorCredentialMap{ + // { + // Key: to.Ptr("BackendAADApplicationCredentials"), + // Value: &armagricultureplatform.DataConnectorCredentials{ + // ClientID: to.Ptr("dce298a8-1eec-481a-a8f9-a3cd5a8257b2"), + // }, + // }, + // }, + // InstalledSolutions: []*armagricultureplatform.InstalledSolutionMap{ + // { + // Key: to.Ptr("bayerAgPowered.cwum"), + // Value: &armagricultureplatform.Solution{ + // ApplicationName: to.Ptr("bayerAgPowered.cwum"), + // }, + // }, + // }, + // }, + // Identity: &armagricultureplatform.ManagedServiceIdentity{ + // PrincipalID: to.Ptr("16763be4-6022-406e-a950-fcd5018633ca"), + // TenantID: to.Ptr("16763be4-6022-406e-a950-fcd5018633ca"), + // Type: to.Ptr(armagricultureplatform.ManagedServiceIdentityTypeNone), + // UserAssignedIdentities: map[string]*armagricultureplatform.UserAssignedIdentity{ + // "key4955": &armagricultureplatform.UserAssignedIdentity{ + // PrincipalID: to.Ptr("16763be4-6022-406e-a950-fcd5018633ca"), + // ClientID: to.Ptr("16763be4-6022-406e-a950-fcd5018633ca"), + // }, + // }, + // }, + // SKU: &armagricultureplatform.SKU{ + // Name: to.Ptr("kfl"), + // Tier: to.Ptr(armagricultureplatform.SKUTierFree), + // Size: to.Ptr("r"), + // Family: to.Ptr("xerdhxyjwrypvxphavgrtjphtohf"), + // Capacity: to.Ptr[int32](20), + // }, + // Tags: map[string]*string{ + // "key137": to.Ptr("oxwansfetzzgdwl"), + // }, + // Location: to.Ptr("pkneuknooprpqirnugzwbkiie"), + // ID: to.Ptr("/subscriptions/E1D6D0B0-6FE4-45D5-9C3F-50F4D1AF2F39/resourceGroups/rgopenapi/providers/Microsoft.AgriculturePlatform/agriServices/TKXbP-22-NGGH-1Eh55xGX"), + // Name: to.Ptr("mnvxvlitiwbndijhbmgiejz"), + // Type: to.Ptr("fvvidjmentwsi"), + // SystemData: &armagricultureplatform.SystemData{ + // CreatedBy: to.Ptr("gthxegufst"), + // CreatedByType: to.Ptr(armagricultureplatform.CreatedByTypeUser), + // CreatedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2024-12-16T11:47:57.784Z"); return t}()), + // LastModifiedBy: to.Ptr("ovgqctuakdgemocstvwqmhyufe"), + // LastModifiedByType: to.Ptr(armagricultureplatform.CreatedByTypeUser), + // LastModifiedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2024-12-16T11:47:57.784Z"); return t}()), + // }, + // }, + // } +} + +// Generated from example definition: 2024-06-01-preview/AgriService_ListAvailableSolutions_MaximumSet_Gen.json +func ExampleAgriServiceClient_ListAvailableSolutions() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armagricultureplatform.NewClientFactory("83D293F5-DEFD-4D48-B120-1DC713BE338A", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + res, err := clientFactory.NewAgriServiceClient().ListAvailableSolutions(ctx, "rgopenapi", "abc123", nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + // You could use response here. We use blank identifier for just demo purposes. + _ = res + // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // res = armagricultureplatform.AgriServiceClientListAvailableSolutionsResponse{ + // AvailableAgriSolutionListResult: &armagricultureplatform.AvailableAgriSolutionListResult{ + // Solutions: []*armagricultureplatform.DataManagerForAgricultureSolution{ + // { + // PartnerID: to.Ptr("dugq"), + // SolutionID: to.Ptr("sgdbaiygsffxcokkxygtepomgyspz"), + // PartnerTenantID: to.Ptr("nxvc"), + // DataAccessScopes: []*string{ + // to.Ptr("ognbthj"), + // }, + // MarketPlaceOfferDetails: &armagricultureplatform.MarketPlaceOfferDetails{ + // SaasOfferID: to.Ptr("xbzymkxqoggdcjrfyvpqaee"), + // PublisherID: to.Ptr("ihvsmtzqbgwudeicsawqovi"), + // }, + // SaasApplicationID: to.Ptr("ypzopzkbzukfxalmeu"), + // AccessAzureDataManagerForAgricultureApplicationID: to.Ptr("khzwsikjlokrhdhotartjeofpiw"), + // AccessAzureDataManagerForAgricultureApplicationName: to.Ptr("ztfnwoksuurzlizk"), + // IsValidateInput: to.Ptr(true), + // }, + // }, + // }, + // } +} + +// Generated from example definition: 2024-06-01-preview/AgriService_ListByResourceGroup_MaximumSet_Gen.json +func ExampleAgriServiceClient_NewListByResourceGroupPager() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armagricultureplatform.NewClientFactory("83D293F5-DEFD-4D48-B120-1DC713BE338A", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + pager := clientFactory.NewAgriServiceClient().NewListByResourceGroupPager("rgopenapi", nil) + for pager.More() { + page, err := pager.NextPage(ctx) + if err != nil { + log.Fatalf("failed to advance page: %v", err) + } + for _, v := range page.Value { + // You could use page here. We use blank identifier for just demo purposes. + _ = v + } + // If the HTTP response code is 200 as defined in example definition, your page structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // page = armagricultureplatform.AgriServiceClientListByResourceGroupResponse{ + // AgriServiceResourceListResult: armagricultureplatform.AgriServiceResourceListResult{ + // Value: []*armagricultureplatform.AgriServiceResource{ + // { + // Properties: &armagricultureplatform.AgriServiceResourceProperties{ + // ProvisioningState: to.Ptr(armagricultureplatform.ProvisioningStateSucceeded), + // Config: &armagricultureplatform.AgriServiceConfig{ + // InstanceURI: to.Ptr("zwjvrpcyzxrsizerkzhwkergjrmxqe"), + // Version: to.Ptr("cwhczenyyxtmslccbv"), + // AppServiceResourceID: to.Ptr("icecbrltkdsresejoidqvlybwsbomotnbnmfa"), + // CosmosDbResourceID: to.Ptr("ygzwcdwitjqshybczyukwhaxkomgimvqdmqsdsx"), + // StorageAccountResourceID: to.Ptr("vdruhddgygpkcwngnvbstyitkzocrwnidpeowekohvisiprcmjzpe"), + // KeyVaultResourceID: to.Ptr("egw"), + // RedisCacheResourceID: to.Ptr("fxhznzcilbmqilgnryyazmhkssbhk"), + // }, + // ManagedOnBehalfOfConfiguration: &armagricultureplatform.ManagedOnBehalfOfConfiguration{ + // MoboBrokerResources: []*armagricultureplatform.MoboBrokerResource{ + // { + // ID: to.Ptr("bnthrkwfkfeorrzvtdxbfz"), + // }, + // }, + // }, + // DataConnectorCredentials: []*armagricultureplatform.DataConnectorCredentialMap{ + // { + // Key: to.Ptr("BackendAADApplicationCredentials"), + // Value: &armagricultureplatform.DataConnectorCredentials{ + // ClientID: to.Ptr("dce298a8-1eec-481a-a8f9-a3cd5a8257b2"), + // }, + // }, + // }, + // InstalledSolutions: []*armagricultureplatform.InstalledSolutionMap{ + // { + // Key: to.Ptr("bayerAgPowered.cwum"), + // Value: &armagricultureplatform.Solution{ + // ApplicationName: to.Ptr("bayerAgPowered.cwum"), + // }, + // }, + // }, + // }, + // Identity: &armagricultureplatform.ManagedServiceIdentity{ + // PrincipalID: to.Ptr("16763be4-6022-406e-a950-fcd5018633ca"), + // TenantID: to.Ptr("16763be4-6022-406e-a950-fcd5018633ca"), + // Type: to.Ptr(armagricultureplatform.ManagedServiceIdentityTypeNone), + // UserAssignedIdentities: map[string]*armagricultureplatform.UserAssignedIdentity{ + // "key4955": &armagricultureplatform.UserAssignedIdentity{ + // PrincipalID: to.Ptr("16763be4-6022-406e-a950-fcd5018633ca"), + // ClientID: to.Ptr("16763be4-6022-406e-a950-fcd5018633ca"), + // }, + // }, + // }, + // SKU: &armagricultureplatform.SKU{ + // Name: to.Ptr("kfl"), + // Tier: to.Ptr(armagricultureplatform.SKUTierFree), + // Size: to.Ptr("r"), + // Family: to.Ptr("xerdhxyjwrypvxphavgrtjphtohf"), + // Capacity: to.Ptr[int32](20), + // }, + // Tags: map[string]*string{ + // "key137": to.Ptr("oxwansfetzzgdwl"), + // }, + // Location: to.Ptr("pkneuknooprpqirnugzwbkiie"), + // ID: to.Ptr("/subscriptions/E1D6D0B0-6FE4-45D5-9C3F-50F4D1AF2F39/resourceGroups/rgopenapi/providers/Microsoft.AgriculturePlatform/agriServices/TKXbP-22-NGGH-1Eh55xGX"), + // Name: to.Ptr("mnvxvlitiwbndijhbmgiejz"), + // Type: to.Ptr("fvvidjmentwsi"), + // SystemData: &armagricultureplatform.SystemData{ + // CreatedBy: to.Ptr("gthxegufst"), + // CreatedByType: to.Ptr(armagricultureplatform.CreatedByTypeUser), + // CreatedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2024-12-16T11:47:57.784Z"); return t}()), + // LastModifiedBy: to.Ptr("ovgqctuakdgemocstvwqmhyufe"), + // LastModifiedByType: to.Ptr(armagricultureplatform.CreatedByTypeUser), + // LastModifiedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2024-12-16T11:47:57.784Z"); return t}()), + // }, + // }, + // }, + // NextLink: to.Ptr("https://microsoft.com/a"), + // }, + // } + } +} + +// Generated from example definition: 2024-06-01-preview/AgriService_ListBySubscription_MaximumSet_Gen.json +func ExampleAgriServiceClient_NewListBySubscriptionPager() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armagricultureplatform.NewClientFactory("83D293F5-DEFD-4D48-B120-1DC713BE338A", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + pager := clientFactory.NewAgriServiceClient().NewListBySubscriptionPager(nil) + for pager.More() { + page, err := pager.NextPage(ctx) + if err != nil { + log.Fatalf("failed to advance page: %v", err) + } + for _, v := range page.Value { + // You could use page here. We use blank identifier for just demo purposes. + _ = v + } + // If the HTTP response code is 200 as defined in example definition, your page structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // page = armagricultureplatform.AgriServiceClientListBySubscriptionResponse{ + // AgriServiceResourceListResult: armagricultureplatform.AgriServiceResourceListResult{ + // Value: []*armagricultureplatform.AgriServiceResource{ + // { + // Properties: &armagricultureplatform.AgriServiceResourceProperties{ + // ProvisioningState: to.Ptr(armagricultureplatform.ProvisioningStateSucceeded), + // Config: &armagricultureplatform.AgriServiceConfig{ + // InstanceURI: to.Ptr("zwjvrpcyzxrsizerkzhwkergjrmxqe"), + // Version: to.Ptr("cwhczenyyxtmslccbv"), + // AppServiceResourceID: to.Ptr("icecbrltkdsresejoidqvlybwsbomotnbnmfa"), + // CosmosDbResourceID: to.Ptr("ygzwcdwitjqshybczyukwhaxkomgimvqdmqsdsx"), + // StorageAccountResourceID: to.Ptr("vdruhddgygpkcwngnvbstyitkzocrwnidpeowekohvisiprcmjzpe"), + // KeyVaultResourceID: to.Ptr("egw"), + // RedisCacheResourceID: to.Ptr("fxhznzcilbmqilgnryyazmhkssbhk"), + // }, + // ManagedOnBehalfOfConfiguration: &armagricultureplatform.ManagedOnBehalfOfConfiguration{ + // MoboBrokerResources: []*armagricultureplatform.MoboBrokerResource{ + // { + // ID: to.Ptr("bnthrkwfkfeorrzvtdxbfz"), + // }, + // }, + // }, + // DataConnectorCredentials: []*armagricultureplatform.DataConnectorCredentialMap{ + // { + // Key: to.Ptr("BackendAADApplicationCredentials"), + // Value: &armagricultureplatform.DataConnectorCredentials{ + // ClientID: to.Ptr("dce298a8-1eec-481a-a8f9-a3cd5a8257b2"), + // }, + // }, + // }, + // InstalledSolutions: []*armagricultureplatform.InstalledSolutionMap{ + // { + // Key: to.Ptr("bayerAgPowered.cwum"), + // Value: &armagricultureplatform.Solution{ + // ApplicationName: to.Ptr("bayerAgPowered.cwum"), + // }, + // }, + // }, + // }, + // Identity: &armagricultureplatform.ManagedServiceIdentity{ + // PrincipalID: to.Ptr("16763be4-6022-406e-a950-fcd5018633ca"), + // TenantID: to.Ptr("16763be4-6022-406e-a950-fcd5018633ca"), + // Type: to.Ptr(armagricultureplatform.ManagedServiceIdentityTypeNone), + // UserAssignedIdentities: map[string]*armagricultureplatform.UserAssignedIdentity{ + // "key4955": &armagricultureplatform.UserAssignedIdentity{ + // PrincipalID: to.Ptr("16763be4-6022-406e-a950-fcd5018633ca"), + // ClientID: to.Ptr("16763be4-6022-406e-a950-fcd5018633ca"), + // }, + // }, + // }, + // SKU: &armagricultureplatform.SKU{ + // Name: to.Ptr("kfl"), + // Tier: to.Ptr(armagricultureplatform.SKUTierFree), + // Size: to.Ptr("r"), + // Family: to.Ptr("xerdhxyjwrypvxphavgrtjphtohf"), + // Capacity: to.Ptr[int32](20), + // }, + // Tags: map[string]*string{ + // "key137": to.Ptr("oxwansfetzzgdwl"), + // }, + // Location: to.Ptr("pkneuknooprpqirnugzwbkiie"), + // ID: to.Ptr("/subscriptions/E1D6D0B0-6FE4-45D5-9C3F-50F4D1AF2F39/resourceGroups/rgopenapi/providers/Microsoft.AgriculturePlatform/agriServices/TKXbP-22-NGGH-1Eh55xGX"), + // Name: to.Ptr("mnvxvlitiwbndijhbmgiejz"), + // Type: to.Ptr("fvvidjmentwsi"), + // SystemData: &armagricultureplatform.SystemData{ + // CreatedBy: to.Ptr("gthxegufst"), + // CreatedByType: to.Ptr(armagricultureplatform.CreatedByTypeUser), + // CreatedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2024-12-16T11:47:57.784Z"); return t}()), + // LastModifiedBy: to.Ptr("ovgqctuakdgemocstvwqmhyufe"), + // LastModifiedByType: to.Ptr(armagricultureplatform.CreatedByTypeUser), + // LastModifiedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2024-12-16T11:47:57.784Z"); return t}()), + // }, + // }, + // }, + // NextLink: to.Ptr("https://microsoft.com/a"), + // }, + // } + } +} + +// Generated from example definition: 2024-06-01-preview/AgriService_Update_MaximumSet_Gen.json +func ExampleAgriServiceClient_BeginUpdate() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armagricultureplatform.NewClientFactory("83D293F5-DEFD-4D48-B120-1DC713BE338A", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + poller, err := clientFactory.NewAgriServiceClient().BeginUpdate(ctx, "rgopenapi", "abc123", armagricultureplatform.AgriServiceResourceUpdate{ + Identity: &armagricultureplatform.ManagedServiceIdentity{ + Type: to.Ptr(armagricultureplatform.ManagedServiceIdentityTypeNone), + UserAssignedIdentities: map[string]*armagricultureplatform.UserAssignedIdentity{ + "key4771": {}, + }, + }, + SKU: &armagricultureplatform.SKU{ + Name: to.Ptr("tbdtdfffkar"), + Tier: to.Ptr(armagricultureplatform.SKUTierFree), + Size: to.Ptr("iusaqqj"), + Family: to.Ptr("hxojswlgs"), + Capacity: to.Ptr[int32](22), + }, + Tags: map[string]*string{ + "key9006": to.Ptr("kuzlwpujbql"), + }, + Properties: &armagricultureplatform.AgriServiceResourceUpdateProperties{ + Config: &armagricultureplatform.AgriServiceConfig{}, + DataConnectorCredentials: []*armagricultureplatform.DataConnectorCredentialMap{ + { + Key: to.Ptr("BackendAADApplicationCredentials"), + Value: &armagricultureplatform.DataConnectorCredentials{ + ClientID: to.Ptr("dce298a8-1eec-481a-a8f9-a3cd5a8257b2"), + }, + }, + }, + InstalledSolutions: []*armagricultureplatform.InstalledSolutionMap{ + { + Key: to.Ptr("bayerAgPowered.cwum"), + Value: &armagricultureplatform.Solution{ + ApplicationName: to.Ptr("bayerAgPowered.cwum"), + }, + }, + }, + }, + }, nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + res, err := poller.PollUntilDone(ctx, nil) + if err != nil { + log.Fatalf("failed to pull the result: %v", err) + } + // You could use response here. We use blank identifier for just demo purposes. + _ = res + // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // res = armagricultureplatform.AgriServiceClientUpdateResponse{ + // AgriServiceResource: &armagricultureplatform.AgriServiceResource{ + // Properties: &armagricultureplatform.AgriServiceResourceProperties{ + // ProvisioningState: to.Ptr(armagricultureplatform.ProvisioningStateSucceeded), + // Config: &armagricultureplatform.AgriServiceConfig{ + // InstanceURI: to.Ptr("zwjvrpcyzxrsizerkzhwkergjrmxqe"), + // Version: to.Ptr("cwhczenyyxtmslccbv"), + // AppServiceResourceID: to.Ptr("icecbrltkdsresejoidqvlybwsbomotnbnmfa"), + // CosmosDbResourceID: to.Ptr("ygzwcdwitjqshybczyukwhaxkomgimvqdmqsdsx"), + // StorageAccountResourceID: to.Ptr("vdruhddgygpkcwngnvbstyitkzocrwnidpeowekohvisiprcmjzpe"), + // KeyVaultResourceID: to.Ptr("egw"), + // RedisCacheResourceID: to.Ptr("fxhznzcilbmqilgnryyazmhkssbhk"), + // }, + // ManagedOnBehalfOfConfiguration: &armagricultureplatform.ManagedOnBehalfOfConfiguration{ + // MoboBrokerResources: []*armagricultureplatform.MoboBrokerResource{ + // { + // ID: to.Ptr("bnthrkwfkfeorrzvtdxbfz"), + // }, + // }, + // }, + // DataConnectorCredentials: []*armagricultureplatform.DataConnectorCredentialMap{ + // { + // Key: to.Ptr("BackendAADApplicationCredentials"), + // Value: &armagricultureplatform.DataConnectorCredentials{ + // ClientID: to.Ptr("dce298a8-1eec-481a-a8f9-a3cd5a8257b2"), + // }, + // }, + // }, + // InstalledSolutions: []*armagricultureplatform.InstalledSolutionMap{ + // { + // Key: to.Ptr("bayerAgPowered.cwum"), + // Value: &armagricultureplatform.Solution{ + // ApplicationName: to.Ptr("bayerAgPowered.cwum"), + // }, + // }, + // }, + // }, + // Identity: &armagricultureplatform.ManagedServiceIdentity{ + // PrincipalID: to.Ptr("16763be4-6022-406e-a950-fcd5018633ca"), + // TenantID: to.Ptr("16763be4-6022-406e-a950-fcd5018633ca"), + // Type: to.Ptr(armagricultureplatform.ManagedServiceIdentityTypeNone), + // UserAssignedIdentities: map[string]*armagricultureplatform.UserAssignedIdentity{ + // "key4955": &armagricultureplatform.UserAssignedIdentity{ + // PrincipalID: to.Ptr("16763be4-6022-406e-a950-fcd5018633ca"), + // ClientID: to.Ptr("16763be4-6022-406e-a950-fcd5018633ca"), + // }, + // }, + // }, + // SKU: &armagricultureplatform.SKU{ + // Name: to.Ptr("kfl"), + // Tier: to.Ptr(armagricultureplatform.SKUTierFree), + // Size: to.Ptr("r"), + // Family: to.Ptr("xerdhxyjwrypvxphavgrtjphtohf"), + // Capacity: to.Ptr[int32](20), + // }, + // Tags: map[string]*string{ + // "key137": to.Ptr("oxwansfetzzgdwl"), + // }, + // Location: to.Ptr("pkneuknooprpqirnugzwbkiie"), + // ID: to.Ptr("/subscriptions/E1D6D0B0-6FE4-45D5-9C3F-50F4D1AF2F39/resourceGroups/rgopenapi/providers/Microsoft.AgriculturePlatform/agriServices/TKXbP-22-NGGH-1Eh55xGX"), + // Name: to.Ptr("mnvxvlitiwbndijhbmgiejz"), + // Type: to.Ptr("fvvidjmentwsi"), + // SystemData: &armagricultureplatform.SystemData{ + // CreatedBy: to.Ptr("gthxegufst"), + // CreatedByType: to.Ptr(armagricultureplatform.CreatedByTypeUser), + // CreatedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2024-12-16T11:47:57.784Z"); return t}()), + // LastModifiedBy: to.Ptr("ovgqctuakdgemocstvwqmhyufe"), + // LastModifiedByType: to.Ptr(armagricultureplatform.CreatedByTypeUser), + // LastModifiedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2024-12-16T11:47:57.784Z"); return t}()), + // }, + // }, + // } +} diff --git a/sdk/resourcemanager/agricultureplatform/armagricultureplatform/ci.yml b/sdk/resourcemanager/agricultureplatform/armagricultureplatform/ci.yml new file mode 100644 index 000000000000..a3768a147ebe --- /dev/null +++ b/sdk/resourcemanager/agricultureplatform/armagricultureplatform/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/agricultureplatform/armagricultureplatform/ + +pr: + branches: + include: + - main + - feature/* + - hotfix/* + - release/* + paths: + include: + - sdk/resourcemanager/agricultureplatform/armagricultureplatform/ + +extends: + template: /eng/pipelines/templates/jobs/archetype-sdk-client.yml + parameters: + ServiceDirectory: 'resourcemanager/agricultureplatform/armagricultureplatform' diff --git a/sdk/resourcemanager/agricultureplatform/armagricultureplatform/client_factory.go b/sdk/resourcemanager/agricultureplatform/armagricultureplatform/client_factory.go new file mode 100644 index 000000000000..fc4d5938554a --- /dev/null +++ b/sdk/resourcemanager/agricultureplatform/armagricultureplatform/client_factory.go @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armagricultureplatform + +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 +} + +// NewAgriServiceClient creates a new instance of AgriServiceClient. +func (c *ClientFactory) NewAgriServiceClient() *AgriServiceClient { + return &AgriServiceClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewOperationsClient creates a new instance of OperationsClient. +func (c *ClientFactory) NewOperationsClient() *OperationsClient { + return &OperationsClient{ + internal: c.internal, + } +} diff --git a/sdk/resourcemanager/agricultureplatform/armagricultureplatform/constants.go b/sdk/resourcemanager/agricultureplatform/armagricultureplatform/constants.go new file mode 100644 index 000000000000..d653565928a4 --- /dev/null +++ b/sdk/resourcemanager/agricultureplatform/armagricultureplatform/constants.go @@ -0,0 +1,171 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armagricultureplatform + +const ( + moduleName = "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/agricultureplatform/armagricultureplatform" + moduleVersion = "v0.1.0" +) + +// ActionType - Extensible enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. +type ActionType string + +const ( + // ActionTypeInternal - Actions are for internal-only APIs. + ActionTypeInternal ActionType = "Internal" +) + +// PossibleActionTypeValues returns the possible values for the ActionType const type. +func PossibleActionTypeValues() []ActionType { + return []ActionType{ + ActionTypeInternal, + } +} + +// AuthCredentialsKind - Types of different kind of Data connector auth credentials supported. +type AuthCredentialsKind string + +const ( + // AuthCredentialsKindAPIKeyAuthCredentials - API Key Auth Credential type + AuthCredentialsKindAPIKeyAuthCredentials AuthCredentialsKind = "ApiKeyAuthCredentials" + // AuthCredentialsKindOAuthClientCredentials - OAuth Client Credential type + AuthCredentialsKindOAuthClientCredentials AuthCredentialsKind = "OAuthClientCredentials" +) + +// PossibleAuthCredentialsKindValues returns the possible values for the AuthCredentialsKind const type. +func PossibleAuthCredentialsKindValues() []AuthCredentialsKind { + return []AuthCredentialsKind{ + AuthCredentialsKindAPIKeyAuthCredentials, + AuthCredentialsKindOAuthClientCredentials, + } +} + +// CreatedByType - The kind of entity that created the resource. +type CreatedByType string + +const ( + // CreatedByTypeApplication - The entity was created by an application. + CreatedByTypeApplication CreatedByType = "Application" + // CreatedByTypeKey - The entity was created by a key. + CreatedByTypeKey CreatedByType = "Key" + // CreatedByTypeManagedIdentity - The entity was created by a managed identity. + CreatedByTypeManagedIdentity CreatedByType = "ManagedIdentity" + // CreatedByTypeUser - The entity was created by a user. + CreatedByTypeUser CreatedByType = "User" +) + +// PossibleCreatedByTypeValues returns the possible values for the CreatedByType const type. +func PossibleCreatedByTypeValues() []CreatedByType { + return []CreatedByType{ + CreatedByTypeApplication, + CreatedByTypeKey, + CreatedByTypeManagedIdentity, + CreatedByTypeUser, + } +} + +// ManagedServiceIdentityType - Type of managed service identity (where both SystemAssigned and UserAssigned types are allowed). +type ManagedServiceIdentityType string + +const ( + // ManagedServiceIdentityTypeNone - No managed identity. + ManagedServiceIdentityTypeNone ManagedServiceIdentityType = "None" + // ManagedServiceIdentityTypeSystemAssigned - System assigned managed identity. + ManagedServiceIdentityTypeSystemAssigned ManagedServiceIdentityType = "SystemAssigned" + // ManagedServiceIdentityTypeSystemAssignedUserAssigned - System and user assigned managed identity. + ManagedServiceIdentityTypeSystemAssignedUserAssigned ManagedServiceIdentityType = "SystemAssigned,UserAssigned" + // ManagedServiceIdentityTypeUserAssigned - User assigned managed identity. + ManagedServiceIdentityTypeUserAssigned ManagedServiceIdentityType = "UserAssigned" +) + +// PossibleManagedServiceIdentityTypeValues returns the possible values for the ManagedServiceIdentityType const type. +func PossibleManagedServiceIdentityTypeValues() []ManagedServiceIdentityType { + return []ManagedServiceIdentityType{ + ManagedServiceIdentityTypeNone, + ManagedServiceIdentityTypeSystemAssigned, + ManagedServiceIdentityTypeSystemAssignedUserAssigned, + ManagedServiceIdentityTypeUserAssigned, + } +} + +// 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 - Indicates the operation is initiated by a system. + OriginSystem Origin = "system" + // OriginUser - Indicates the operation is initiated by a user. + OriginUser Origin = "user" + // OriginUserSystem - Indicates the operation is initiated by a user or system. + OriginUserSystem Origin = "user,system" +) + +// PossibleOriginValues returns the possible values for the Origin const type. +func PossibleOriginValues() []Origin { + return []Origin{ + OriginSystem, + OriginUser, + OriginUserSystem, + } +} + +// ProvisioningState - The status of the current operation. +type ProvisioningState string + +const ( + // ProvisioningStateAccepted - The resource create request has been accepted + ProvisioningStateAccepted ProvisioningState = "Accepted" + // ProvisioningStateCanceled - Resource creation was canceled. + ProvisioningStateCanceled ProvisioningState = "Canceled" + // ProvisioningStateDeleting - The resource is being deleted + ProvisioningStateDeleting ProvisioningState = "Deleting" + // ProvisioningStateFailed - Resource creation failed. + ProvisioningStateFailed ProvisioningState = "Failed" + // ProvisioningStateProvisioning - The resource is being provisioned + ProvisioningStateProvisioning ProvisioningState = "Provisioning" + // ProvisioningStateSucceeded - Resource has been created. + ProvisioningStateSucceeded ProvisioningState = "Succeeded" + // ProvisioningStateUpdating - The resource is updating + ProvisioningStateUpdating ProvisioningState = "Updating" +) + +// PossibleProvisioningStateValues returns the possible values for the ProvisioningState const type. +func PossibleProvisioningStateValues() []ProvisioningState { + return []ProvisioningState{ + ProvisioningStateAccepted, + ProvisioningStateCanceled, + ProvisioningStateDeleting, + ProvisioningStateFailed, + ProvisioningStateProvisioning, + ProvisioningStateSucceeded, + ProvisioningStateUpdating, + } +} + +// SKUTier - This field is required to be implemented by the Resource Provider if the service has more than one tier, but +// is not required on a PUT. +type SKUTier string + +const ( + // SKUTierBasic - The Basic service tier. + SKUTierBasic SKUTier = "Basic" + // SKUTierFree - The Free service tier. + SKUTierFree SKUTier = "Free" + // SKUTierPremium - The Premium service tier. + SKUTierPremium SKUTier = "Premium" + // SKUTierStandard - The Standard service tier. + SKUTierStandard SKUTier = "Standard" +) + +// PossibleSKUTierValues returns the possible values for the SKUTier const type. +func PossibleSKUTierValues() []SKUTier { + return []SKUTier{ + SKUTierBasic, + SKUTierFree, + SKUTierPremium, + SKUTierStandard, + } +} diff --git a/sdk/resourcemanager/agricultureplatform/armagricultureplatform/fake/agriservice_server.go b/sdk/resourcemanager/agricultureplatform/armagricultureplatform/fake/agriservice_server.go new file mode 100644 index 000000000000..39e51defd4e2 --- /dev/null +++ b/sdk/resourcemanager/agricultureplatform/armagricultureplatform/fake/agriservice_server.go @@ -0,0 +1,413 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/agricultureplatform/armagricultureplatform" + "net/http" + "net/url" + "regexp" +) + +// AgriServiceServer is a fake server for instances of the armagricultureplatform.AgriServiceClient type. +type AgriServiceServer struct { + // BeginCreateOrUpdate is the fake for method AgriServiceClient.BeginCreateOrUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + BeginCreateOrUpdate func(ctx context.Context, resourceGroupName string, agriServiceResourceName string, resource armagricultureplatform.AgriServiceResource, options *armagricultureplatform.AgriServiceClientBeginCreateOrUpdateOptions) (resp azfake.PollerResponder[armagricultureplatform.AgriServiceClientCreateOrUpdateResponse], errResp azfake.ErrorResponder) + + // BeginDelete is the fake for method AgriServiceClient.BeginDelete + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent + BeginDelete func(ctx context.Context, resourceGroupName string, agriServiceResourceName string, options *armagricultureplatform.AgriServiceClientBeginDeleteOptions) (resp azfake.PollerResponder[armagricultureplatform.AgriServiceClientDeleteResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method AgriServiceClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceGroupName string, agriServiceResourceName string, options *armagricultureplatform.AgriServiceClientGetOptions) (resp azfake.Responder[armagricultureplatform.AgriServiceClientGetResponse], errResp azfake.ErrorResponder) + + // ListAvailableSolutions is the fake for method AgriServiceClient.ListAvailableSolutions + // HTTP status codes to indicate success: http.StatusOK + ListAvailableSolutions func(ctx context.Context, resourceGroupName string, agriServiceResourceName string, options *armagricultureplatform.AgriServiceClientListAvailableSolutionsOptions) (resp azfake.Responder[armagricultureplatform.AgriServiceClientListAvailableSolutionsResponse], errResp azfake.ErrorResponder) + + // NewListByResourceGroupPager is the fake for method AgriServiceClient.NewListByResourceGroupPager + // HTTP status codes to indicate success: http.StatusOK + NewListByResourceGroupPager func(resourceGroupName string, options *armagricultureplatform.AgriServiceClientListByResourceGroupOptions) (resp azfake.PagerResponder[armagricultureplatform.AgriServiceClientListByResourceGroupResponse]) + + // NewListBySubscriptionPager is the fake for method AgriServiceClient.NewListBySubscriptionPager + // HTTP status codes to indicate success: http.StatusOK + NewListBySubscriptionPager func(options *armagricultureplatform.AgriServiceClientListBySubscriptionOptions) (resp azfake.PagerResponder[armagricultureplatform.AgriServiceClientListBySubscriptionResponse]) + + // BeginUpdate is the fake for method AgriServiceClient.BeginUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted + BeginUpdate func(ctx context.Context, resourceGroupName string, agriServiceResourceName string, properties armagricultureplatform.AgriServiceResourceUpdate, options *armagricultureplatform.AgriServiceClientBeginUpdateOptions) (resp azfake.PollerResponder[armagricultureplatform.AgriServiceClientUpdateResponse], errResp azfake.ErrorResponder) +} + +// NewAgriServiceServerTransport creates a new instance of AgriServiceServerTransport with the provided implementation. +// The returned AgriServiceServerTransport instance is connected to an instance of armagricultureplatform.AgriServiceClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewAgriServiceServerTransport(srv *AgriServiceServer) *AgriServiceServerTransport { + return &AgriServiceServerTransport{ + srv: srv, + beginCreateOrUpdate: newTracker[azfake.PollerResponder[armagricultureplatform.AgriServiceClientCreateOrUpdateResponse]](), + beginDelete: newTracker[azfake.PollerResponder[armagricultureplatform.AgriServiceClientDeleteResponse]](), + newListByResourceGroupPager: newTracker[azfake.PagerResponder[armagricultureplatform.AgriServiceClientListByResourceGroupResponse]](), + newListBySubscriptionPager: newTracker[azfake.PagerResponder[armagricultureplatform.AgriServiceClientListBySubscriptionResponse]](), + beginUpdate: newTracker[azfake.PollerResponder[armagricultureplatform.AgriServiceClientUpdateResponse]](), + } +} + +// AgriServiceServerTransport connects instances of armagricultureplatform.AgriServiceClient to instances of AgriServiceServer. +// Don't use this type directly, use NewAgriServiceServerTransport instead. +type AgriServiceServerTransport struct { + srv *AgriServiceServer + beginCreateOrUpdate *tracker[azfake.PollerResponder[armagricultureplatform.AgriServiceClientCreateOrUpdateResponse]] + beginDelete *tracker[azfake.PollerResponder[armagricultureplatform.AgriServiceClientDeleteResponse]] + newListByResourceGroupPager *tracker[azfake.PagerResponder[armagricultureplatform.AgriServiceClientListByResourceGroupResponse]] + newListBySubscriptionPager *tracker[azfake.PagerResponder[armagricultureplatform.AgriServiceClientListBySubscriptionResponse]] + beginUpdate *tracker[azfake.PollerResponder[armagricultureplatform.AgriServiceClientUpdateResponse]] +} + +// Do implements the policy.Transporter interface for AgriServiceServerTransport. +func (a *AgriServiceServerTransport) 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 *AgriServiceServerTransport) 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 agriServiceServerTransportInterceptor != nil { + res.resp, res.err, intercepted = agriServiceServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "AgriServiceClient.BeginCreateOrUpdate": + res.resp, res.err = a.dispatchBeginCreateOrUpdate(req) + case "AgriServiceClient.BeginDelete": + res.resp, res.err = a.dispatchBeginDelete(req) + case "AgriServiceClient.Get": + res.resp, res.err = a.dispatchGet(req) + case "AgriServiceClient.ListAvailableSolutions": + res.resp, res.err = a.dispatchListAvailableSolutions(req) + case "AgriServiceClient.NewListByResourceGroupPager": + res.resp, res.err = a.dispatchNewListByResourceGroupPager(req) + case "AgriServiceClient.NewListBySubscriptionPager": + res.resp, res.err = a.dispatchNewListBySubscriptionPager(req) + case "AgriServiceClient.BeginUpdate": + res.resp, res.err = a.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 (a *AgriServiceServerTransport) dispatchBeginCreateOrUpdate(req *http.Request) (*http.Response, error) { + if a.srv.BeginCreateOrUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginCreateOrUpdate not implemented")} + } + beginCreateOrUpdate := a.beginCreateOrUpdate.get(req) + if beginCreateOrUpdate == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.AgriculturePlatform/agriServices/(?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[armagricultureplatform.AgriServiceResource](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + agriServiceResourceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("agriServiceResourceName")]) + if err != nil { + return nil, err + } + respr, errRespr := a.srv.BeginCreateOrUpdate(req.Context(), resourceGroupNameParam, agriServiceResourceNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginCreateOrUpdate = &respr + a.beginCreateOrUpdate.add(req, beginCreateOrUpdate) + } + + resp, err := server.PollerResponderNext(beginCreateOrUpdate, req) + if err != nil { + return nil, err + } + + if !contains([]int{http.StatusOK, http.StatusCreated}, resp.StatusCode) { + a.beginCreateOrUpdate.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", resp.StatusCode)} + } + if !server.PollerResponderMore(beginCreateOrUpdate) { + a.beginCreateOrUpdate.remove(req) + } + + return resp, nil +} + +func (a *AgriServiceServerTransport) dispatchBeginDelete(req *http.Request) (*http.Response, error) { + if a.srv.BeginDelete == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginDelete not implemented")} + } + beginDelete := a.beginDelete.get(req) + if beginDelete == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.AgriculturePlatform/agriServices/(?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 + } + agriServiceResourceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("agriServiceResourceName")]) + if err != nil { + return nil, err + } + respr, errRespr := a.srv.BeginDelete(req.Context(), resourceGroupNameParam, agriServiceResourceNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginDelete = &respr + a.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) { + a.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) { + a.beginDelete.remove(req) + } + + return resp, nil +} + +func (a *AgriServiceServerTransport) 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\.AgriculturePlatform/agriServices/(?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 + } + agriServiceResourceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("agriServiceResourceName")]) + if err != nil { + return nil, err + } + respr, errRespr := a.srv.Get(req.Context(), resourceGroupNameParam, agriServiceResourceNameParam, 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).AgriServiceResource, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (a *AgriServiceServerTransport) dispatchListAvailableSolutions(req *http.Request) (*http.Response, error) { + if a.srv.ListAvailableSolutions == nil { + return nil, &nonRetriableError{errors.New("fake for method ListAvailableSolutions not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.AgriculturePlatform/agriServices/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/listAvailableSolutions` + 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 + } + agriServiceResourceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("agriServiceResourceName")]) + if err != nil { + return nil, err + } + respr, errRespr := a.srv.ListAvailableSolutions(req.Context(), resourceGroupNameParam, agriServiceResourceNameParam, 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).AvailableAgriSolutionListResult, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (a *AgriServiceServerTransport) dispatchNewListByResourceGroupPager(req *http.Request) (*http.Response, error) { + if a.srv.NewListByResourceGroupPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListByResourceGroupPager not implemented")} + } + newListByResourceGroupPager := a.newListByResourceGroupPager.get(req) + if newListByResourceGroupPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.AgriculturePlatform/agriServices` + 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 := a.srv.NewListByResourceGroupPager(resourceGroupNameParam, nil) + newListByResourceGroupPager = &resp + a.newListByResourceGroupPager.add(req, newListByResourceGroupPager) + server.PagerResponderInjectNextLinks(newListByResourceGroupPager, req, func(page *armagricultureplatform.AgriServiceClientListByResourceGroupResponse, 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) { + a.newListByResourceGroupPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListByResourceGroupPager) { + a.newListByResourceGroupPager.remove(req) + } + return resp, nil +} + +func (a *AgriServiceServerTransport) dispatchNewListBySubscriptionPager(req *http.Request) (*http.Response, error) { + if a.srv.NewListBySubscriptionPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListBySubscriptionPager not implemented")} + } + newListBySubscriptionPager := a.newListBySubscriptionPager.get(req) + if newListBySubscriptionPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.AgriculturePlatform/agriServices` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if matches == nil || len(matches) < 1 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resp := a.srv.NewListBySubscriptionPager(nil) + newListBySubscriptionPager = &resp + a.newListBySubscriptionPager.add(req, newListBySubscriptionPager) + server.PagerResponderInjectNextLinks(newListBySubscriptionPager, req, func(page *armagricultureplatform.AgriServiceClientListBySubscriptionResponse, 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) { + a.newListBySubscriptionPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListBySubscriptionPager) { + a.newListBySubscriptionPager.remove(req) + } + return resp, nil +} + +func (a *AgriServiceServerTransport) dispatchBeginUpdate(req *http.Request) (*http.Response, error) { + if a.srv.BeginUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginUpdate not implemented")} + } + beginUpdate := a.beginUpdate.get(req) + if beginUpdate == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.AgriculturePlatform/agriServices/(?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[armagricultureplatform.AgriServiceResourceUpdate](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + agriServiceResourceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("agriServiceResourceName")]) + if err != nil { + return nil, err + } + respr, errRespr := a.srv.BeginUpdate(req.Context(), resourceGroupNameParam, agriServiceResourceNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginUpdate = &respr + a.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) { + a.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) { + a.beginUpdate.remove(req) + } + + return resp, nil +} + +// set this to conditionally intercept incoming requests to AgriServiceServerTransport +var agriServiceServerTransportInterceptor 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/agricultureplatform/armagricultureplatform/fake/internal.go b/sdk/resourcemanager/agricultureplatform/armagricultureplatform/fake/internal.go new file mode 100644 index 000000000000..7425b6a669e2 --- /dev/null +++ b/sdk/resourcemanager/agricultureplatform/armagricultureplatform/fake/internal.go @@ -0,0 +1,65 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "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 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/agricultureplatform/armagricultureplatform/fake/operations_server.go b/sdk/resourcemanager/agricultureplatform/armagricultureplatform/fake/operations_server.go new file mode 100644 index 000000000000..e48ead23e155 --- /dev/null +++ b/sdk/resourcemanager/agricultureplatform/armagricultureplatform/fake/operations_server.go @@ -0,0 +1,117 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/agricultureplatform/armagricultureplatform" + "net/http" +) + +// OperationsServer is a fake server for instances of the armagricultureplatform.OperationsClient type. +type OperationsServer struct { + // NewListPager is the fake for method OperationsClient.NewListPager + // HTTP status codes to indicate success: http.StatusOK + NewListPager func(options *armagricultureplatform.OperationsClientListOptions) (resp azfake.PagerResponder[armagricultureplatform.OperationsClientListResponse]) +} + +// NewOperationsServerTransport creates a new instance of OperationsServerTransport with the provided implementation. +// The returned OperationsServerTransport instance is connected to an instance of armagricultureplatform.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[armagricultureplatform.OperationsClientListResponse]](), + } +} + +// OperationsServerTransport connects instances of armagricultureplatform.OperationsClient to instances of OperationsServer. +// Don't use this type directly, use NewOperationsServerTransport instead. +type OperationsServerTransport struct { + srv *OperationsServer + newListPager *tracker[azfake.PagerResponder[armagricultureplatform.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 *armagricultureplatform.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/agricultureplatform/armagricultureplatform/fake/server_factory.go b/sdk/resourcemanager/agricultureplatform/armagricultureplatform/fake/server_factory.go new file mode 100644 index 000000000000..cd51757cb195 --- /dev/null +++ b/sdk/resourcemanager/agricultureplatform/armagricultureplatform/fake/server_factory.go @@ -0,0 +1,79 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "errors" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" + "sync" +) + +// ServerFactory is a fake server for instances of the armagricultureplatform.ClientFactory type. +type ServerFactory struct { + // AgriServiceServer contains the fakes for client AgriServiceClient + AgriServiceServer AgriServiceServer + + // OperationsServer contains the fakes for client OperationsClient + OperationsServer OperationsServer +} + +// NewServerFactoryTransport creates a new instance of ServerFactoryTransport with the provided implementation. +// The returned ServerFactoryTransport instance is connected to an instance of armagricultureplatform.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 armagricultureplatform.ClientFactory to instances of ServerFactory. +// Don't use this type directly, use NewServerFactoryTransport instead. +type ServerFactoryTransport struct { + srv *ServerFactory + trMu sync.Mutex + trAgriServiceServer *AgriServiceServerTransport + trOperationsServer *OperationsServerTransport +} + +// 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 "AgriServiceClient": + initServer(s, &s.trAgriServiceServer, func() *AgriServiceServerTransport { return NewAgriServiceServerTransport(&s.srv.AgriServiceServer) }) + resp, err = s.trAgriServiceServer.Do(req) + case "OperationsClient": + initServer(s, &s.trOperationsServer, func() *OperationsServerTransport { return NewOperationsServerTransport(&s.srv.OperationsServer) }) + resp, err = s.trOperationsServer.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/agricultureplatform/armagricultureplatform/fake/time_rfc3339.go b/sdk/resourcemanager/agricultureplatform/armagricultureplatform/fake/time_rfc3339.go new file mode 100644 index 000000000000..87ee11e83b32 --- /dev/null +++ b/sdk/resourcemanager/agricultureplatform/armagricultureplatform/fake/time_rfc3339.go @@ -0,0 +1,109 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "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 +} diff --git a/sdk/resourcemanager/agricultureplatform/armagricultureplatform/go.mod b/sdk/resourcemanager/agricultureplatform/armagricultureplatform/go.mod new file mode 100644 index 000000000000..3893dcf227b8 --- /dev/null +++ b/sdk/resourcemanager/agricultureplatform/armagricultureplatform/go.mod @@ -0,0 +1,23 @@ +module github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/agricultureplatform/armagricultureplatform + +go 1.23.0 + +toolchain go1.23.8 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.17.1 + github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.7.0 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.10.0 // indirect + github.com/AzureAD/microsoft-authentication-library-for-go v1.2.2 // indirect + github.com/golang-jwt/jwt/v5 v5.2.1 // indirect + github.com/google/uuid v1.6.0 // indirect + github.com/kylelemons/godebug v1.1.0 // indirect + github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c // indirect + golang.org/x/crypto v0.36.0 // indirect + golang.org/x/net v0.37.0 // indirect + golang.org/x/sys v0.31.0 // indirect + golang.org/x/text v0.23.0 // indirect +) diff --git a/sdk/resourcemanager/agricultureplatform/armagricultureplatform/go.sum b/sdk/resourcemanager/agricultureplatform/armagricultureplatform/go.sum new file mode 100644 index 000000000000..1f92486fbbcf --- /dev/null +++ b/sdk/resourcemanager/agricultureplatform/armagricultureplatform/go.sum @@ -0,0 +1,33 @@ +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/azidentity v1.7.0 h1:tfLQ34V6F7tVSwoTf/4lH5sE0o6eCJuNDTmH09nDpbc= +github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.7.0/go.mod h1:9kIvujWAA58nmPmWB1m23fyWic1kYZMxD9CxaWn4Qpg= +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/AzureAD/microsoft-authentication-library-for-go v1.2.2 h1:XHOnouVk1mxXfQidrMEnLlPk9UMeRtyBTnEFtxkV0kU= +github.com/AzureAD/microsoft-authentication-library-for-go v1.2.2/go.mod h1:wP83P5OoQ5p6ip3ScPr0BAq0BvuPAvacpEuSzyouqAI= +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/golang-jwt/jwt/v5 v5.2.1 h1:OuVbFODueb089Lh128TAcimifWaLhJwVflnrgM17wHk= +github.com/golang-jwt/jwt/v5 v5.2.1/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk= +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc= +github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= +github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c h1:+mdjkGKdHQG3305AYmdv1U2eRNDiU2ErMBj1gwrq8eQ= +github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c/go.mod h1:7rwL4CYBLnjLxUqIJNnCWiEdr3bn6IUYi15bNlnbCCU= +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/crypto v0.36.0 h1:AnAEvhDddvBdpY+uR+MyHmuZzzNqXSe/GvuDeob5L34= +golang.org/x/crypto v0.36.0/go.mod h1:Y4J0ReaxCR1IMaabaSMugxJES1EpwhBHhv2bDHklZvc= +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/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.31.0 h1:ioabZlmFYtWhL+TRYpcnNlLwhyxaM9kWTDEmfnprqik= +golang.org/x/sys v0.31.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= +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/agricultureplatform/armagricultureplatform/models.go b/sdk/resourcemanager/agricultureplatform/armagricultureplatform/models.go new file mode 100644 index 000000000000..6c20aeaa10b4 --- /dev/null +++ b/sdk/resourcemanager/agricultureplatform/armagricultureplatform/models.go @@ -0,0 +1,345 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armagricultureplatform + +import "time" + +// AgriServiceConfig - Config of the AgriService resource instance. +type AgriServiceConfig struct { + // READ-ONLY; App service resource Id. + AppServiceResourceID *string + + // READ-ONLY; Cosmos Db resource Id. + CosmosDbResourceID *string + + // READ-ONLY; Instance URI of the AgriService instance. + InstanceURI *string + + // READ-ONLY; Key vault resource Id. + KeyVaultResourceID *string + + // READ-ONLY; Redis cache resource Id. + RedisCacheResourceID *string + + // READ-ONLY; Storage account resource Id. + StorageAccountResourceID *string + + // READ-ONLY; Version of AgriService instance. + Version *string +} + +// AgriServiceResource - Schema of the AgriService resource from Microsoft.AgriculturePlatform resource provider. +type AgriServiceResource struct { + // REQUIRED; The geo-location where the resource lives + Location *string + + // READ-ONLY; The name of the AgriService resource. + Name *string + + // The managed service identities assigned to this resource. + Identity *ManagedServiceIdentity + + // The resource-specific properties for this resource. + Properties *AgriServiceResourceProperties + + // The SKU (Stock Keeping Unit) assigned to this resource. + SKU *SKU + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; 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 +} + +// AgriServiceResourceListResult - The response of a AgriServiceResource list operation. +type AgriServiceResourceListResult struct { + // REQUIRED; The AgriServiceResource items on this page + Value []*AgriServiceResource + + // The link to the next page of items + NextLink *string +} + +// AgriServiceResourceProperties - Details of the Agriculture AgriDataManager. +type AgriServiceResourceProperties struct { + // Config of the AgriService instance. + Config *AgriServiceConfig + + // Data connector credentials of AgriService instance. + DataConnectorCredentials []*DataConnectorCredentialMap + + // AgriService installed solutions. + InstalledSolutions []*InstalledSolutionMap + + // READ-ONLY; Managed On Behalf Of Configuration. + ManagedOnBehalfOfConfiguration *ManagedOnBehalfOfConfiguration + + // READ-ONLY; The status of the last operation. + ProvisioningState *ProvisioningState +} + +// AgriServiceResourceUpdate - The type used for update operations of the AgriServiceResource. +type AgriServiceResourceUpdate struct { + // The managed service identities assigned to this resource. + Identity *ManagedServiceIdentity + + // The resource-specific properties for this resource. + Properties *AgriServiceResourceUpdateProperties + + // The SKU (Stock Keeping Unit) assigned to this resource. + SKU *SKU + + // Resource tags. + Tags map[string]*string +} + +// AgriServiceResourceUpdateProperties - The updatable properties of the AgriServiceResource. +type AgriServiceResourceUpdateProperties struct { + // Config of the AgriService instance. + Config *AgriServiceConfig + + // Data connector credentials of AgriService instance. + DataConnectorCredentials []*DataConnectorCredentialMap + + // AgriService installed solutions. + InstalledSolutions []*InstalledSolutionMap +} + +// AvailableAgriSolutionListResult - The list of available agri solutions. +type AvailableAgriSolutionListResult struct { + // REQUIRED; Agri solutions list. + Solutions []*DataManagerForAgricultureSolution +} + +// DataConnectorCredentialMap - Mapping of data connector credentials. +type DataConnectorCredentialMap struct { + // REQUIRED; The key representing the credential. + Key *string + + // REQUIRED; The data connector credential value. + Value *DataConnectorCredentials +} + +// DataConnectorCredentials - The properties related to an AgriService data connector. +type DataConnectorCredentials struct { + // Client Id associated with the provider, if type of credentials is OAuthClientCredentials. + ClientID *string + + // Name of the key vault key. + KeyName *string + + // Uri of the key vault + KeyVaultURI *string + + // Version of the key vault key. + KeyVersion *string + + // Type of credential. + Kind *AuthCredentialsKind +} + +// DataManagerForAgricultureSolution - Data Manager for Agriculture solution. +type DataManagerForAgricultureSolution struct { + // REQUIRED; Entra application Id used to access azure data manager for agriculture instance. + AccessAzureDataManagerForAgricultureApplicationID *string + + // REQUIRED; Entra application name used to access azure data manager for agriculture instance. + AccessAzureDataManagerForAgricultureApplicationName *string + + // REQUIRED; Data access scopes. + DataAccessScopes []*string + + // REQUIRED; Whether solution inference will validate input. + IsValidateInput *bool + + // REQUIRED; Marketplace offer details. + MarketPlaceOfferDetails *MarketPlaceOfferDetails + + // REQUIRED; Partner Id. + PartnerID *string + + // REQUIRED; Partner tenant Id. + PartnerTenantID *string + + // REQUIRED; Saas application Id. + SaasApplicationID *string + + // REQUIRED; Solution Id. + SolutionID *string +} + +// InstalledSolutionMap - Mapping of installed solutions. +type InstalledSolutionMap struct { + // REQUIRED; The key representing the installed solution. + Key *string + + // REQUIRED; The installed solution value. + Value *Solution +} + +// ManagedOnBehalfOfConfiguration - Configuration of the managed on behalf of resource. +type ManagedOnBehalfOfConfiguration struct { + // READ-ONLY; Associated MoboBrokerResources. + MoboBrokerResources []*MoboBrokerResource +} + +// ManagedServiceIdentity - Managed service identity (system assigned and/or user assigned identities) +type ManagedServiceIdentity struct { + // REQUIRED; The type of managed identity assigned to this resource. + Type *ManagedServiceIdentityType + + // The identities assigned to this resource by the user. + 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 +} + +// MarketPlaceOfferDetails - Marketplace offer details of Agri solution. +type MarketPlaceOfferDetails struct { + // REQUIRED; Publisher Id. + PublisherID *string + + // REQUIRED; Saas offer Id. + SaasOfferID *string +} + +// MoboBrokerResource - MoboBroker resource. +type MoboBrokerResource struct { + // READ-ONLY; The fully qualified resource ID of the MoboBroker resource. + // Example: `/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}` + ID *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; Extensible 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 Azure + // Resource Manager/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 and 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 { + // REQUIRED; The Operation items on this page + Value []*Operation + + // The link to the next page of items + NextLink *string +} + +// SKU - The resource model definition representing SKU +type SKU struct { + // REQUIRED; The name of the SKU. Ex - P3. It is typically a letter+number code + Name *string + + // If the SKU supports scale out/in then the capacity integer should be included. If scale out/in is not possible for the + // resource this may be omitted. + Capacity *int32 + + // If the service has different generations of hardware, for the same SKU, then that can be captured here. + Family *string + + // The SKU size. When the name field is the combination of tier and some other value, this would be the standalone code. + Size *string + + // This field is required to be implemented by the Resource Provider if the service has more than one tier, but is not required + // on a PUT. + Tier *SKUTier +} + +// Solution - Installed data manager for Agriculture solution detail. +type Solution struct { + // Application name of the solution. + ApplicationName *string + + // Marketplace publisher Id. + MarketPlacePublisherID *string + + // Partner Id. + PartnerID *string + + // Plan Id. + PlanID *string + + // Saas subscription Id. + SaasSubscriptionID *string + + // Saas subscription name. + SaasSubscriptionName *string +} + +// 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 +} + +// 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/agricultureplatform/armagricultureplatform/models_serde.go b/sdk/resourcemanager/agricultureplatform/armagricultureplatform/models_serde.go new file mode 100644 index 000000000000..4d559c90cf17 --- /dev/null +++ b/sdk/resourcemanager/agricultureplatform/armagricultureplatform/models_serde.go @@ -0,0 +1,886 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armagricultureplatform + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "reflect" +) + +// MarshalJSON implements the json.Marshaller interface for type AgriServiceConfig. +func (a AgriServiceConfig) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "appServiceResourceId", a.AppServiceResourceID) + populate(objectMap, "cosmosDbResourceId", a.CosmosDbResourceID) + populate(objectMap, "instanceUri", a.InstanceURI) + populate(objectMap, "keyVaultResourceId", a.KeyVaultResourceID) + populate(objectMap, "redisCacheResourceId", a.RedisCacheResourceID) + populate(objectMap, "storageAccountResourceId", a.StorageAccountResourceID) + populate(objectMap, "version", a.Version) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AgriServiceConfig. +func (a *AgriServiceConfig) 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 "appServiceResourceId": + err = unpopulate(val, "AppServiceResourceID", &a.AppServiceResourceID) + delete(rawMsg, key) + case "cosmosDbResourceId": + err = unpopulate(val, "CosmosDbResourceID", &a.CosmosDbResourceID) + delete(rawMsg, key) + case "instanceUri": + err = unpopulate(val, "InstanceURI", &a.InstanceURI) + delete(rawMsg, key) + case "keyVaultResourceId": + err = unpopulate(val, "KeyVaultResourceID", &a.KeyVaultResourceID) + delete(rawMsg, key) + case "redisCacheResourceId": + err = unpopulate(val, "RedisCacheResourceID", &a.RedisCacheResourceID) + delete(rawMsg, key) + case "storageAccountResourceId": + err = unpopulate(val, "StorageAccountResourceID", &a.StorageAccountResourceID) + delete(rawMsg, key) + case "version": + err = unpopulate(val, "Version", &a.Version) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AgriServiceResource. +func (a AgriServiceResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", a.ID) + populate(objectMap, "identity", a.Identity) + populate(objectMap, "location", a.Location) + populate(objectMap, "name", a.Name) + populate(objectMap, "properties", a.Properties) + populate(objectMap, "sku", a.SKU) + populate(objectMap, "systemData", a.SystemData) + populate(objectMap, "tags", a.Tags) + populate(objectMap, "type", a.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AgriServiceResource. +func (a *AgriServiceResource) 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 "identity": + err = unpopulate(val, "Identity", &a.Identity) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &a.Location) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &a.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &a.Properties) + delete(rawMsg, key) + case "sku": + err = unpopulate(val, "SKU", &a.SKU) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &a.SystemData) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &a.Tags) + 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 AgriServiceResourceListResult. +func (a AgriServiceResourceListResult) 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 AgriServiceResourceListResult. +func (a *AgriServiceResourceListResult) 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 AgriServiceResourceProperties. +func (a AgriServiceResourceProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "config", a.Config) + populate(objectMap, "dataConnectorCredentials", a.DataConnectorCredentials) + populate(objectMap, "installedSolutions", a.InstalledSolutions) + populate(objectMap, "managedOnBehalfOfConfiguration", a.ManagedOnBehalfOfConfiguration) + populate(objectMap, "provisioningState", a.ProvisioningState) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AgriServiceResourceProperties. +func (a *AgriServiceResourceProperties) 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 "config": + err = unpopulate(val, "Config", &a.Config) + delete(rawMsg, key) + case "dataConnectorCredentials": + err = unpopulate(val, "DataConnectorCredentials", &a.DataConnectorCredentials) + delete(rawMsg, key) + case "installedSolutions": + err = unpopulate(val, "InstalledSolutions", &a.InstalledSolutions) + delete(rawMsg, key) + case "managedOnBehalfOfConfiguration": + err = unpopulate(val, "ManagedOnBehalfOfConfiguration", &a.ManagedOnBehalfOfConfiguration) + 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 AgriServiceResourceUpdate. +func (a AgriServiceResourceUpdate) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "identity", a.Identity) + populate(objectMap, "properties", a.Properties) + populate(objectMap, "sku", a.SKU) + populate(objectMap, "tags", a.Tags) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AgriServiceResourceUpdate. +func (a *AgriServiceResourceUpdate) 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 "identity": + err = unpopulate(val, "Identity", &a.Identity) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &a.Properties) + delete(rawMsg, key) + case "sku": + err = unpopulate(val, "SKU", &a.SKU) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &a.Tags) + 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 AgriServiceResourceUpdateProperties. +func (a AgriServiceResourceUpdateProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "config", a.Config) + populate(objectMap, "dataConnectorCredentials", a.DataConnectorCredentials) + populate(objectMap, "installedSolutions", a.InstalledSolutions) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AgriServiceResourceUpdateProperties. +func (a *AgriServiceResourceUpdateProperties) 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 "config": + err = unpopulate(val, "Config", &a.Config) + delete(rawMsg, key) + case "dataConnectorCredentials": + err = unpopulate(val, "DataConnectorCredentials", &a.DataConnectorCredentials) + delete(rawMsg, key) + case "installedSolutions": + err = unpopulate(val, "InstalledSolutions", &a.InstalledSolutions) + 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 AvailableAgriSolutionListResult. +func (a AvailableAgriSolutionListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "solutions", a.Solutions) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AvailableAgriSolutionListResult. +func (a *AvailableAgriSolutionListResult) 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 "solutions": + err = unpopulate(val, "Solutions", &a.Solutions) + 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 DataConnectorCredentialMap. +func (d DataConnectorCredentialMap) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "key", d.Key) + populate(objectMap, "value", d.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DataConnectorCredentialMap. +func (d *DataConnectorCredentialMap) 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 "key": + err = unpopulate(val, "Key", &d.Key) + 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 DataConnectorCredentials. +func (d DataConnectorCredentials) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "clientId", d.ClientID) + populate(objectMap, "keyName", d.KeyName) + populate(objectMap, "keyVaultUri", d.KeyVaultURI) + populate(objectMap, "keyVersion", d.KeyVersion) + populate(objectMap, "kind", d.Kind) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DataConnectorCredentials. +func (d *DataConnectorCredentials) 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 "clientId": + err = unpopulate(val, "ClientID", &d.ClientID) + delete(rawMsg, key) + case "keyName": + err = unpopulate(val, "KeyName", &d.KeyName) + delete(rawMsg, key) + case "keyVaultUri": + err = unpopulate(val, "KeyVaultURI", &d.KeyVaultURI) + delete(rawMsg, key) + case "keyVersion": + err = unpopulate(val, "KeyVersion", &d.KeyVersion) + delete(rawMsg, key) + case "kind": + err = unpopulate(val, "Kind", &d.Kind) + 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 DataManagerForAgricultureSolution. +func (d DataManagerForAgricultureSolution) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "accessAzureDataManagerForAgricultureApplicationId", d.AccessAzureDataManagerForAgricultureApplicationID) + populate(objectMap, "accessAzureDataManagerForAgricultureApplicationName", d.AccessAzureDataManagerForAgricultureApplicationName) + populate(objectMap, "dataAccessScopes", d.DataAccessScopes) + populate(objectMap, "isValidateInput", d.IsValidateInput) + populate(objectMap, "marketPlaceOfferDetails", d.MarketPlaceOfferDetails) + populate(objectMap, "partnerId", d.PartnerID) + populate(objectMap, "partnerTenantId", d.PartnerTenantID) + populate(objectMap, "saasApplicationId", d.SaasApplicationID) + populate(objectMap, "solutionId", d.SolutionID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DataManagerForAgricultureSolution. +func (d *DataManagerForAgricultureSolution) 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 "accessAzureDataManagerForAgricultureApplicationId": + err = unpopulate(val, "AccessAzureDataManagerForAgricultureApplicationID", &d.AccessAzureDataManagerForAgricultureApplicationID) + delete(rawMsg, key) + case "accessAzureDataManagerForAgricultureApplicationName": + err = unpopulate(val, "AccessAzureDataManagerForAgricultureApplicationName", &d.AccessAzureDataManagerForAgricultureApplicationName) + delete(rawMsg, key) + case "dataAccessScopes": + err = unpopulate(val, "DataAccessScopes", &d.DataAccessScopes) + delete(rawMsg, key) + case "isValidateInput": + err = unpopulate(val, "IsValidateInput", &d.IsValidateInput) + delete(rawMsg, key) + case "marketPlaceOfferDetails": + err = unpopulate(val, "MarketPlaceOfferDetails", &d.MarketPlaceOfferDetails) + delete(rawMsg, key) + case "partnerId": + err = unpopulate(val, "PartnerID", &d.PartnerID) + delete(rawMsg, key) + case "partnerTenantId": + err = unpopulate(val, "PartnerTenantID", &d.PartnerTenantID) + delete(rawMsg, key) + case "saasApplicationId": + err = unpopulate(val, "SaasApplicationID", &d.SaasApplicationID) + delete(rawMsg, key) + case "solutionId": + err = unpopulate(val, "SolutionID", &d.SolutionID) + 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 InstalledSolutionMap. +func (i InstalledSolutionMap) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "key", i.Key) + populate(objectMap, "value", i.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type InstalledSolutionMap. +func (i *InstalledSolutionMap) 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 "key": + err = unpopulate(val, "Key", &i.Key) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &i.Value) + 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 ManagedOnBehalfOfConfiguration. +func (m ManagedOnBehalfOfConfiguration) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "moboBrokerResources", m.MoboBrokerResources) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ManagedOnBehalfOfConfiguration. +func (m *ManagedOnBehalfOfConfiguration) 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 "moboBrokerResources": + err = unpopulate(val, "MoboBrokerResources", &m.MoboBrokerResources) + 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 MarketPlaceOfferDetails. +func (m MarketPlaceOfferDetails) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "publisherId", m.PublisherID) + populate(objectMap, "saasOfferId", m.SaasOfferID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type MarketPlaceOfferDetails. +func (m *MarketPlaceOfferDetails) 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 "publisherId": + err = unpopulate(val, "PublisherID", &m.PublisherID) + delete(rawMsg, key) + case "saasOfferId": + err = unpopulate(val, "SaasOfferID", &m.SaasOfferID) + 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 MoboBrokerResource. +func (m MoboBrokerResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", m.ID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type MoboBrokerResource. +func (m *MoboBrokerResource) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &m.ID) + delete(rawMsg, key) + } + 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 SKU. +func (s SKU) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "capacity", s.Capacity) + populate(objectMap, "family", s.Family) + populate(objectMap, "name", s.Name) + populate(objectMap, "size", s.Size) + populate(objectMap, "tier", s.Tier) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SKU. +func (s *SKU) 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 "capacity": + err = unpopulate(val, "Capacity", &s.Capacity) + delete(rawMsg, key) + case "family": + err = unpopulate(val, "Family", &s.Family) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &s.Name) + delete(rawMsg, key) + case "size": + err = unpopulate(val, "Size", &s.Size) + delete(rawMsg, key) + case "tier": + err = unpopulate(val, "Tier", &s.Tier) + 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 Solution. +func (s Solution) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "applicationName", s.ApplicationName) + populate(objectMap, "marketPlacePublisherId", s.MarketPlacePublisherID) + populate(objectMap, "partnerId", s.PartnerID) + populate(objectMap, "planId", s.PlanID) + populate(objectMap, "saasSubscriptionId", s.SaasSubscriptionID) + populate(objectMap, "saasSubscriptionName", s.SaasSubscriptionName) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Solution. +func (s *Solution) 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 "applicationName": + err = unpopulate(val, "ApplicationName", &s.ApplicationName) + delete(rawMsg, key) + case "marketPlacePublisherId": + err = unpopulate(val, "MarketPlacePublisherID", &s.MarketPlacePublisherID) + delete(rawMsg, key) + case "partnerId": + err = unpopulate(val, "PartnerID", &s.PartnerID) + delete(rawMsg, key) + case "planId": + err = unpopulate(val, "PlanID", &s.PlanID) + delete(rawMsg, key) + case "saasSubscriptionId": + err = unpopulate(val, "SaasSubscriptionID", &s.SaasSubscriptionID) + delete(rawMsg, key) + case "saasSubscriptionName": + err = unpopulate(val, "SaasSubscriptionName", &s.SaasSubscriptionName) + 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 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/agricultureplatform/armagricultureplatform/operations_client.go b/sdk/resourcemanager/agricultureplatform/armagricultureplatform/operations_client.go new file mode 100644 index 000000000000..c8e0bd56974a --- /dev/null +++ b/sdk/resourcemanager/agricultureplatform/armagricultureplatform/operations_client.go @@ -0,0 +1,84 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armagricultureplatform + +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 2024-06-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.AgriculturePlatform/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", "2024-06-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/agricultureplatform/armagricultureplatform/operations_client_example_test.go b/sdk/resourcemanager/agricultureplatform/armagricultureplatform/operations_client_example_test.go new file mode 100644 index 000000000000..435bc4cb184a --- /dev/null +++ b/sdk/resourcemanager/agricultureplatform/armagricultureplatform/operations_client_example_test.go @@ -0,0 +1,56 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armagricultureplatform_test + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azidentity" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/agricultureplatform/armagricultureplatform" + "log" +) + +// Generated from example definition: 2024-06-01-preview/Operations_List_MaximumSet_Gen.json +func ExampleOperationsClient_NewListPager() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armagricultureplatform.NewClientFactory("", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + pager := clientFactory.NewOperationsClient().NewListPager(nil) + for pager.More() { + page, err := pager.NextPage(ctx) + if err != nil { + log.Fatalf("failed to advance page: %v", err) + } + for _, v := range page.Value { + // You could use page here. We use blank identifier for just demo purposes. + _ = v + } + // If the HTTP response code is 200 as defined in example definition, your page structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // page = armagricultureplatform.OperationsClientListResponse{ + // OperationListResult: armagricultureplatform.OperationListResult{ + // Value: []*armagricultureplatform.Operation{ + // { + // Name: to.Ptr("on"), + // IsDataAction: to.Ptr(true), + // Display: &armagricultureplatform.OperationDisplay{ + // Provider: to.Ptr("yvkmdseicusbpedotoit"), + // Resource: to.Ptr("gzqgh"), + // Operation: to.Ptr("wdvqfctmtffessbckulhoswzv"), + // Description: to.Ptr("xuvqlrnkwqsafmydwvywnpdxlsmnn"), + // }, + // Origin: to.Ptr(armagricultureplatform.OriginUser), + // ActionType: to.Ptr(armagricultureplatform.ActionTypeInternal), + // }, + // }, + // NextLink: to.Ptr("https://microsoft.com/a"), + // }, + // } + } +} diff --git a/sdk/resourcemanager/agricultureplatform/armagricultureplatform/options.go b/sdk/resourcemanager/agricultureplatform/armagricultureplatform/options.go new file mode 100644 index 000000000000..9ea72f9c4123 --- /dev/null +++ b/sdk/resourcemanager/agricultureplatform/armagricultureplatform/options.go @@ -0,0 +1,52 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armagricultureplatform + +// AgriServiceClientBeginCreateOrUpdateOptions contains the optional parameters for the AgriServiceClient.BeginCreateOrUpdate +// method. +type AgriServiceClientBeginCreateOrUpdateOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// AgriServiceClientBeginDeleteOptions contains the optional parameters for the AgriServiceClient.BeginDelete method. +type AgriServiceClientBeginDeleteOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// AgriServiceClientBeginUpdateOptions contains the optional parameters for the AgriServiceClient.BeginUpdate method. +type AgriServiceClientBeginUpdateOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// AgriServiceClientGetOptions contains the optional parameters for the AgriServiceClient.Get method. +type AgriServiceClientGetOptions struct { + // placeholder for future optional parameters +} + +// AgriServiceClientListAvailableSolutionsOptions contains the optional parameters for the AgriServiceClient.ListAvailableSolutions +// method. +type AgriServiceClientListAvailableSolutionsOptions struct { + // placeholder for future optional parameters +} + +// AgriServiceClientListByResourceGroupOptions contains the optional parameters for the AgriServiceClient.NewListByResourceGroupPager +// method. +type AgriServiceClientListByResourceGroupOptions struct { + // placeholder for future optional parameters +} + +// AgriServiceClientListBySubscriptionOptions contains the optional parameters for the AgriServiceClient.NewListBySubscriptionPager +// method. +type AgriServiceClientListBySubscriptionOptions struct { + // placeholder for future optional parameters +} + +// OperationsClientListOptions contains the optional parameters for the OperationsClient.NewListPager method. +type OperationsClientListOptions struct { + // placeholder for future optional parameters +} diff --git a/sdk/resourcemanager/agricultureplatform/armagricultureplatform/responses.go b/sdk/resourcemanager/agricultureplatform/armagricultureplatform/responses.go new file mode 100644 index 000000000000..27d782bd7376 --- /dev/null +++ b/sdk/resourcemanager/agricultureplatform/armagricultureplatform/responses.go @@ -0,0 +1,52 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armagricultureplatform + +// AgriServiceClientCreateOrUpdateResponse contains the response from method AgriServiceClient.BeginCreateOrUpdate. +type AgriServiceClientCreateOrUpdateResponse struct { + // Schema of the AgriService resource from Microsoft.AgriculturePlatform resource provider. + AgriServiceResource +} + +// AgriServiceClientDeleteResponse contains the response from method AgriServiceClient.BeginDelete. +type AgriServiceClientDeleteResponse struct { + // placeholder for future response values +} + +// AgriServiceClientGetResponse contains the response from method AgriServiceClient.Get. +type AgriServiceClientGetResponse struct { + // Schema of the AgriService resource from Microsoft.AgriculturePlatform resource provider. + AgriServiceResource +} + +// AgriServiceClientListAvailableSolutionsResponse contains the response from method AgriServiceClient.ListAvailableSolutions. +type AgriServiceClientListAvailableSolutionsResponse struct { + // The list of available agri solutions. + AvailableAgriSolutionListResult +} + +// AgriServiceClientListByResourceGroupResponse contains the response from method AgriServiceClient.NewListByResourceGroupPager. +type AgriServiceClientListByResourceGroupResponse struct { + // The response of a AgriServiceResource list operation. + AgriServiceResourceListResult +} + +// AgriServiceClientListBySubscriptionResponse contains the response from method AgriServiceClient.NewListBySubscriptionPager. +type AgriServiceClientListBySubscriptionResponse struct { + // The response of a AgriServiceResource list operation. + AgriServiceResourceListResult +} + +// AgriServiceClientUpdateResponse contains the response from method AgriServiceClient.BeginUpdate. +type AgriServiceClientUpdateResponse struct { + // Schema of the AgriService resource from Microsoft.AgriculturePlatform resource provider. + AgriServiceResource +} + +// 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 +} diff --git a/sdk/resourcemanager/agricultureplatform/armagricultureplatform/time_rfc3339.go b/sdk/resourcemanager/agricultureplatform/armagricultureplatform/time_rfc3339.go new file mode 100644 index 000000000000..6084d77153d5 --- /dev/null +++ b/sdk/resourcemanager/agricultureplatform/armagricultureplatform/time_rfc3339.go @@ -0,0 +1,109 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armagricultureplatform + +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 +} diff --git a/sdk/resourcemanager/agricultureplatform/armagricultureplatform/tsp-location.yaml b/sdk/resourcemanager/agricultureplatform/armagricultureplatform/tsp-location.yaml new file mode 100644 index 000000000000..e5c23549c652 --- /dev/null +++ b/sdk/resourcemanager/agricultureplatform/armagricultureplatform/tsp-location.yaml @@ -0,0 +1,4 @@ +directory: specification/agricultureplatform/AgriculturePlatform.Management +commit: 1f578543d267d08febc1bebf4e33ffe14363ddfc +repo: Azure/azure-rest-api-specs +additionalDirectories: diff --git a/sdk/resourcemanager/carbonoptimization/armcarbonoptimization/CHANGELOG.md b/sdk/resourcemanager/carbonoptimization/armcarbonoptimization/CHANGELOG.md new file mode 100644 index 000000000000..69adc2249ee0 --- /dev/null +++ b/sdk/resourcemanager/carbonoptimization/armcarbonoptimization/CHANGELOG.md @@ -0,0 +1,8 @@ +# Release History + +## 0.1.0 (2025-04-27) +### Other Changes + +The package of `github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/carbonoptimization/armcarbonoptimization` 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/carbonoptimization/armcarbonoptimization/LICENSE.txt b/sdk/resourcemanager/carbonoptimization/armcarbonoptimization/LICENSE.txt new file mode 100644 index 000000000000..dc0c2ffb3dc1 --- /dev/null +++ b/sdk/resourcemanager/carbonoptimization/armcarbonoptimization/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/carbonoptimization/armcarbonoptimization/README.md b/sdk/resourcemanager/carbonoptimization/armcarbonoptimization/README.md new file mode 100644 index 000000000000..f31d83f7224c --- /dev/null +++ b/sdk/resourcemanager/carbonoptimization/armcarbonoptimization/README.md @@ -0,0 +1,90 @@ +# Azure Carbonoptimization Module for Go + +The `armcarbonoptimization` module provides operations for working with Azure Carbonoptimization. + +[Source code](https://github.com/Azure/azure-sdk-for-go/tree/main/sdk/resourcemanager/carbonoptimization/armcarbonoptimization) + +# 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 Carbonoptimization module: + +```sh +go get github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/carbonoptimization/armcarbonoptimization +``` + +## Authorization + +When creating a client, you will need to provide a credential for authenticating with Azure Carbonoptimization. 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 Carbonoptimization 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 := armcarbonoptimization.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 := armcarbonoptimization.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.() +``` + +## 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 `Carbonoptimization` 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/carbonoptimization/armcarbonoptimization/carbonservice_client.go b/sdk/resourcemanager/carbonoptimization/armcarbonoptimization/carbonservice_client.go new file mode 100644 index 000000000000..a02693c953b2 --- /dev/null +++ b/sdk/resourcemanager/carbonoptimization/armcarbonoptimization/carbonservice_client.go @@ -0,0 +1,141 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcarbonoptimization + +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" +) + +// CarbonServiceClient contains the methods for the CarbonService group. +// Don't use this type directly, use NewCarbonServiceClient() instead. +type CarbonServiceClient struct { + internal *arm.Client +} + +// NewCarbonServiceClient creates a new instance of CarbonServiceClient with the specified values. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - pass nil to accept the default values. +func NewCarbonServiceClient(credential azcore.TokenCredential, options *arm.ClientOptions) (*CarbonServiceClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &CarbonServiceClient{ + internal: cl, + } + return client, nil +} + +// QueryCarbonEmissionDataAvailableDateRange - API for query carbon emission data available date range +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2025-04-01 +// - options - CarbonServiceClientQueryCarbonEmissionDataAvailableDateRangeOptions contains the optional parameters for the +// CarbonServiceClient.QueryCarbonEmissionDataAvailableDateRange method. +func (client *CarbonServiceClient) QueryCarbonEmissionDataAvailableDateRange(ctx context.Context, options *CarbonServiceClientQueryCarbonEmissionDataAvailableDateRangeOptions) (CarbonServiceClientQueryCarbonEmissionDataAvailableDateRangeResponse, error) { + var err error + const operationName = "CarbonServiceClient.QueryCarbonEmissionDataAvailableDateRange" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.queryCarbonEmissionDataAvailableDateRangeCreateRequest(ctx, options) + if err != nil { + return CarbonServiceClientQueryCarbonEmissionDataAvailableDateRangeResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return CarbonServiceClientQueryCarbonEmissionDataAvailableDateRangeResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return CarbonServiceClientQueryCarbonEmissionDataAvailableDateRangeResponse{}, err + } + resp, err := client.queryCarbonEmissionDataAvailableDateRangeHandleResponse(httpResp) + return resp, err +} + +// queryCarbonEmissionDataAvailableDateRangeCreateRequest creates the QueryCarbonEmissionDataAvailableDateRange request. +func (client *CarbonServiceClient) queryCarbonEmissionDataAvailableDateRangeCreateRequest(ctx context.Context, _ *CarbonServiceClientQueryCarbonEmissionDataAvailableDateRangeOptions) (*policy.Request, error) { + urlPath := "/providers/Microsoft.Carbon/queryCarbonEmissionDataAvailableDateRange" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2025-04-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// queryCarbonEmissionDataAvailableDateRangeHandleResponse handles the QueryCarbonEmissionDataAvailableDateRange response. +func (client *CarbonServiceClient) queryCarbonEmissionDataAvailableDateRangeHandleResponse(resp *http.Response) (CarbonServiceClientQueryCarbonEmissionDataAvailableDateRangeResponse, error) { + result := CarbonServiceClientQueryCarbonEmissionDataAvailableDateRangeResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.CarbonEmissionDataAvailableDateRange); err != nil { + return CarbonServiceClientQueryCarbonEmissionDataAvailableDateRangeResponse{}, err + } + return result, nil +} + +// QueryCarbonEmissionReports - API for Carbon Emissions Reports +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2025-04-01 +// - queryParameters - Query parameters +// - options - CarbonServiceClientQueryCarbonEmissionReportsOptions contains the optional parameters for the CarbonServiceClient.QueryCarbonEmissionReports +// method. +func (client *CarbonServiceClient) QueryCarbonEmissionReports(ctx context.Context, queryParameters QueryFilterClassification, options *CarbonServiceClientQueryCarbonEmissionReportsOptions) (CarbonServiceClientQueryCarbonEmissionReportsResponse, error) { + var err error + const operationName = "CarbonServiceClient.QueryCarbonEmissionReports" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.queryCarbonEmissionReportsCreateRequest(ctx, queryParameters, options) + if err != nil { + return CarbonServiceClientQueryCarbonEmissionReportsResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return CarbonServiceClientQueryCarbonEmissionReportsResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return CarbonServiceClientQueryCarbonEmissionReportsResponse{}, err + } + resp, err := client.queryCarbonEmissionReportsHandleResponse(httpResp) + return resp, err +} + +// queryCarbonEmissionReportsCreateRequest creates the QueryCarbonEmissionReports request. +func (client *CarbonServiceClient) queryCarbonEmissionReportsCreateRequest(ctx context.Context, queryParameters QueryFilterClassification, _ *CarbonServiceClientQueryCarbonEmissionReportsOptions) (*policy.Request, error) { + urlPath := "/providers/Microsoft.Carbon/carbonEmissionReports" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2025-04-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, queryParameters); err != nil { + return nil, err + } + return req, nil +} + +// queryCarbonEmissionReportsHandleResponse handles the QueryCarbonEmissionReports response. +func (client *CarbonServiceClient) queryCarbonEmissionReportsHandleResponse(resp *http.Response) (CarbonServiceClientQueryCarbonEmissionReportsResponse, error) { + result := CarbonServiceClientQueryCarbonEmissionReportsResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.CarbonEmissionDataListResult); err != nil { + return CarbonServiceClientQueryCarbonEmissionReportsResponse{}, err + } + return result, nil +} diff --git a/sdk/resourcemanager/carbonoptimization/armcarbonoptimization/carbonservice_client_example_test.go b/sdk/resourcemanager/carbonoptimization/armcarbonoptimization/carbonservice_client_example_test.go new file mode 100644 index 000000000000..ea8cfbde3e9f --- /dev/null +++ b/sdk/resourcemanager/carbonoptimization/armcarbonoptimization/carbonservice_client_example_test.go @@ -0,0 +1,2642 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcarbonoptimization_test + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/Azure/azure-sdk-for-go/sdk/azidentity" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/carbonoptimization/armcarbonoptimization" + "log" + "time" +) + +// Generated from example definition: 2025-04-01/carbonEmissionsDataAvailableDateRange.json +func ExampleCarbonServiceClient_QueryCarbonEmissionDataAvailableDateRange() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armcarbonoptimization.NewClientFactory(cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + res, err := clientFactory.NewCarbonServiceClient().QueryCarbonEmissionDataAvailableDateRange(ctx, nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + // You could use response here. We use blank identifier for just demo purposes. + _ = res + // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // res = armcarbonoptimization.CarbonServiceClientQueryCarbonEmissionDataAvailableDateRangeResponse{ + // CarbonEmissionDataAvailableDateRange: &armcarbonoptimization.CarbonEmissionDataAvailableDateRange{ + // StartDate: to.Ptr("2023-01-01"), + // EndDate: to.Ptr("2023-05-01"), + // }, + // } +} + +// Generated from example definition: 2025-04-01/queryCarbonEmissionsLocationItemDetailsReport.json +func ExampleCarbonServiceClient_QueryCarbonEmissionReports_queryCarbonEmissionLocationItemDetailsReport() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armcarbonoptimization.NewClientFactory(cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + res, err := clientFactory.NewCarbonServiceClient().QueryCarbonEmissionReports(ctx, armcarbonoptimization.ItemDetailsQueryFilter{ + ReportType: to.Ptr(armcarbonoptimization.ReportTypeEnumItemDetailsReport), + SubscriptionList: []*string{ + to.Ptr("00000000-0000-0000-0000-000000000000"), + to.Ptr("00000000-0000-0000-0000-000000000001,"), + to.Ptr("00000000-0000-0000-0000-000000000002"), + to.Ptr("00000000-0000-0000-0000-000000000003"), + to.Ptr("00000000-0000-0000-0000-000000000004"), + to.Ptr("00000000-0000-0000-0000-000000000005"), + to.Ptr("00000000-0000-0000-0000-000000000006"), + to.Ptr("00000000-0000-0000-0000-000000000007"), + to.Ptr("00000000-0000-0000-0000-000000000008"), + }, + CarbonScopeList: []*armcarbonoptimization.EmissionScopeEnum{ + to.Ptr(armcarbonoptimization.EmissionScopeEnumScope1), + to.Ptr(armcarbonoptimization.EmissionScopeEnumScope3), + }, + DateRange: &armcarbonoptimization.DateRange{ + Start: to.Ptr(func() time.Time { t, _ := time.Parse("2006-01-02", "2024-05-01"); return t }()), + End: to.Ptr(func() time.Time { t, _ := time.Parse("2006-01-02", "2024-05-01"); return t }()), + }, + CategoryType: to.Ptr(armcarbonoptimization.CategoryTypeEnumLocation), + OrderBy: to.Ptr(armcarbonoptimization.OrderByColumnEnumLatestMonthEmissions), + SortDirection: to.Ptr(armcarbonoptimization.SortDirectionEnumDesc), + PageSize: to.Ptr[int32](100), + }, nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + // You could use response here. We use blank identifier for just demo purposes. + _ = res + // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // res = armcarbonoptimization.CarbonServiceClientQueryCarbonEmissionReportsResponse{ + // CarbonEmissionDataListResult: &armcarbonoptimization.CarbonEmissionDataListResult{ + // SubscriptionAccessDecisionList: []*armcarbonoptimization.SubscriptionAccessDecision{ + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000000"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumAllowed), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000001"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumAllowed), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000002"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumAllowed), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000003"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumAllowed), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000004"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumAllowed), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000005"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumAllowed), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000006"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumDenied), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000007"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumDenied), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000008"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumDenied), + // DenialReason: to.Ptr("Carbon Optimization Reader permisison required"), + // }, + // }, + // Value: []armcarbonoptimization.CarbonEmissionDataClassification{ + // &armcarbonoptimization.CarbonEmissionItemDetailData{ + // DataType: to.Ptr(armcarbonoptimization.ResponseDataTypeEnumItemDetailsData), + // LatestMonthEmissions: to.Ptr[float64](0.1), + // PreviousMonthEmissions: to.Ptr[float64](0.05), + // MonthOverMonthEmissionsChangeRatio: to.Ptr[float64](1), + // MonthlyEmissionsChangeValue: to.Ptr[float64](0.05), + // ItemName: to.Ptr("east us"), + // CategoryType: to.Ptr(armcarbonoptimization.CategoryTypeEnumLocation), + // }, + // &armcarbonoptimization.CarbonEmissionItemDetailData{ + // DataType: to.Ptr(armcarbonoptimization.ResponseDataTypeEnumItemDetailsData), + // LatestMonthEmissions: to.Ptr[float64](0.1), + // PreviousMonthEmissions: to.Ptr[float64](0.05), + // MonthOverMonthEmissionsChangeRatio: to.Ptr[float64](1), + // MonthlyEmissionsChangeValue: to.Ptr[float64](0.05), + // ItemName: to.Ptr("west us"), + // CategoryType: to.Ptr(armcarbonoptimization.CategoryTypeEnumLocation), + // }, + // &armcarbonoptimization.CarbonEmissionItemDetailData{ + // DataType: to.Ptr(armcarbonoptimization.ResponseDataTypeEnumItemDetailsData), + // LatestMonthEmissions: to.Ptr[float64](0.1), + // PreviousMonthEmissions: to.Ptr[float64](0.05), + // MonthOverMonthEmissionsChangeRatio: to.Ptr[float64](1), + // MonthlyEmissionsChangeValue: to.Ptr[float64](0.05), + // ItemName: to.Ptr("west us 2"), + // CategoryType: to.Ptr(armcarbonoptimization.CategoryTypeEnumLocation), + // }, + // &armcarbonoptimization.CarbonEmissionItemDetailData{ + // DataType: to.Ptr(armcarbonoptimization.ResponseDataTypeEnumItemDetailsData), + // LatestMonthEmissions: to.Ptr[float64](0.1), + // PreviousMonthEmissions: to.Ptr[float64](0.05), + // MonthOverMonthEmissionsChangeRatio: to.Ptr[float64](1), + // MonthlyEmissionsChangeValue: to.Ptr[float64](0.05), + // ItemName: to.Ptr("west us 3"), + // CategoryType: to.Ptr(armcarbonoptimization.CategoryTypeEnumLocation), + // }, + // &armcarbonoptimization.CarbonEmissionItemDetailData{ + // DataType: to.Ptr(armcarbonoptimization.ResponseDataTypeEnumItemDetailsData), + // LatestMonthEmissions: to.Ptr[float64](0.1), + // PreviousMonthEmissions: to.Ptr[float64](0.05), + // MonthOverMonthEmissionsChangeRatio: to.Ptr[float64](1), + // MonthlyEmissionsChangeValue: to.Ptr[float64](0.05), + // ItemName: to.Ptr("east us 2"), + // CategoryType: to.Ptr(armcarbonoptimization.CategoryTypeEnumLocation), + // }, + // }, + // }, + // } +} + +// Generated from example definition: 2025-04-01/queryCarbonEmissionsMonthlySummaryReport.json +func ExampleCarbonServiceClient_QueryCarbonEmissionReports_queryCarbonEmissionOverallMonthlySummaryReport() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armcarbonoptimization.NewClientFactory(cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + res, err := clientFactory.NewCarbonServiceClient().QueryCarbonEmissionReports(ctx, armcarbonoptimization.MonthlySummaryReportQueryFilter{ + ReportType: to.Ptr(armcarbonoptimization.ReportTypeEnumMonthlySummaryReport), + SubscriptionList: []*string{ + to.Ptr("00000000-0000-0000-0000-000000000000"), + }, + CarbonScopeList: []*armcarbonoptimization.EmissionScopeEnum{ + to.Ptr(armcarbonoptimization.EmissionScopeEnumScope1), + to.Ptr(armcarbonoptimization.EmissionScopeEnumScope3), + }, + DateRange: &armcarbonoptimization.DateRange{ + Start: to.Ptr(func() time.Time { t, _ := time.Parse("2006-01-02", "2024-03-01"); return t }()), + End: to.Ptr(func() time.Time { t, _ := time.Parse("2006-01-02", "2024-05-01"); return t }()), + }, + }, nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + // You could use response here. We use blank identifier for just demo purposes. + _ = res + // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // res = armcarbonoptimization.CarbonServiceClientQueryCarbonEmissionReportsResponse{ + // CarbonEmissionDataListResult: &armcarbonoptimization.CarbonEmissionDataListResult{ + // SubscriptionAccessDecisionList: []*armcarbonoptimization.SubscriptionAccessDecision{ + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000000"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumAllowed), + // }, + // }, + // Value: []armcarbonoptimization.CarbonEmissionDataClassification{ + // &armcarbonoptimization.CarbonEmissionMonthlySummaryData{ + // DataType: to.Ptr(armcarbonoptimization.ResponseDataTypeEnumMonthlySummaryData), + // LatestMonthEmissions: to.Ptr[float64](0.1), + // PreviousMonthEmissions: to.Ptr[float64](0.05), + // MonthOverMonthEmissionsChangeRatio: to.Ptr[float64](1), + // MonthlyEmissionsChangeValue: to.Ptr[float64](0.05), + // Date: to.Ptr("2024-05-01"), + // CarbonIntensity: to.Ptr[float64](22), + // }, + // &armcarbonoptimization.CarbonEmissionMonthlySummaryData{ + // DataType: to.Ptr(armcarbonoptimization.ResponseDataTypeEnumMonthlySummaryData), + // LatestMonthEmissions: to.Ptr[float64](0.1), + // PreviousMonthEmissions: to.Ptr[float64](0.05), + // MonthOverMonthEmissionsChangeRatio: to.Ptr[float64](1), + // MonthlyEmissionsChangeValue: to.Ptr[float64](0.05), + // Date: to.Ptr("2024-04-01"), + // CarbonIntensity: to.Ptr[float64](22), + // }, + // &armcarbonoptimization.CarbonEmissionMonthlySummaryData{ + // DataType: to.Ptr(armcarbonoptimization.ResponseDataTypeEnumMonthlySummaryData), + // LatestMonthEmissions: to.Ptr[float64](0.1), + // PreviousMonthEmissions: to.Ptr[float64](0.05), + // MonthOverMonthEmissionsChangeRatio: to.Ptr[float64](1), + // MonthlyEmissionsChangeValue: to.Ptr[float64](0.05), + // Date: to.Ptr("2024-03-01"), + // CarbonIntensity: to.Ptr[float64](22), + // }, + // }, + // }, + // } +} + +// Generated from example definition: 2025-04-01/queryCarbonEmissionsMonthlySummaryReportWithOtherOptionalFilter.json +func ExampleCarbonServiceClient_QueryCarbonEmissionReports_queryCarbonEmissionMonthlySummaryReportWithOptionalFilterLocationListResourceTypeListResourceGroupUrlList() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armcarbonoptimization.NewClientFactory(cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + res, err := clientFactory.NewCarbonServiceClient().QueryCarbonEmissionReports(ctx, armcarbonoptimization.MonthlySummaryReportQueryFilter{ + ReportType: to.Ptr(armcarbonoptimization.ReportTypeEnumMonthlySummaryReport), + SubscriptionList: []*string{ + to.Ptr("00000000-0000-0000-0000-000000000000"), + }, + CarbonScopeList: []*armcarbonoptimization.EmissionScopeEnum{ + to.Ptr(armcarbonoptimization.EmissionScopeEnumScope1), + to.Ptr(armcarbonoptimization.EmissionScopeEnumScope3), + }, + DateRange: &armcarbonoptimization.DateRange{ + Start: to.Ptr(func() time.Time { t, _ := time.Parse("2006-01-02", "2024-03-01"); return t }()), + End: to.Ptr(func() time.Time { t, _ := time.Parse("2006-01-02", "2024-05-01"); return t }()), + }, + LocationList: []*string{ + to.Ptr("east us"), + to.Ptr("west us"), + }, + ResourceTypeList: []*string{ + to.Ptr("microsoft.storage/storageaccounts"), + to.Ptr("microsoft.databricks/workspaces"), + }, + ResourceGroupURLList: []*string{ + to.Ptr("/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/rg-name"), + }, + }, nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + // You could use response here. We use blank identifier for just demo purposes. + _ = res + // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // res = armcarbonoptimization.CarbonServiceClientQueryCarbonEmissionReportsResponse{ + // CarbonEmissionDataListResult: &armcarbonoptimization.CarbonEmissionDataListResult{ + // SubscriptionAccessDecisionList: []*armcarbonoptimization.SubscriptionAccessDecision{ + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000000"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumAllowed), + // }, + // }, + // Value: []armcarbonoptimization.CarbonEmissionDataClassification{ + // &armcarbonoptimization.CarbonEmissionMonthlySummaryData{ + // DataType: to.Ptr(armcarbonoptimization.ResponseDataTypeEnumMonthlySummaryData), + // LatestMonthEmissions: to.Ptr[float64](0.1), + // PreviousMonthEmissions: to.Ptr[float64](0.05), + // MonthOverMonthEmissionsChangeRatio: to.Ptr[float64](1), + // MonthlyEmissionsChangeValue: to.Ptr[float64](0.05), + // Date: to.Ptr("2024-05-01"), + // CarbonIntensity: to.Ptr[float64](22), + // }, + // &armcarbonoptimization.CarbonEmissionMonthlySummaryData{ + // DataType: to.Ptr(armcarbonoptimization.ResponseDataTypeEnumMonthlySummaryData), + // LatestMonthEmissions: to.Ptr[float64](0.1), + // PreviousMonthEmissions: to.Ptr[float64](0.05), + // MonthOverMonthEmissionsChangeRatio: to.Ptr[float64](1), + // MonthlyEmissionsChangeValue: to.Ptr[float64](0.05), + // Date: to.Ptr("2024-04-01"), + // CarbonIntensity: to.Ptr[float64](22), + // }, + // &armcarbonoptimization.CarbonEmissionMonthlySummaryData{ + // DataType: to.Ptr(armcarbonoptimization.ResponseDataTypeEnumMonthlySummaryData), + // LatestMonthEmissions: to.Ptr[float64](0.1), + // PreviousMonthEmissions: to.Ptr[float64](0.05), + // MonthOverMonthEmissionsChangeRatio: to.Ptr[float64](1), + // MonthlyEmissionsChangeValue: to.Ptr[float64](0.05), + // Date: to.Ptr("2024-03-01"), + // CarbonIntensity: to.Ptr[float64](22), + // }, + // }, + // }, + // } +} + +// Generated from example definition: 2025-04-01/queryCarbonEmissionsOverallSummaryReport.json +func ExampleCarbonServiceClient_QueryCarbonEmissionReports_queryCarbonEmissionOverallSummaryReport() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armcarbonoptimization.NewClientFactory(cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + res, err := clientFactory.NewCarbonServiceClient().QueryCarbonEmissionReports(ctx, armcarbonoptimization.OverallSummaryReportQueryFilter{ + ReportType: to.Ptr(armcarbonoptimization.ReportTypeEnumOverallSummaryReport), + SubscriptionList: []*string{ + to.Ptr("00000000-0000-0000-0000-000000000000"), + }, + CarbonScopeList: []*armcarbonoptimization.EmissionScopeEnum{ + to.Ptr(armcarbonoptimization.EmissionScopeEnumScope1), + to.Ptr(armcarbonoptimization.EmissionScopeEnumScope3), + }, + DateRange: &armcarbonoptimization.DateRange{ + Start: to.Ptr(func() time.Time { t, _ := time.Parse("2006-01-02", "2023-06-01"); return t }()), + End: to.Ptr(func() time.Time { t, _ := time.Parse("2006-01-02", "2023-06-01"); return t }()), + }, + }, nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + // You could use response here. We use blank identifier for just demo purposes. + _ = res + // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // res = armcarbonoptimization.CarbonServiceClientQueryCarbonEmissionReportsResponse{ + // CarbonEmissionDataListResult: &armcarbonoptimization.CarbonEmissionDataListResult{ + // SubscriptionAccessDecisionList: []*armcarbonoptimization.SubscriptionAccessDecision{ + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000000"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumAllowed), + // }, + // }, + // Value: []armcarbonoptimization.CarbonEmissionDataClassification{ + // &armcarbonoptimization.CarbonEmissionOverallSummaryData{ + // DataType: to.Ptr(armcarbonoptimization.ResponseDataTypeEnumOverallSummaryData), + // LatestMonthEmissions: to.Ptr[float64](0.1), + // PreviousMonthEmissions: to.Ptr[float64](0.05), + // MonthOverMonthEmissionsChangeRatio: to.Ptr[float64](1), + // MonthlyEmissionsChangeValue: to.Ptr[float64](0.05), + // }, + // }, + // }, + // } +} + +// Generated from example definition: 2025-04-01/queryCarbonEmissionsOverallSummaryReportWithOtherOptionalFilter.json +func ExampleCarbonServiceClient_QueryCarbonEmissionReports_queryCarbonEmissionOverallSummaryReportWithOptionalFilterLocationListResourceTypeListResourceGroupUrlList() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armcarbonoptimization.NewClientFactory(cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + res, err := clientFactory.NewCarbonServiceClient().QueryCarbonEmissionReports(ctx, armcarbonoptimization.OverallSummaryReportQueryFilter{ + ReportType: to.Ptr(armcarbonoptimization.ReportTypeEnumOverallSummaryReport), + SubscriptionList: []*string{ + to.Ptr("00000000-0000-0000-0000-000000000000"), + }, + CarbonScopeList: []*armcarbonoptimization.EmissionScopeEnum{ + to.Ptr(armcarbonoptimization.EmissionScopeEnumScope1), + to.Ptr(armcarbonoptimization.EmissionScopeEnumScope3), + }, + DateRange: &armcarbonoptimization.DateRange{ + Start: to.Ptr(func() time.Time { t, _ := time.Parse("2006-01-02", "2023-06-01"); return t }()), + End: to.Ptr(func() time.Time { t, _ := time.Parse("2006-01-02", "2023-06-01"); return t }()), + }, + LocationList: []*string{ + to.Ptr("east us"), + to.Ptr("west us"), + }, + ResourceTypeList: []*string{ + to.Ptr("microsoft.storage/storageaccounts"), + to.Ptr("microsoft.databricks/workspaces"), + }, + ResourceGroupURLList: []*string{ + to.Ptr("/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/rg-name"), + }, + }, nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + // You could use response here. We use blank identifier for just demo purposes. + _ = res + // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // res = armcarbonoptimization.CarbonServiceClientQueryCarbonEmissionReportsResponse{ + // CarbonEmissionDataListResult: &armcarbonoptimization.CarbonEmissionDataListResult{ + // SubscriptionAccessDecisionList: []*armcarbonoptimization.SubscriptionAccessDecision{ + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000000"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumAllowed), + // }, + // }, + // Value: []armcarbonoptimization.CarbonEmissionDataClassification{ + // &armcarbonoptimization.CarbonEmissionOverallSummaryData{ + // DataType: to.Ptr(armcarbonoptimization.ResponseDataTypeEnumOverallSummaryData), + // LatestMonthEmissions: to.Ptr[float64](0.1), + // PreviousMonthEmissions: to.Ptr[float64](0.05), + // MonthOverMonthEmissionsChangeRatio: to.Ptr[float64](1), + // MonthlyEmissionsChangeValue: to.Ptr[float64](0.05), + // }, + // }, + // }, + // } +} + +// Generated from example definition: 2025-04-01/queryCarbonEmissionsResourceGroupItemDetailsReport.json +func ExampleCarbonServiceClient_QueryCarbonEmissionReports_queryCarbonEmissionResourceGroupItemDetailsReport() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armcarbonoptimization.NewClientFactory(cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + res, err := clientFactory.NewCarbonServiceClient().QueryCarbonEmissionReports(ctx, armcarbonoptimization.ItemDetailsQueryFilter{ + ReportType: to.Ptr(armcarbonoptimization.ReportTypeEnumItemDetailsReport), + SubscriptionList: []*string{ + to.Ptr("00000000-0000-0000-0000-000000000000"), + to.Ptr("00000000-0000-0000-0000-000000000001,"), + to.Ptr("00000000-0000-0000-0000-000000000002"), + to.Ptr("00000000-0000-0000-0000-000000000003"), + to.Ptr("00000000-0000-0000-0000-000000000004"), + to.Ptr("00000000-0000-0000-0000-000000000005"), + to.Ptr("00000000-0000-0000-0000-000000000006"), + to.Ptr("00000000-0000-0000-0000-000000000007"), + to.Ptr("00000000-0000-0000-0000-000000000008"), + }, + CarbonScopeList: []*armcarbonoptimization.EmissionScopeEnum{ + to.Ptr(armcarbonoptimization.EmissionScopeEnumScope1), + to.Ptr(armcarbonoptimization.EmissionScopeEnumScope3), + }, + DateRange: &armcarbonoptimization.DateRange{ + Start: to.Ptr(func() time.Time { t, _ := time.Parse("2006-01-02", "2024-05-01"); return t }()), + End: to.Ptr(func() time.Time { t, _ := time.Parse("2006-01-02", "2024-05-01"); return t }()), + }, + CategoryType: to.Ptr(armcarbonoptimization.CategoryTypeEnumResourceGroup), + OrderBy: to.Ptr(armcarbonoptimization.OrderByColumnEnumLatestMonthEmissions), + SortDirection: to.Ptr(armcarbonoptimization.SortDirectionEnumDesc), + PageSize: to.Ptr[int32](100), + }, nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + // You could use response here. We use blank identifier for just demo purposes. + _ = res + // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // res = armcarbonoptimization.CarbonServiceClientQueryCarbonEmissionReportsResponse{ + // CarbonEmissionDataListResult: &armcarbonoptimization.CarbonEmissionDataListResult{ + // SubscriptionAccessDecisionList: []*armcarbonoptimization.SubscriptionAccessDecision{ + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000000"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumAllowed), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000001"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumAllowed), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000002"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumAllowed), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000003"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumAllowed), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000004"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumAllowed), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000005"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumAllowed), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000006"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumDenied), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000007"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumDenied), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000008"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumDenied), + // DenialReason: to.Ptr("Carbon Optimization Reader permisison required"), + // }, + // }, + // Value: []armcarbonoptimization.CarbonEmissionDataClassification{ + // &armcarbonoptimization.ResourceGroupCarbonEmissionItemDetailData{ + // DataType: to.Ptr(armcarbonoptimization.ResponseDataTypeEnumResourceGroupItemDetailsData), + // LatestMonthEmissions: to.Ptr[float64](0.1), + // PreviousMonthEmissions: to.Ptr[float64](0.05), + // MonthOverMonthEmissionsChangeRatio: to.Ptr[float64](1), + // MonthlyEmissionsChangeValue: to.Ptr[float64](0.05), + // ItemName: to.Ptr("rgGroup1"), + // ResourceGroupURL: to.Ptr("/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rgGroup1"), + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000000"), + // CategoryType: to.Ptr(armcarbonoptimization.CategoryTypeEnumResourceGroup), + // }, + // &armcarbonoptimization.ResourceGroupCarbonEmissionItemDetailData{ + // DataType: to.Ptr(armcarbonoptimization.ResponseDataTypeEnumResourceGroupItemDetailsData), + // LatestMonthEmissions: to.Ptr[float64](0.1), + // PreviousMonthEmissions: to.Ptr[float64](0.05), + // MonthOverMonthEmissionsChangeRatio: to.Ptr[float64](1), + // MonthlyEmissionsChangeValue: to.Ptr[float64](0.05), + // ItemName: to.Ptr("rgGroup2"), + // ResourceGroupURL: to.Ptr("/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rgGroup2"), + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000000"), + // CategoryType: to.Ptr(armcarbonoptimization.CategoryTypeEnumResourceGroup), + // }, + // &armcarbonoptimization.ResourceGroupCarbonEmissionItemDetailData{ + // DataType: to.Ptr(armcarbonoptimization.ResponseDataTypeEnumResourceGroupItemDetailsData), + // LatestMonthEmissions: to.Ptr[float64](0.1), + // PreviousMonthEmissions: to.Ptr[float64](0.05), + // MonthOverMonthEmissionsChangeRatio: to.Ptr[float64](1), + // MonthlyEmissionsChangeValue: to.Ptr[float64](0.05), + // ItemName: to.Ptr("rgGroup3"), + // ResourceGroupURL: to.Ptr("/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rgGroup3"), + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000000"), + // CategoryType: to.Ptr(armcarbonoptimization.CategoryTypeEnumResourceGroup), + // }, + // &armcarbonoptimization.ResourceGroupCarbonEmissionItemDetailData{ + // DataType: to.Ptr(armcarbonoptimization.ResponseDataTypeEnumResourceGroupItemDetailsData), + // LatestMonthEmissions: to.Ptr[float64](0.1), + // PreviousMonthEmissions: to.Ptr[float64](0.05), + // MonthOverMonthEmissionsChangeRatio: to.Ptr[float64](1), + // MonthlyEmissionsChangeValue: to.Ptr[float64](0.05), + // ItemName: to.Ptr("rgGroup4"), + // ResourceGroupURL: to.Ptr("/subscriptions/00000000-0000-0000-0000-000000000002/resourceGroups/rgGroup4"), + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000002"), + // CategoryType: to.Ptr(armcarbonoptimization.CategoryTypeEnumResourceGroup), + // }, + // &armcarbonoptimization.ResourceGroupCarbonEmissionItemDetailData{ + // DataType: to.Ptr(armcarbonoptimization.ResponseDataTypeEnumResourceGroupItemDetailsData), + // LatestMonthEmissions: to.Ptr[float64](0.1), + // PreviousMonthEmissions: to.Ptr[float64](0.05), + // MonthOverMonthEmissionsChangeRatio: to.Ptr[float64](1), + // MonthlyEmissionsChangeValue: to.Ptr[float64](0.05), + // ItemName: to.Ptr("rgGroup5"), + // ResourceGroupURL: to.Ptr("/subscriptions/00000000-0000-0000-0000-000000000002/resourceGroups/rgGroup5"), + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000002"), + // CategoryType: to.Ptr(armcarbonoptimization.CategoryTypeEnumResourceGroup), + // }, + // }, + // }, + // } +} + +// Generated from example definition: 2025-04-01/queryCarbonEmissionsResourceItemDetailsReport.json +func ExampleCarbonServiceClient_QueryCarbonEmissionReports_queryCarbonEmissionResourceItemDetailsReport() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armcarbonoptimization.NewClientFactory(cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + res, err := clientFactory.NewCarbonServiceClient().QueryCarbonEmissionReports(ctx, armcarbonoptimization.ItemDetailsQueryFilter{ + ReportType: to.Ptr(armcarbonoptimization.ReportTypeEnumItemDetailsReport), + SubscriptionList: []*string{ + to.Ptr("00000000-0000-0000-0000-000000000000"), + to.Ptr("00000000-0000-0000-0000-000000000001,"), + to.Ptr("00000000-0000-0000-0000-000000000002"), + to.Ptr("00000000-0000-0000-0000-000000000003"), + to.Ptr("00000000-0000-0000-0000-000000000004"), + to.Ptr("00000000-0000-0000-0000-000000000005"), + to.Ptr("00000000-0000-0000-0000-000000000006"), + to.Ptr("00000000-0000-0000-0000-000000000007"), + to.Ptr("00000000-0000-0000-0000-000000000008"), + }, + CarbonScopeList: []*armcarbonoptimization.EmissionScopeEnum{ + to.Ptr(armcarbonoptimization.EmissionScopeEnumScope1), + to.Ptr(armcarbonoptimization.EmissionScopeEnumScope3), + }, + DateRange: &armcarbonoptimization.DateRange{ + Start: to.Ptr(func() time.Time { t, _ := time.Parse("2006-01-02", "2024-05-01"); return t }()), + End: to.Ptr(func() time.Time { t, _ := time.Parse("2006-01-02", "2024-05-01"); return t }()), + }, + CategoryType: to.Ptr(armcarbonoptimization.CategoryTypeEnumResource), + OrderBy: to.Ptr(armcarbonoptimization.OrderByColumnEnumLatestMonthEmissions), + SortDirection: to.Ptr(armcarbonoptimization.SortDirectionEnumDesc), + PageSize: to.Ptr[int32](100), + }, nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + // You could use response here. We use blank identifier for just demo purposes. + _ = res + // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // res = armcarbonoptimization.CarbonServiceClientQueryCarbonEmissionReportsResponse{ + // CarbonEmissionDataListResult: &armcarbonoptimization.CarbonEmissionDataListResult{ + // SubscriptionAccessDecisionList: []*armcarbonoptimization.SubscriptionAccessDecision{ + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000000"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumAllowed), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000001"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumAllowed), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000002"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumAllowed), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000003"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumAllowed), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000004"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumAllowed), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000005"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumAllowed), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000006"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumDenied), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000007"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumDenied), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000008"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumDenied), + // DenialReason: to.Ptr("Carbon Optimization Reader permisison required"), + // }, + // }, + // Value: []armcarbonoptimization.CarbonEmissionDataClassification{ + // &armcarbonoptimization.ResourceCarbonEmissionItemDetailData{ + // DataType: to.Ptr(armcarbonoptimization.ResponseDataTypeEnumResourceItemDetailsData), + // LatestMonthEmissions: to.Ptr[float64](0.1), + // PreviousMonthEmissions: to.Ptr[float64](0.05), + // MonthOverMonthEmissionsChangeRatio: to.Ptr[float64](1), + // MonthlyEmissionsChangeValue: to.Ptr[float64](0.05), + // ItemName: to.Ptr("rgName1"), + // ResourceGroup: to.Ptr("rgGroup"), + // ResourceID: to.Ptr("/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rgGroup/providers/microsoft.storage/storageaccounts/rgName1"), + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000000"), + // CategoryType: to.Ptr(armcarbonoptimization.CategoryTypeEnumResource), + // ResourceType: to.Ptr("microsoft.storage/storageaccounts"), + // Location: to.Ptr("east us"), + // }, + // &armcarbonoptimization.ResourceCarbonEmissionItemDetailData{ + // DataType: to.Ptr(armcarbonoptimization.ResponseDataTypeEnumResourceItemDetailsData), + // LatestMonthEmissions: to.Ptr[float64](0.1), + // PreviousMonthEmissions: to.Ptr[float64](0.05), + // MonthOverMonthEmissionsChangeRatio: to.Ptr[float64](1), + // MonthlyEmissionsChangeValue: to.Ptr[float64](0.05), + // ItemName: to.Ptr("rgName2"), + // ResourceGroup: to.Ptr("rgGroup"), + // ResourceID: to.Ptr("/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rgGroup/providers/microsoft.storage/storageaccounts/rgName2"), + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000000"), + // CategoryType: to.Ptr(armcarbonoptimization.CategoryTypeEnumResource), + // ResourceType: to.Ptr("microsoft.storage/storageaccounts"), + // Location: to.Ptr("east us"), + // }, + // &armcarbonoptimization.ResourceCarbonEmissionItemDetailData{ + // DataType: to.Ptr(armcarbonoptimization.ResponseDataTypeEnumResourceItemDetailsData), + // LatestMonthEmissions: to.Ptr[float64](0.1), + // PreviousMonthEmissions: to.Ptr[float64](0.05), + // MonthOverMonthEmissionsChangeRatio: to.Ptr[float64](1), + // MonthlyEmissionsChangeValue: to.Ptr[float64](0.05), + // ItemName: to.Ptr("rgName3"), + // ResourceGroup: to.Ptr("rgGroup"), + // ResourceID: to.Ptr("/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rgGroup/providers/microsoft.storage/storageaccounts/rgName3"), + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000000"), + // CategoryType: to.Ptr(armcarbonoptimization.CategoryTypeEnumResource), + // ResourceType: to.Ptr("microsoft.storage/storageaccounts"), + // Location: to.Ptr("east us"), + // }, + // &armcarbonoptimization.ResourceCarbonEmissionItemDetailData{ + // DataType: to.Ptr(armcarbonoptimization.ResponseDataTypeEnumResourceItemDetailsData), + // LatestMonthEmissions: to.Ptr[float64](0.1), + // PreviousMonthEmissions: to.Ptr[float64](0.05), + // MonthOverMonthEmissionsChangeRatio: to.Ptr[float64](1), + // MonthlyEmissionsChangeValue: to.Ptr[float64](0.05), + // ItemName: to.Ptr("rgName4"), + // ResourceGroup: to.Ptr("rgGroup"), + // ResourceID: to.Ptr("/subscriptions/00000000-0000-0000-0000-000000000002/resourceGroups/rgGroup/providers/microsoft.storage/storageaccounts/rgName4"), + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000002"), + // CategoryType: to.Ptr(armcarbonoptimization.CategoryTypeEnumResource), + // ResourceType: to.Ptr("microsoft.storage/storageaccounts"), + // Location: to.Ptr("east us"), + // }, + // &armcarbonoptimization.ResourceCarbonEmissionItemDetailData{ + // DataType: to.Ptr(armcarbonoptimization.ResponseDataTypeEnumResourceItemDetailsData), + // LatestMonthEmissions: to.Ptr[float64](0.1), + // PreviousMonthEmissions: to.Ptr[float64](0.05), + // MonthOverMonthEmissionsChangeRatio: to.Ptr[float64](1), + // MonthlyEmissionsChangeValue: to.Ptr[float64](0.05), + // ItemName: to.Ptr("rgName5"), + // ResourceGroup: to.Ptr("rgGroup"), + // ResourceID: to.Ptr("/subscriptions/00000000-0000-0000-0000-000000000002/resourceGroups/rgGroup/providers/microsoft.storage/storageaccounts/rgName5"), + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000002"), + // CategoryType: to.Ptr(armcarbonoptimization.CategoryTypeEnumResource), + // ResourceType: to.Ptr("microsoft.storage/storageaccounts"), + // Location: to.Ptr("east us"), + // }, + // }, + // SkipToken: to.Ptr("dGVzZGZhZGZzZnNkZg=="), + // }, + // } +} + +// Generated from example definition: 2025-04-01/queryCarbonEmissionsResourceItemDetailsReportWithPaginationToken.json +func ExampleCarbonServiceClient_QueryCarbonEmissionReports_queryCarbonEmissionResourceItemDetailsReportWithPaginationToken() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armcarbonoptimization.NewClientFactory(cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + res, err := clientFactory.NewCarbonServiceClient().QueryCarbonEmissionReports(ctx, armcarbonoptimization.ItemDetailsQueryFilter{ + ReportType: to.Ptr(armcarbonoptimization.ReportTypeEnumItemDetailsReport), + SubscriptionList: []*string{ + to.Ptr("00000000-0000-0000-0000-000000000000"), + to.Ptr("00000000-0000-0000-0000-000000000001,"), + to.Ptr("00000000-0000-0000-0000-000000000002"), + to.Ptr("00000000-0000-0000-0000-000000000003"), + to.Ptr("00000000-0000-0000-0000-000000000004"), + to.Ptr("00000000-0000-0000-0000-000000000005"), + to.Ptr("00000000-0000-0000-0000-000000000006"), + to.Ptr("00000000-0000-0000-0000-000000000007"), + to.Ptr("00000000-0000-0000-0000-000000000008"), + }, + CarbonScopeList: []*armcarbonoptimization.EmissionScopeEnum{ + to.Ptr(armcarbonoptimization.EmissionScopeEnumScope1), + to.Ptr(armcarbonoptimization.EmissionScopeEnumScope3), + }, + DateRange: &armcarbonoptimization.DateRange{ + Start: to.Ptr(func() time.Time { t, _ := time.Parse("2006-01-02", "2024-05-01"); return t }()), + End: to.Ptr(func() time.Time { t, _ := time.Parse("2006-01-02", "2024-05-01"); return t }()), + }, + CategoryType: to.Ptr(armcarbonoptimization.CategoryTypeEnumResource), + OrderBy: to.Ptr(armcarbonoptimization.OrderByColumnEnumLatestMonthEmissions), + SortDirection: to.Ptr(armcarbonoptimization.SortDirectionEnumDesc), + PageSize: to.Ptr[int32](100), + SkipToken: to.Ptr("dGVzZGZhZGZzZnNkZg=="), + }, nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + // You could use response here. We use blank identifier for just demo purposes. + _ = res + // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // res = armcarbonoptimization.CarbonServiceClientQueryCarbonEmissionReportsResponse{ + // CarbonEmissionDataListResult: &armcarbonoptimization.CarbonEmissionDataListResult{ + // SubscriptionAccessDecisionList: []*armcarbonoptimization.SubscriptionAccessDecision{ + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000000"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumAllowed), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000001"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumAllowed), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000002"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumAllowed), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000003"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumAllowed), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000004"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumAllowed), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000005"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumAllowed), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000006"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumDenied), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000007"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumDenied), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000008"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumDenied), + // DenialReason: to.Ptr("Carbon Optimization Reader permisison required"), + // }, + // }, + // Value: []armcarbonoptimization.CarbonEmissionDataClassification{ + // &armcarbonoptimization.ResourceCarbonEmissionItemDetailData{ + // DataType: to.Ptr(armcarbonoptimization.ResponseDataTypeEnumResourceItemDetailsData), + // LatestMonthEmissions: to.Ptr[float64](0.1), + // PreviousMonthEmissions: to.Ptr[float64](0.05), + // MonthOverMonthEmissionsChangeRatio: to.Ptr[float64](1), + // MonthlyEmissionsChangeValue: to.Ptr[float64](0.05), + // ItemName: to.Ptr("rgName1"), + // ResourceGroup: to.Ptr("rgGroup"), + // ResourceID: to.Ptr("/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rgGroup/providers/microsoft.storage/storageaccounts/rgName1"), + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000000"), + // CategoryType: to.Ptr(armcarbonoptimization.CategoryTypeEnumResource), + // ResourceType: to.Ptr("microsoft.storage/storageaccounts"), + // Location: to.Ptr("east us"), + // }, + // &armcarbonoptimization.ResourceCarbonEmissionItemDetailData{ + // DataType: to.Ptr(armcarbonoptimization.ResponseDataTypeEnumResourceItemDetailsData), + // LatestMonthEmissions: to.Ptr[float64](0.1), + // PreviousMonthEmissions: to.Ptr[float64](0.05), + // MonthOverMonthEmissionsChangeRatio: to.Ptr[float64](1), + // MonthlyEmissionsChangeValue: to.Ptr[float64](0.05), + // ItemName: to.Ptr("rgName2"), + // ResourceGroup: to.Ptr("rgGroup"), + // ResourceID: to.Ptr("/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rgGroup/providers/microsoft.storage/storageaccounts/rgName2"), + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000000"), + // CategoryType: to.Ptr(armcarbonoptimization.CategoryTypeEnumResource), + // ResourceType: to.Ptr("microsoft.storage/storageaccounts"), + // Location: to.Ptr("east us"), + // }, + // &armcarbonoptimization.ResourceCarbonEmissionItemDetailData{ + // DataType: to.Ptr(armcarbonoptimization.ResponseDataTypeEnumResourceItemDetailsData), + // LatestMonthEmissions: to.Ptr[float64](0.1), + // PreviousMonthEmissions: to.Ptr[float64](0.05), + // MonthOverMonthEmissionsChangeRatio: to.Ptr[float64](1), + // MonthlyEmissionsChangeValue: to.Ptr[float64](0.05), + // ItemName: to.Ptr("rgName3"), + // ResourceGroup: to.Ptr("rgGroup"), + // ResourceID: to.Ptr("/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rgGroup/providers/microsoft.storage/storageaccounts/rgName3"), + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000000"), + // CategoryType: to.Ptr(armcarbonoptimization.CategoryTypeEnumResource), + // ResourceType: to.Ptr("microsoft.storage/storageaccounts"), + // Location: to.Ptr("east us"), + // }, + // &armcarbonoptimization.ResourceCarbonEmissionItemDetailData{ + // DataType: to.Ptr(armcarbonoptimization.ResponseDataTypeEnumResourceItemDetailsData), + // LatestMonthEmissions: to.Ptr[float64](0.1), + // PreviousMonthEmissions: to.Ptr[float64](0.05), + // MonthOverMonthEmissionsChangeRatio: to.Ptr[float64](1), + // MonthlyEmissionsChangeValue: to.Ptr[float64](0.05), + // ItemName: to.Ptr("rgName4"), + // ResourceGroup: to.Ptr("rgGroup"), + // ResourceID: to.Ptr("/subscriptions/00000000-0000-0000-0000-000000000002/resourceGroups/rgGroup/providers/microsoft.storage/storageaccounts/rgName4"), + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000002"), + // CategoryType: to.Ptr(armcarbonoptimization.CategoryTypeEnumResource), + // ResourceType: to.Ptr("microsoft.storage/storageaccounts"), + // Location: to.Ptr("east us"), + // }, + // &armcarbonoptimization.ResourceCarbonEmissionItemDetailData{ + // DataType: to.Ptr(armcarbonoptimization.ResponseDataTypeEnumResourceItemDetailsData), + // LatestMonthEmissions: to.Ptr[float64](0.1), + // PreviousMonthEmissions: to.Ptr[float64](0.05), + // MonthOverMonthEmissionsChangeRatio: to.Ptr[float64](1), + // MonthlyEmissionsChangeValue: to.Ptr[float64](0.05), + // ItemName: to.Ptr("rgName5"), + // ResourceGroup: to.Ptr("rgGroup"), + // ResourceID: to.Ptr("/subscriptions/00000000-0000-0000-0000-000000000002/resourceGroups/rgGroup/providers/microsoft.storage/storageaccounts/rgName5"), + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000002"), + // CategoryType: to.Ptr(armcarbonoptimization.CategoryTypeEnumResource), + // ResourceType: to.Ptr("microsoft.storage/storageaccounts"), + // Location: to.Ptr("east us"), + // }, + // }, + // }, + // } +} + +// Generated from example definition: 2025-04-01/queryCarbonEmissionsResourceTypeItemDetailsReport.json +func ExampleCarbonServiceClient_QueryCarbonEmissionReports_queryCarbonEmissionResourceTypeItemDetailsReport() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armcarbonoptimization.NewClientFactory(cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + res, err := clientFactory.NewCarbonServiceClient().QueryCarbonEmissionReports(ctx, armcarbonoptimization.ItemDetailsQueryFilter{ + ReportType: to.Ptr(armcarbonoptimization.ReportTypeEnumItemDetailsReport), + SubscriptionList: []*string{ + to.Ptr("00000000-0000-0000-0000-000000000000"), + to.Ptr("00000000-0000-0000-0000-000000000001,"), + to.Ptr("00000000-0000-0000-0000-000000000002"), + to.Ptr("00000000-0000-0000-0000-000000000003"), + to.Ptr("00000000-0000-0000-0000-000000000004"), + to.Ptr("00000000-0000-0000-0000-000000000005"), + to.Ptr("00000000-0000-0000-0000-000000000006"), + to.Ptr("00000000-0000-0000-0000-000000000007"), + to.Ptr("00000000-0000-0000-0000-000000000008"), + }, + CarbonScopeList: []*armcarbonoptimization.EmissionScopeEnum{ + to.Ptr(armcarbonoptimization.EmissionScopeEnumScope1), + to.Ptr(armcarbonoptimization.EmissionScopeEnumScope3), + }, + DateRange: &armcarbonoptimization.DateRange{ + Start: to.Ptr(func() time.Time { t, _ := time.Parse("2006-01-02", "2024-05-01"); return t }()), + End: to.Ptr(func() time.Time { t, _ := time.Parse("2006-01-02", "2024-05-01"); return t }()), + }, + CategoryType: to.Ptr(armcarbonoptimization.CategoryTypeEnumResourceType), + OrderBy: to.Ptr(armcarbonoptimization.OrderByColumnEnumLatestMonthEmissions), + SortDirection: to.Ptr(armcarbonoptimization.SortDirectionEnumDesc), + PageSize: to.Ptr[int32](100), + }, nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + // You could use response here. We use blank identifier for just demo purposes. + _ = res + // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // res = armcarbonoptimization.CarbonServiceClientQueryCarbonEmissionReportsResponse{ + // CarbonEmissionDataListResult: &armcarbonoptimization.CarbonEmissionDataListResult{ + // SubscriptionAccessDecisionList: []*armcarbonoptimization.SubscriptionAccessDecision{ + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000000"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumAllowed), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000001"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumAllowed), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000002"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumAllowed), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000003"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumAllowed), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000004"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumAllowed), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000005"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumAllowed), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000006"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumDenied), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000007"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumDenied), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000008"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumDenied), + // DenialReason: to.Ptr("Carbon Optimization Reader permisison required"), + // }, + // }, + // Value: []armcarbonoptimization.CarbonEmissionDataClassification{ + // &armcarbonoptimization.CarbonEmissionItemDetailData{ + // DataType: to.Ptr(armcarbonoptimization.ResponseDataTypeEnumItemDetailsData), + // LatestMonthEmissions: to.Ptr[float64](0.1), + // PreviousMonthEmissions: to.Ptr[float64](0.05), + // MonthOverMonthEmissionsChangeRatio: to.Ptr[float64](1), + // MonthlyEmissionsChangeValue: to.Ptr[float64](0.05), + // ItemName: to.Ptr("microsoft.storage/storageaccounts"), + // CategoryType: to.Ptr(armcarbonoptimization.CategoryTypeEnumResourceType), + // }, + // &armcarbonoptimization.CarbonEmissionItemDetailData{ + // DataType: to.Ptr(armcarbonoptimization.ResponseDataTypeEnumItemDetailsData), + // LatestMonthEmissions: to.Ptr[float64](0.1), + // PreviousMonthEmissions: to.Ptr[float64](0.05), + // MonthOverMonthEmissionsChangeRatio: to.Ptr[float64](1), + // MonthlyEmissionsChangeValue: to.Ptr[float64](0.05), + // ItemName: to.Ptr("microsoft.compute/disks"), + // CategoryType: to.Ptr(armcarbonoptimization.CategoryTypeEnumResourceType), + // }, + // &armcarbonoptimization.CarbonEmissionItemDetailData{ + // DataType: to.Ptr(armcarbonoptimization.ResponseDataTypeEnumItemDetailsData), + // LatestMonthEmissions: to.Ptr[float64](0.1), + // PreviousMonthEmissions: to.Ptr[float64](0.05), + // MonthOverMonthEmissionsChangeRatio: to.Ptr[float64](1), + // MonthlyEmissionsChangeValue: to.Ptr[float64](0.05), + // ItemName: to.Ptr("microsoft.sql/servers"), + // CategoryType: to.Ptr(armcarbonoptimization.CategoryTypeEnumResourceType), + // }, + // &armcarbonoptimization.CarbonEmissionItemDetailData{ + // DataType: to.Ptr(armcarbonoptimization.ResponseDataTypeEnumItemDetailsData), + // LatestMonthEmissions: to.Ptr[float64](0.1), + // PreviousMonthEmissions: to.Ptr[float64](0.05), + // MonthOverMonthEmissionsChangeRatio: to.Ptr[float64](1), + // MonthlyEmissionsChangeValue: to.Ptr[float64](0.05), + // ItemName: to.Ptr("microsoft.keyvault/vaults"), + // CategoryType: to.Ptr(armcarbonoptimization.CategoryTypeEnumResourceType), + // }, + // &armcarbonoptimization.CarbonEmissionItemDetailData{ + // DataType: to.Ptr(armcarbonoptimization.ResponseDataTypeEnumItemDetailsData), + // LatestMonthEmissions: to.Ptr[float64](0.1), + // PreviousMonthEmissions: to.Ptr[float64](0.05), + // MonthOverMonthEmissionsChangeRatio: to.Ptr[float64](1), + // MonthlyEmissionsChangeValue: to.Ptr[float64](0.05), + // ItemName: to.Ptr("microsoft.compute/virtualmachines"), + // CategoryType: to.Ptr(armcarbonoptimization.CategoryTypeEnumResourceType), + // }, + // }, + // }, + // } +} + +// Generated from example definition: 2025-04-01/queryCarbonEmissionsSubscriptionItemDetailsReportReport.json +func ExampleCarbonServiceClient_QueryCarbonEmissionReports_queryCarbonEmissionSubscriptionsItemDetailsReport() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armcarbonoptimization.NewClientFactory(cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + res, err := clientFactory.NewCarbonServiceClient().QueryCarbonEmissionReports(ctx, armcarbonoptimization.ItemDetailsQueryFilter{ + ReportType: to.Ptr(armcarbonoptimization.ReportTypeEnumItemDetailsReport), + SubscriptionList: []*string{ + to.Ptr("00000000-0000-0000-0000-000000000000"), + to.Ptr("00000000-0000-0000-0000-000000000001,"), + to.Ptr("00000000-0000-0000-0000-000000000002"), + to.Ptr("00000000-0000-0000-0000-000000000003"), + to.Ptr("00000000-0000-0000-0000-000000000004"), + to.Ptr("00000000-0000-0000-0000-000000000005"), + to.Ptr("00000000-0000-0000-0000-000000000006"), + to.Ptr("00000000-0000-0000-0000-000000000007"), + to.Ptr("00000000-0000-0000-0000-000000000008"), + }, + CarbonScopeList: []*armcarbonoptimization.EmissionScopeEnum{ + to.Ptr(armcarbonoptimization.EmissionScopeEnumScope1), + to.Ptr(armcarbonoptimization.EmissionScopeEnumScope3), + }, + DateRange: &armcarbonoptimization.DateRange{ + Start: to.Ptr(func() time.Time { t, _ := time.Parse("2006-01-02", "2024-05-01"); return t }()), + End: to.Ptr(func() time.Time { t, _ := time.Parse("2006-01-02", "2024-05-01"); return t }()), + }, + CategoryType: to.Ptr(armcarbonoptimization.CategoryTypeEnumSubscription), + OrderBy: to.Ptr(armcarbonoptimization.OrderByColumnEnumLatestMonthEmissions), + SortDirection: to.Ptr(armcarbonoptimization.SortDirectionEnumDesc), + PageSize: to.Ptr[int32](100), + }, nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + // You could use response here. We use blank identifier for just demo purposes. + _ = res + // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // res = armcarbonoptimization.CarbonServiceClientQueryCarbonEmissionReportsResponse{ + // CarbonEmissionDataListResult: &armcarbonoptimization.CarbonEmissionDataListResult{ + // SubscriptionAccessDecisionList: []*armcarbonoptimization.SubscriptionAccessDecision{ + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000000"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumAllowed), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000001"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumAllowed), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000002"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumAllowed), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000003"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumAllowed), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000004"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumAllowed), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000005"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumAllowed), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000006"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumDenied), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000007"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumDenied), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000008"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumDenied), + // DenialReason: to.Ptr("Carbon Optimization Reader permisison required"), + // }, + // }, + // Value: []armcarbonoptimization.CarbonEmissionDataClassification{ + // &armcarbonoptimization.CarbonEmissionItemDetailData{ + // DataType: to.Ptr(armcarbonoptimization.ResponseDataTypeEnumItemDetailsData), + // LatestMonthEmissions: to.Ptr[float64](0.1), + // PreviousMonthEmissions: to.Ptr[float64](0.05), + // MonthOverMonthEmissionsChangeRatio: to.Ptr[float64](1), + // MonthlyEmissionsChangeValue: to.Ptr[float64](0.05), + // ItemName: to.Ptr("00000000-0000-0000-0000-000000000000"), + // CategoryType: to.Ptr(armcarbonoptimization.CategoryTypeEnumSubscription), + // }, + // &armcarbonoptimization.CarbonEmissionItemDetailData{ + // DataType: to.Ptr(armcarbonoptimization.ResponseDataTypeEnumItemDetailsData), + // LatestMonthEmissions: to.Ptr[float64](0.1), + // PreviousMonthEmissions: to.Ptr[float64](0.05), + // MonthOverMonthEmissionsChangeRatio: to.Ptr[float64](1), + // MonthlyEmissionsChangeValue: to.Ptr[float64](0.05), + // ItemName: to.Ptr("00000000-0000-0000-0000-000000000001"), + // CategoryType: to.Ptr(armcarbonoptimization.CategoryTypeEnumSubscription), + // }, + // &armcarbonoptimization.CarbonEmissionItemDetailData{ + // DataType: to.Ptr(armcarbonoptimization.ResponseDataTypeEnumItemDetailsData), + // LatestMonthEmissions: to.Ptr[float64](0.1), + // PreviousMonthEmissions: to.Ptr[float64](0.05), + // MonthOverMonthEmissionsChangeRatio: to.Ptr[float64](1), + // MonthlyEmissionsChangeValue: to.Ptr[float64](0.05), + // ItemName: to.Ptr("00000000-0000-0000-0000-000000000002"), + // CategoryType: to.Ptr(armcarbonoptimization.CategoryTypeEnumSubscription), + // }, + // &armcarbonoptimization.CarbonEmissionItemDetailData{ + // DataType: to.Ptr(armcarbonoptimization.ResponseDataTypeEnumItemDetailsData), + // LatestMonthEmissions: to.Ptr[float64](0.1), + // PreviousMonthEmissions: to.Ptr[float64](0.05), + // MonthOverMonthEmissionsChangeRatio: to.Ptr[float64](1), + // MonthlyEmissionsChangeValue: to.Ptr[float64](0.05), + // ItemName: to.Ptr("00000000-0000-0000-0000-000000000003"), + // CategoryType: to.Ptr(armcarbonoptimization.CategoryTypeEnumSubscription), + // }, + // &armcarbonoptimization.CarbonEmissionItemDetailData{ + // DataType: to.Ptr(armcarbonoptimization.ResponseDataTypeEnumItemDetailsData), + // LatestMonthEmissions: to.Ptr[float64](0.1), + // PreviousMonthEmissions: to.Ptr[float64](0.05), + // MonthOverMonthEmissionsChangeRatio: to.Ptr[float64](1), + // MonthlyEmissionsChangeValue: to.Ptr[float64](0.05), + // ItemName: to.Ptr("00000000-0000-0000-0000-000000000004"), + // CategoryType: to.Ptr(armcarbonoptimization.CategoryTypeEnumSubscription), + // }, + // }, + // }, + // } +} + +// Generated from example definition: 2025-04-01/queryCarbonEmissionsTopNLocationItemsMonthlyReport.json +func ExampleCarbonServiceClient_QueryCarbonEmissionReports_queryCarbonEmissionTopNLocationsMonthlyReport() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armcarbonoptimization.NewClientFactory(cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + res, err := clientFactory.NewCarbonServiceClient().QueryCarbonEmissionReports(ctx, armcarbonoptimization.TopItemsMonthlySummaryReportQueryFilter{ + ReportType: to.Ptr(armcarbonoptimization.ReportTypeEnumTopItemsMonthlySummaryReport), + SubscriptionList: []*string{ + to.Ptr("00000000-0000-0000-0000-000000000000"), + to.Ptr("00000000-0000-0000-0000-000000000001,"), + to.Ptr("00000000-0000-0000-0000-000000000002"), + to.Ptr("00000000-0000-0000-0000-000000000003"), + to.Ptr("00000000-0000-0000-0000-000000000004"), + to.Ptr("00000000-0000-0000-0000-000000000005"), + to.Ptr("00000000-0000-0000-0000-000000000006"), + to.Ptr("00000000-0000-0000-0000-000000000007"), + to.Ptr("00000000-0000-0000-0000-000000000008"), + }, + CarbonScopeList: []*armcarbonoptimization.EmissionScopeEnum{ + to.Ptr(armcarbonoptimization.EmissionScopeEnumScope1), + to.Ptr(armcarbonoptimization.EmissionScopeEnumScope3), + }, + DateRange: &armcarbonoptimization.DateRange{ + Start: to.Ptr(func() time.Time { t, _ := time.Parse("2006-01-02", "2024-03-01"); return t }()), + End: to.Ptr(func() time.Time { t, _ := time.Parse("2006-01-02", "2024-05-01"); return t }()), + }, + CategoryType: to.Ptr(armcarbonoptimization.CategoryTypeEnumLocation), + TopItems: to.Ptr[int32](2), + }, nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + // You could use response here. We use blank identifier for just demo purposes. + _ = res + // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // res = armcarbonoptimization.CarbonServiceClientQueryCarbonEmissionReportsResponse{ + // CarbonEmissionDataListResult: &armcarbonoptimization.CarbonEmissionDataListResult{ + // SubscriptionAccessDecisionList: []*armcarbonoptimization.SubscriptionAccessDecision{ + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000000"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumAllowed), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000001"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumAllowed), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000002"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumAllowed), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000003"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumAllowed), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000004"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumAllowed), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000005"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumAllowed), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000006"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumDenied), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000007"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumDenied), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000008"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumDenied), + // DenialReason: to.Ptr("Carbon Optimization Reader permisison required"), + // }, + // }, + // Value: []armcarbonoptimization.CarbonEmissionDataClassification{ + // &armcarbonoptimization.CarbonEmissionTopItemMonthlySummaryData{ + // DataType: to.Ptr(armcarbonoptimization.ResponseDataTypeEnumTopItemsMonthlySummaryData), + // LatestMonthEmissions: to.Ptr[float64](0.1), + // PreviousMonthEmissions: to.Ptr[float64](0.05), + // MonthOverMonthEmissionsChangeRatio: to.Ptr[float64](1), + // MonthlyEmissionsChangeValue: to.Ptr[float64](0.05), + // ItemName: to.Ptr("east us"), + // CategoryType: to.Ptr(armcarbonoptimization.CategoryTypeEnumLocation), + // Date: to.Ptr("2024-05-01"), + // }, + // &armcarbonoptimization.CarbonEmissionTopItemMonthlySummaryData{ + // DataType: to.Ptr(armcarbonoptimization.ResponseDataTypeEnumTopItemsMonthlySummaryData), + // LatestMonthEmissions: to.Ptr[float64](0.1), + // PreviousMonthEmissions: to.Ptr[float64](0.05), + // MonthOverMonthEmissionsChangeRatio: to.Ptr[float64](1), + // MonthlyEmissionsChangeValue: to.Ptr[float64](0.05), + // ItemName: to.Ptr("east us"), + // CategoryType: to.Ptr(armcarbonoptimization.CategoryTypeEnumLocation), + // Date: to.Ptr("2024-04-01"), + // }, + // &armcarbonoptimization.CarbonEmissionTopItemMonthlySummaryData{ + // DataType: to.Ptr(armcarbonoptimization.ResponseDataTypeEnumTopItemsMonthlySummaryData), + // LatestMonthEmissions: to.Ptr[float64](0.1), + // PreviousMonthEmissions: to.Ptr[float64](0.05), + // MonthOverMonthEmissionsChangeRatio: to.Ptr[float64](1), + // MonthlyEmissionsChangeValue: to.Ptr[float64](0.05), + // ItemName: to.Ptr("east us"), + // CategoryType: to.Ptr(armcarbonoptimization.CategoryTypeEnumLocation), + // Date: to.Ptr("2024-03-01"), + // }, + // &armcarbonoptimization.CarbonEmissionTopItemMonthlySummaryData{ + // DataType: to.Ptr(armcarbonoptimization.ResponseDataTypeEnumTopItemsMonthlySummaryData), + // LatestMonthEmissions: to.Ptr[float64](0.1), + // PreviousMonthEmissions: to.Ptr[float64](0.05), + // MonthOverMonthEmissionsChangeRatio: to.Ptr[float64](1), + // MonthlyEmissionsChangeValue: to.Ptr[float64](0.05), + // ItemName: to.Ptr("west us"), + // CategoryType: to.Ptr(armcarbonoptimization.CategoryTypeEnumLocation), + // Date: to.Ptr("2024-05-01"), + // }, + // &armcarbonoptimization.CarbonEmissionTopItemMonthlySummaryData{ + // DataType: to.Ptr(armcarbonoptimization.ResponseDataTypeEnumTopItemsMonthlySummaryData), + // LatestMonthEmissions: to.Ptr[float64](0.1), + // PreviousMonthEmissions: to.Ptr[float64](0.05), + // MonthOverMonthEmissionsChangeRatio: to.Ptr[float64](1), + // MonthlyEmissionsChangeValue: to.Ptr[float64](0.05), + // ItemName: to.Ptr("west us"), + // CategoryType: to.Ptr(armcarbonoptimization.CategoryTypeEnumLocation), + // Date: to.Ptr("2024-04-01"), + // }, + // &armcarbonoptimization.CarbonEmissionTopItemMonthlySummaryData{ + // DataType: to.Ptr(armcarbonoptimization.ResponseDataTypeEnumTopItemsMonthlySummaryData), + // LatestMonthEmissions: to.Ptr[float64](0.1), + // PreviousMonthEmissions: to.Ptr[float64](0.05), + // MonthOverMonthEmissionsChangeRatio: to.Ptr[float64](1), + // MonthlyEmissionsChangeValue: to.Ptr[float64](0.05), + // ItemName: to.Ptr("west us"), + // CategoryType: to.Ptr(armcarbonoptimization.CategoryTypeEnumLocation), + // Date: to.Ptr("2024-03-01"), + // }, + // }, + // }, + // } +} + +// Generated from example definition: 2025-04-01/queryCarbonEmissionsTopNLocationItemsReport.json +func ExampleCarbonServiceClient_QueryCarbonEmissionReports_queryCarbonEmissionTopNLocationsReport() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armcarbonoptimization.NewClientFactory(cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + res, err := clientFactory.NewCarbonServiceClient().QueryCarbonEmissionReports(ctx, armcarbonoptimization.TopItemsSummaryReportQueryFilter{ + ReportType: to.Ptr(armcarbonoptimization.ReportTypeEnumTopItemsSummaryReport), + SubscriptionList: []*string{ + to.Ptr("00000000-0000-0000-0000-000000000000"), + to.Ptr("00000000-0000-0000-0000-000000000001,"), + to.Ptr("00000000-0000-0000-0000-000000000002"), + to.Ptr("00000000-0000-0000-0000-000000000003"), + to.Ptr("00000000-0000-0000-0000-000000000004"), + to.Ptr("00000000-0000-0000-0000-000000000005"), + to.Ptr("00000000-0000-0000-0000-000000000006"), + to.Ptr("00000000-0000-0000-0000-000000000007"), + to.Ptr("00000000-0000-0000-0000-000000000008"), + }, + CarbonScopeList: []*armcarbonoptimization.EmissionScopeEnum{ + to.Ptr(armcarbonoptimization.EmissionScopeEnumScope1), + to.Ptr(armcarbonoptimization.EmissionScopeEnumScope3), + }, + DateRange: &armcarbonoptimization.DateRange{ + Start: to.Ptr(func() time.Time { t, _ := time.Parse("2006-01-02", "2024-05-01"); return t }()), + End: to.Ptr(func() time.Time { t, _ := time.Parse("2006-01-02", "2024-05-01"); return t }()), + }, + CategoryType: to.Ptr(armcarbonoptimization.CategoryTypeEnumLocation), + TopItems: to.Ptr[int32](5), + }, nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + // You could use response here. We use blank identifier for just demo purposes. + _ = res + // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // res = armcarbonoptimization.CarbonServiceClientQueryCarbonEmissionReportsResponse{ + // CarbonEmissionDataListResult: &armcarbonoptimization.CarbonEmissionDataListResult{ + // SubscriptionAccessDecisionList: []*armcarbonoptimization.SubscriptionAccessDecision{ + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000000"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumAllowed), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000001"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumAllowed), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000002"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumAllowed), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000003"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumAllowed), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000004"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumAllowed), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000005"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumAllowed), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000006"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumDenied), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000007"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumDenied), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000008"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumDenied), + // DenialReason: to.Ptr("Carbon Optimization Reader permisison required"), + // }, + // }, + // Value: []armcarbonoptimization.CarbonEmissionDataClassification{ + // &armcarbonoptimization.CarbonEmissionTopItemsSummaryData{ + // DataType: to.Ptr(armcarbonoptimization.ResponseDataTypeEnumTopItemsSummaryData), + // LatestMonthEmissions: to.Ptr[float64](0.1), + // PreviousMonthEmissions: to.Ptr[float64](0.05), + // MonthOverMonthEmissionsChangeRatio: to.Ptr[float64](1), + // MonthlyEmissionsChangeValue: to.Ptr[float64](0.05), + // ItemName: to.Ptr("east us"), + // CategoryType: to.Ptr(armcarbonoptimization.CategoryTypeEnumLocation), + // }, + // &armcarbonoptimization.CarbonEmissionTopItemsSummaryData{ + // DataType: to.Ptr(armcarbonoptimization.ResponseDataTypeEnumTopItemsSummaryData), + // LatestMonthEmissions: to.Ptr[float64](0.1), + // PreviousMonthEmissions: to.Ptr[float64](0.05), + // MonthOverMonthEmissionsChangeRatio: to.Ptr[float64](1), + // MonthlyEmissionsChangeValue: to.Ptr[float64](0.05), + // ItemName: to.Ptr("west us"), + // CategoryType: to.Ptr(armcarbonoptimization.CategoryTypeEnumLocation), + // }, + // &armcarbonoptimization.CarbonEmissionTopItemsSummaryData{ + // DataType: to.Ptr(armcarbonoptimization.ResponseDataTypeEnumTopItemsSummaryData), + // LatestMonthEmissions: to.Ptr[float64](0.1), + // PreviousMonthEmissions: to.Ptr[float64](0.05), + // MonthOverMonthEmissionsChangeRatio: to.Ptr[float64](1), + // MonthlyEmissionsChangeValue: to.Ptr[float64](0.05), + // ItemName: to.Ptr("west us 2"), + // CategoryType: to.Ptr(armcarbonoptimization.CategoryTypeEnumLocation), + // }, + // &armcarbonoptimization.CarbonEmissionTopItemsSummaryData{ + // DataType: to.Ptr(armcarbonoptimization.ResponseDataTypeEnumTopItemsSummaryData), + // LatestMonthEmissions: to.Ptr[float64](0.1), + // PreviousMonthEmissions: to.Ptr[float64](0.05), + // MonthOverMonthEmissionsChangeRatio: to.Ptr[float64](1), + // MonthlyEmissionsChangeValue: to.Ptr[float64](0.05), + // ItemName: to.Ptr("west us 3"), + // CategoryType: to.Ptr(armcarbonoptimization.CategoryTypeEnumLocation), + // }, + // &armcarbonoptimization.CarbonEmissionTopItemsSummaryData{ + // DataType: to.Ptr(armcarbonoptimization.ResponseDataTypeEnumTopItemsSummaryData), + // LatestMonthEmissions: to.Ptr[float64](0.1), + // PreviousMonthEmissions: to.Ptr[float64](0.05), + // MonthOverMonthEmissionsChangeRatio: to.Ptr[float64](1), + // MonthlyEmissionsChangeValue: to.Ptr[float64](0.05), + // ItemName: to.Ptr("east us 2"), + // CategoryType: to.Ptr(armcarbonoptimization.CategoryTypeEnumLocation), + // }, + // }, + // }, + // } +} + +// Generated from example definition: 2025-04-01/queryCarbonEmissionsTopNResourceGroupItemsMonthlyReport.json +func ExampleCarbonServiceClient_QueryCarbonEmissionReports_queryCarbonEmissionTopNResourceGroupMonthlyReport() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armcarbonoptimization.NewClientFactory(cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + res, err := clientFactory.NewCarbonServiceClient().QueryCarbonEmissionReports(ctx, armcarbonoptimization.TopItemsMonthlySummaryReportQueryFilter{ + ReportType: to.Ptr(armcarbonoptimization.ReportTypeEnumTopItemsMonthlySummaryReport), + SubscriptionList: []*string{ + to.Ptr("00000000-0000-0000-0000-000000000000"), + to.Ptr("00000000-0000-0000-0000-000000000001,"), + to.Ptr("00000000-0000-0000-0000-000000000002"), + to.Ptr("00000000-0000-0000-0000-000000000003"), + to.Ptr("00000000-0000-0000-0000-000000000004"), + to.Ptr("00000000-0000-0000-0000-000000000005"), + to.Ptr("00000000-0000-0000-0000-000000000006"), + to.Ptr("00000000-0000-0000-0000-000000000007"), + to.Ptr("00000000-0000-0000-0000-000000000008"), + }, + CarbonScopeList: []*armcarbonoptimization.EmissionScopeEnum{ + to.Ptr(armcarbonoptimization.EmissionScopeEnumScope1), + to.Ptr(armcarbonoptimization.EmissionScopeEnumScope3), + }, + DateRange: &armcarbonoptimization.DateRange{ + Start: to.Ptr(func() time.Time { t, _ := time.Parse("2006-01-02", "2024-03-01"); return t }()), + End: to.Ptr(func() time.Time { t, _ := time.Parse("2006-01-02", "2024-05-01"); return t }()), + }, + CategoryType: to.Ptr(armcarbonoptimization.CategoryTypeEnumResourceGroup), + TopItems: to.Ptr[int32](2), + }, nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + // You could use response here. We use blank identifier for just demo purposes. + _ = res + // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // res = armcarbonoptimization.CarbonServiceClientQueryCarbonEmissionReportsResponse{ + // CarbonEmissionDataListResult: &armcarbonoptimization.CarbonEmissionDataListResult{ + // SubscriptionAccessDecisionList: []*armcarbonoptimization.SubscriptionAccessDecision{ + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000000"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumAllowed), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000001"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumAllowed), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000002"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumAllowed), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000003"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumAllowed), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000004"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumAllowed), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000005"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumAllowed), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000006"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumDenied), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000007"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumDenied), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000008"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumDenied), + // DenialReason: to.Ptr("Carbon Optimization Reader permisison required"), + // }, + // }, + // Value: []armcarbonoptimization.CarbonEmissionDataClassification{ + // &armcarbonoptimization.ResourceGroupCarbonEmissionTopItemMonthlySummaryData{ + // DataType: to.Ptr(armcarbonoptimization.ResponseDataTypeEnumResourceGroupTopItemsMonthlySummaryData), + // LatestMonthEmissions: to.Ptr[float64](0.1), + // PreviousMonthEmissions: to.Ptr[float64](0.05), + // MonthOverMonthEmissionsChangeRatio: to.Ptr[float64](1), + // MonthlyEmissionsChangeValue: to.Ptr[float64](0.05), + // ItemName: to.Ptr("rgGroup1"), + // ResourceGroupURL: to.Ptr("/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rgGroup1"), + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000000"), + // CategoryType: to.Ptr(armcarbonoptimization.CategoryTypeEnumResourceGroup), + // Date: to.Ptr("2024-05-01"), + // }, + // &armcarbonoptimization.ResourceGroupCarbonEmissionTopItemMonthlySummaryData{ + // DataType: to.Ptr(armcarbonoptimization.ResponseDataTypeEnumResourceGroupTopItemsMonthlySummaryData), + // LatestMonthEmissions: to.Ptr[float64](0.1), + // PreviousMonthEmissions: to.Ptr[float64](0.05), + // MonthOverMonthEmissionsChangeRatio: to.Ptr[float64](1), + // MonthlyEmissionsChangeValue: to.Ptr[float64](0.05), + // ItemName: to.Ptr("rgGroup1"), + // ResourceGroupURL: to.Ptr("/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rgGroup1"), + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000000"), + // CategoryType: to.Ptr(armcarbonoptimization.CategoryTypeEnumResourceGroup), + // Date: to.Ptr("2024-04-01"), + // }, + // &armcarbonoptimization.ResourceGroupCarbonEmissionTopItemMonthlySummaryData{ + // DataType: to.Ptr(armcarbonoptimization.ResponseDataTypeEnumResourceGroupTopItemsMonthlySummaryData), + // LatestMonthEmissions: to.Ptr[float64](0.1), + // PreviousMonthEmissions: to.Ptr[float64](0.05), + // MonthOverMonthEmissionsChangeRatio: to.Ptr[float64](1), + // MonthlyEmissionsChangeValue: to.Ptr[float64](0.05), + // ItemName: to.Ptr("rgGroup1"), + // ResourceGroupURL: to.Ptr("/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rgGroup1"), + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000000"), + // CategoryType: to.Ptr(armcarbonoptimization.CategoryTypeEnumResourceGroup), + // Date: to.Ptr("2024-03-01"), + // }, + // &armcarbonoptimization.ResourceGroupCarbonEmissionTopItemMonthlySummaryData{ + // DataType: to.Ptr(armcarbonoptimization.ResponseDataTypeEnumResourceGroupTopItemsMonthlySummaryData), + // LatestMonthEmissions: to.Ptr[float64](0.1), + // PreviousMonthEmissions: to.Ptr[float64](0.05), + // MonthOverMonthEmissionsChangeRatio: to.Ptr[float64](1), + // MonthlyEmissionsChangeValue: to.Ptr[float64](0.05), + // ItemName: to.Ptr("rgGroup2"), + // ResourceGroupURL: to.Ptr("/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rgGroup2"), + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000000"), + // CategoryType: to.Ptr(armcarbonoptimization.CategoryTypeEnumResourceGroup), + // Date: to.Ptr("2024-05-01"), + // }, + // &armcarbonoptimization.ResourceGroupCarbonEmissionTopItemMonthlySummaryData{ + // DataType: to.Ptr(armcarbonoptimization.ResponseDataTypeEnumResourceGroupTopItemsMonthlySummaryData), + // LatestMonthEmissions: to.Ptr[float64](0.1), + // PreviousMonthEmissions: to.Ptr[float64](0.05), + // MonthOverMonthEmissionsChangeRatio: to.Ptr[float64](1), + // MonthlyEmissionsChangeValue: to.Ptr[float64](0.05), + // ItemName: to.Ptr("rgGroup2"), + // ResourceGroupURL: to.Ptr("/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rgGroup2"), + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000000"), + // CategoryType: to.Ptr(armcarbonoptimization.CategoryTypeEnumResourceGroup), + // Date: to.Ptr("2024-04-01"), + // }, + // &armcarbonoptimization.ResourceGroupCarbonEmissionTopItemMonthlySummaryData{ + // DataType: to.Ptr(armcarbonoptimization.ResponseDataTypeEnumResourceGroupTopItemsMonthlySummaryData), + // LatestMonthEmissions: to.Ptr[float64](0.1), + // PreviousMonthEmissions: to.Ptr[float64](0.05), + // MonthOverMonthEmissionsChangeRatio: to.Ptr[float64](1), + // MonthlyEmissionsChangeValue: to.Ptr[float64](0.05), + // ItemName: to.Ptr("rgGroup2"), + // ResourceGroupURL: to.Ptr("/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rgGroup2"), + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000000"), + // CategoryType: to.Ptr(armcarbonoptimization.CategoryTypeEnumResourceGroup), + // Date: to.Ptr("2024-03-01"), + // }, + // }, + // }, + // } +} + +// Generated from example definition: 2025-04-01/queryCarbonEmissionsTopNResourceGroupItemsReport.json +func ExampleCarbonServiceClient_QueryCarbonEmissionReports_queryCarbonEmissionTopNResourceGroupReport() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armcarbonoptimization.NewClientFactory(cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + res, err := clientFactory.NewCarbonServiceClient().QueryCarbonEmissionReports(ctx, armcarbonoptimization.TopItemsSummaryReportQueryFilter{ + ReportType: to.Ptr(armcarbonoptimization.ReportTypeEnumTopItemsSummaryReport), + SubscriptionList: []*string{ + to.Ptr("00000000-0000-0000-0000-000000000000"), + to.Ptr("00000000-0000-0000-0000-000000000001,"), + to.Ptr("00000000-0000-0000-0000-000000000002"), + to.Ptr("00000000-0000-0000-0000-000000000003"), + to.Ptr("00000000-0000-0000-0000-000000000004"), + to.Ptr("00000000-0000-0000-0000-000000000005"), + to.Ptr("00000000-0000-0000-0000-000000000006"), + to.Ptr("00000000-0000-0000-0000-000000000007"), + to.Ptr("00000000-0000-0000-0000-000000000008"), + }, + CarbonScopeList: []*armcarbonoptimization.EmissionScopeEnum{ + to.Ptr(armcarbonoptimization.EmissionScopeEnumScope1), + to.Ptr(armcarbonoptimization.EmissionScopeEnumScope3), + }, + DateRange: &armcarbonoptimization.DateRange{ + Start: to.Ptr(func() time.Time { t, _ := time.Parse("2006-01-02", "2024-05-01"); return t }()), + End: to.Ptr(func() time.Time { t, _ := time.Parse("2006-01-02", "2024-05-01"); return t }()), + }, + CategoryType: to.Ptr(armcarbonoptimization.CategoryTypeEnumResourceGroup), + TopItems: to.Ptr[int32](5), + }, nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + // You could use response here. We use blank identifier for just demo purposes. + _ = res + // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // res = armcarbonoptimization.CarbonServiceClientQueryCarbonEmissionReportsResponse{ + // CarbonEmissionDataListResult: &armcarbonoptimization.CarbonEmissionDataListResult{ + // SubscriptionAccessDecisionList: []*armcarbonoptimization.SubscriptionAccessDecision{ + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000000"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumAllowed), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000001"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumAllowed), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000002"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumAllowed), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000003"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumAllowed), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000004"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumAllowed), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000005"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumAllowed), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000006"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumDenied), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000007"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumDenied), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000008"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumDenied), + // DenialReason: to.Ptr("Carbon Optimization Reader permisison required"), + // }, + // }, + // Value: []armcarbonoptimization.CarbonEmissionDataClassification{ + // &armcarbonoptimization.ResourceGroupCarbonEmissionTopItemsSummaryData{ + // DataType: to.Ptr(armcarbonoptimization.ResponseDataTypeEnumResourceGroupTopItemsSummaryData), + // LatestMonthEmissions: to.Ptr[float64](0.1), + // PreviousMonthEmissions: to.Ptr[float64](0.05), + // MonthOverMonthEmissionsChangeRatio: to.Ptr[float64](1), + // MonthlyEmissionsChangeValue: to.Ptr[float64](0.05), + // ItemName: to.Ptr("rgGroup1"), + // ResourceGroupURL: to.Ptr("/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rgGroup1"), + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000000"), + // CategoryType: to.Ptr(armcarbonoptimization.CategoryTypeEnumResourceGroup), + // }, + // &armcarbonoptimization.ResourceGroupCarbonEmissionTopItemsSummaryData{ + // DataType: to.Ptr(armcarbonoptimization.ResponseDataTypeEnumResourceGroupTopItemsSummaryData), + // LatestMonthEmissions: to.Ptr[float64](0.1), + // PreviousMonthEmissions: to.Ptr[float64](0.05), + // MonthOverMonthEmissionsChangeRatio: to.Ptr[float64](1), + // MonthlyEmissionsChangeValue: to.Ptr[float64](0.05), + // ItemName: to.Ptr("rgGroup2"), + // ResourceGroupURL: to.Ptr("/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rgGroup2"), + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000000"), + // CategoryType: to.Ptr(armcarbonoptimization.CategoryTypeEnumResourceGroup), + // }, + // &armcarbonoptimization.ResourceGroupCarbonEmissionTopItemsSummaryData{ + // DataType: to.Ptr(armcarbonoptimization.ResponseDataTypeEnumResourceGroupTopItemsSummaryData), + // LatestMonthEmissions: to.Ptr[float64](0.1), + // PreviousMonthEmissions: to.Ptr[float64](0.05), + // MonthOverMonthEmissionsChangeRatio: to.Ptr[float64](1), + // MonthlyEmissionsChangeValue: to.Ptr[float64](0.05), + // ItemName: to.Ptr("rgGroup3"), + // ResourceGroupURL: to.Ptr("/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rgGroup3"), + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000000"), + // CategoryType: to.Ptr(armcarbonoptimization.CategoryTypeEnumResourceGroup), + // }, + // &armcarbonoptimization.ResourceGroupCarbonEmissionTopItemsSummaryData{ + // DataType: to.Ptr(armcarbonoptimization.ResponseDataTypeEnumResourceGroupTopItemsSummaryData), + // LatestMonthEmissions: to.Ptr[float64](0.1), + // PreviousMonthEmissions: to.Ptr[float64](0.05), + // MonthOverMonthEmissionsChangeRatio: to.Ptr[float64](1), + // MonthlyEmissionsChangeValue: to.Ptr[float64](0.05), + // ItemName: to.Ptr("rgGroup4"), + // ResourceGroupURL: to.Ptr("/subscriptions/00000000-0000-0000-0000-000000000002/resourceGroups/rgGroup4"), + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000002"), + // CategoryType: to.Ptr(armcarbonoptimization.CategoryTypeEnumResourceGroup), + // }, + // &armcarbonoptimization.ResourceGroupCarbonEmissionTopItemsSummaryData{ + // DataType: to.Ptr(armcarbonoptimization.ResponseDataTypeEnumResourceGroupTopItemsSummaryData), + // LatestMonthEmissions: to.Ptr[float64](0.1), + // PreviousMonthEmissions: to.Ptr[float64](0.05), + // MonthOverMonthEmissionsChangeRatio: to.Ptr[float64](1), + // MonthlyEmissionsChangeValue: to.Ptr[float64](0.05), + // ItemName: to.Ptr("rgGroup5"), + // ResourceGroupURL: to.Ptr("/subscriptions/00000000-0000-0000-0000-000000000002/resourceGroups/rgGroup5"), + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000002"), + // CategoryType: to.Ptr(armcarbonoptimization.CategoryTypeEnumResourceGroup), + // }, + // }, + // }, + // } +} + +// Generated from example definition: 2025-04-01/queryCarbonEmissionsTopNResourceItemsMonthlyReport.json +func ExampleCarbonServiceClient_QueryCarbonEmissionReports_queryCarbonEmissionTopNResourceMonthlyReport() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armcarbonoptimization.NewClientFactory(cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + res, err := clientFactory.NewCarbonServiceClient().QueryCarbonEmissionReports(ctx, armcarbonoptimization.TopItemsMonthlySummaryReportQueryFilter{ + ReportType: to.Ptr(armcarbonoptimization.ReportTypeEnumTopItemsMonthlySummaryReport), + SubscriptionList: []*string{ + to.Ptr("00000000-0000-0000-0000-000000000000"), + to.Ptr("00000000-0000-0000-0000-000000000001,"), + to.Ptr("00000000-0000-0000-0000-000000000002"), + to.Ptr("00000000-0000-0000-0000-000000000003"), + to.Ptr("00000000-0000-0000-0000-000000000004"), + to.Ptr("00000000-0000-0000-0000-000000000005"), + to.Ptr("00000000-0000-0000-0000-000000000006"), + to.Ptr("00000000-0000-0000-0000-000000000007"), + to.Ptr("00000000-0000-0000-0000-000000000008"), + }, + CarbonScopeList: []*armcarbonoptimization.EmissionScopeEnum{ + to.Ptr(armcarbonoptimization.EmissionScopeEnumScope1), + to.Ptr(armcarbonoptimization.EmissionScopeEnumScope3), + }, + DateRange: &armcarbonoptimization.DateRange{ + Start: to.Ptr(func() time.Time { t, _ := time.Parse("2006-01-02", "2024-03-01"); return t }()), + End: to.Ptr(func() time.Time { t, _ := time.Parse("2006-01-02", "2024-05-01"); return t }()), + }, + CategoryType: to.Ptr(armcarbonoptimization.CategoryTypeEnumResource), + TopItems: to.Ptr[int32](2), + }, nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + // You could use response here. We use blank identifier for just demo purposes. + _ = res + // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // res = armcarbonoptimization.CarbonServiceClientQueryCarbonEmissionReportsResponse{ + // CarbonEmissionDataListResult: &armcarbonoptimization.CarbonEmissionDataListResult{ + // SubscriptionAccessDecisionList: []*armcarbonoptimization.SubscriptionAccessDecision{ + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000000"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumAllowed), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000001"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumAllowed), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000002"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumAllowed), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000003"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumAllowed), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000004"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumAllowed), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000005"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumAllowed), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000006"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumDenied), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000007"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumDenied), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000008"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumDenied), + // DenialReason: to.Ptr("Carbon Optimization Reader permisison required"), + // }, + // }, + // Value: []armcarbonoptimization.CarbonEmissionDataClassification{ + // &armcarbonoptimization.ResourceCarbonEmissionTopItemMonthlySummaryData{ + // DataType: to.Ptr(armcarbonoptimization.ResponseDataTypeEnumResourceTopItemsMonthlySummaryData), + // LatestMonthEmissions: to.Ptr[float64](0.1), + // PreviousMonthEmissions: to.Ptr[float64](0.05), + // MonthOverMonthEmissionsChangeRatio: to.Ptr[float64](1), + // MonthlyEmissionsChangeValue: to.Ptr[float64](0.05), + // ItemName: to.Ptr("rgName1"), + // ResourceGroup: to.Ptr("rgGroup"), + // ResourceID: to.Ptr("/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rgGroup/providers/microsoft.storage/storageaccounts/rgName1"), + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000000"), + // CategoryType: to.Ptr(armcarbonoptimization.CategoryTypeEnumResource), + // Date: to.Ptr("2024-05-01"), + // }, + // &armcarbonoptimization.ResourceCarbonEmissionTopItemMonthlySummaryData{ + // DataType: to.Ptr(armcarbonoptimization.ResponseDataTypeEnumResourceTopItemsMonthlySummaryData), + // LatestMonthEmissions: to.Ptr[float64](0.1), + // PreviousMonthEmissions: to.Ptr[float64](0.05), + // MonthOverMonthEmissionsChangeRatio: to.Ptr[float64](1), + // MonthlyEmissionsChangeValue: to.Ptr[float64](0.05), + // ItemName: to.Ptr("rgName1"), + // ResourceGroup: to.Ptr("rgGroup"), + // ResourceID: to.Ptr("/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rgGroup/providers/microsoft.storage/storageaccounts/rgName1"), + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000000"), + // CategoryType: to.Ptr(armcarbonoptimization.CategoryTypeEnumResource), + // Date: to.Ptr("2024-04-01"), + // }, + // &armcarbonoptimization.ResourceCarbonEmissionTopItemMonthlySummaryData{ + // DataType: to.Ptr(armcarbonoptimization.ResponseDataTypeEnumResourceTopItemsMonthlySummaryData), + // LatestMonthEmissions: to.Ptr[float64](0.1), + // PreviousMonthEmissions: to.Ptr[float64](0.05), + // MonthOverMonthEmissionsChangeRatio: to.Ptr[float64](1), + // MonthlyEmissionsChangeValue: to.Ptr[float64](0.05), + // ItemName: to.Ptr("rgName1"), + // ResourceGroup: to.Ptr("rgGroup"), + // ResourceID: to.Ptr("/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rgGroup/providers/microsoft.storage/storageaccounts/rgName1"), + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000000"), + // CategoryType: to.Ptr(armcarbonoptimization.CategoryTypeEnumResource), + // Date: to.Ptr("2024-03-01"), + // }, + // &armcarbonoptimization.ResourceCarbonEmissionTopItemMonthlySummaryData{ + // DataType: to.Ptr(armcarbonoptimization.ResponseDataTypeEnumResourceTopItemsMonthlySummaryData), + // LatestMonthEmissions: to.Ptr[float64](0.1), + // PreviousMonthEmissions: to.Ptr[float64](0.05), + // MonthOverMonthEmissionsChangeRatio: to.Ptr[float64](1), + // MonthlyEmissionsChangeValue: to.Ptr[float64](0.05), + // ItemName: to.Ptr("rgName2"), + // ResourceGroup: to.Ptr("rgGroup"), + // ResourceID: to.Ptr("/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rgGroup/providers/microsoft.storage/storageaccounts/rgName2"), + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000000"), + // CategoryType: to.Ptr(armcarbonoptimization.CategoryTypeEnumResource), + // Date: to.Ptr("2024-05-01"), + // }, + // &armcarbonoptimization.ResourceCarbonEmissionTopItemMonthlySummaryData{ + // DataType: to.Ptr(armcarbonoptimization.ResponseDataTypeEnumResourceTopItemsMonthlySummaryData), + // LatestMonthEmissions: to.Ptr[float64](0.1), + // PreviousMonthEmissions: to.Ptr[float64](0.05), + // MonthOverMonthEmissionsChangeRatio: to.Ptr[float64](1), + // MonthlyEmissionsChangeValue: to.Ptr[float64](0.05), + // ItemName: to.Ptr("rgName2"), + // ResourceGroup: to.Ptr("rgGroup"), + // ResourceID: to.Ptr("/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rgGroup/providers/microsoft.storage/storageaccounts/rgName2"), + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000000"), + // CategoryType: to.Ptr(armcarbonoptimization.CategoryTypeEnumResource), + // Date: to.Ptr("2024-04-01"), + // }, + // &armcarbonoptimization.ResourceCarbonEmissionTopItemMonthlySummaryData{ + // DataType: to.Ptr(armcarbonoptimization.ResponseDataTypeEnumResourceTopItemsMonthlySummaryData), + // LatestMonthEmissions: to.Ptr[float64](0.1), + // PreviousMonthEmissions: to.Ptr[float64](0.05), + // MonthOverMonthEmissionsChangeRatio: to.Ptr[float64](1), + // MonthlyEmissionsChangeValue: to.Ptr[float64](0.05), + // ItemName: to.Ptr("rgName2"), + // ResourceGroup: to.Ptr("rgGroup"), + // ResourceID: to.Ptr("/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rgGroup/providers/microsoft.storage/storageaccounts/rgName2"), + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000000"), + // CategoryType: to.Ptr(armcarbonoptimization.CategoryTypeEnumResource), + // Date: to.Ptr("2024-03-01"), + // }, + // }, + // }, + // } +} + +// Generated from example definition: 2025-04-01/queryCarbonEmissionsTopNResourceItemsReport.json +func ExampleCarbonServiceClient_QueryCarbonEmissionReports_queryCarbonEmissionTopNResourceReport() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armcarbonoptimization.NewClientFactory(cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + res, err := clientFactory.NewCarbonServiceClient().QueryCarbonEmissionReports(ctx, armcarbonoptimization.TopItemsSummaryReportQueryFilter{ + ReportType: to.Ptr(armcarbonoptimization.ReportTypeEnumTopItemsSummaryReport), + SubscriptionList: []*string{ + to.Ptr("00000000-0000-0000-0000-000000000000"), + to.Ptr("00000000-0000-0000-0000-000000000001,"), + to.Ptr("00000000-0000-0000-0000-000000000002"), + to.Ptr("00000000-0000-0000-0000-000000000003"), + to.Ptr("00000000-0000-0000-0000-000000000004"), + to.Ptr("00000000-0000-0000-0000-000000000005"), + to.Ptr("00000000-0000-0000-0000-000000000006"), + to.Ptr("00000000-0000-0000-0000-000000000007"), + to.Ptr("00000000-0000-0000-0000-000000000008"), + }, + CarbonScopeList: []*armcarbonoptimization.EmissionScopeEnum{ + to.Ptr(armcarbonoptimization.EmissionScopeEnumScope1), + to.Ptr(armcarbonoptimization.EmissionScopeEnumScope3), + }, + DateRange: &armcarbonoptimization.DateRange{ + Start: to.Ptr(func() time.Time { t, _ := time.Parse("2006-01-02", "2024-05-01"); return t }()), + End: to.Ptr(func() time.Time { t, _ := time.Parse("2006-01-02", "2024-05-01"); return t }()), + }, + CategoryType: to.Ptr(armcarbonoptimization.CategoryTypeEnumResource), + TopItems: to.Ptr[int32](5), + }, nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + // You could use response here. We use blank identifier for just demo purposes. + _ = res + // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // res = armcarbonoptimization.CarbonServiceClientQueryCarbonEmissionReportsResponse{ + // CarbonEmissionDataListResult: &armcarbonoptimization.CarbonEmissionDataListResult{ + // SubscriptionAccessDecisionList: []*armcarbonoptimization.SubscriptionAccessDecision{ + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000000"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumAllowed), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000001"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumAllowed), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000002"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumAllowed), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000003"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumAllowed), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000004"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumAllowed), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000005"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumAllowed), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000006"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumDenied), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000007"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumDenied), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000008"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumDenied), + // DenialReason: to.Ptr("Carbon Optimization Reader permisison required"), + // }, + // }, + // Value: []armcarbonoptimization.CarbonEmissionDataClassification{ + // &armcarbonoptimization.ResourceCarbonEmissionTopItemsSummaryData{ + // DataType: to.Ptr(armcarbonoptimization.ResponseDataTypeEnumResourceTopItemsSummaryData), + // LatestMonthEmissions: to.Ptr[float64](0.1), + // PreviousMonthEmissions: to.Ptr[float64](0.05), + // MonthOverMonthEmissionsChangeRatio: to.Ptr[float64](1), + // MonthlyEmissionsChangeValue: to.Ptr[float64](0.05), + // ItemName: to.Ptr("rgName1"), + // ResourceGroup: to.Ptr("rgGroup"), + // ResourceID: to.Ptr("/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rgGroup/providers/microsoft.storage/storageaccounts/rgName1"), + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000000"), + // CategoryType: to.Ptr(armcarbonoptimization.CategoryTypeEnumResource), + // }, + // &armcarbonoptimization.ResourceCarbonEmissionTopItemsSummaryData{ + // DataType: to.Ptr(armcarbonoptimization.ResponseDataTypeEnumResourceTopItemsSummaryData), + // LatestMonthEmissions: to.Ptr[float64](0.1), + // PreviousMonthEmissions: to.Ptr[float64](0.05), + // MonthOverMonthEmissionsChangeRatio: to.Ptr[float64](1), + // MonthlyEmissionsChangeValue: to.Ptr[float64](0.05), + // ItemName: to.Ptr("rgName2"), + // ResourceGroup: to.Ptr("rgGroup"), + // ResourceID: to.Ptr("/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rgGroup/providers/microsoft.storage/storageaccounts/rgName2"), + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000000"), + // CategoryType: to.Ptr(armcarbonoptimization.CategoryTypeEnumResource), + // }, + // &armcarbonoptimization.ResourceCarbonEmissionTopItemsSummaryData{ + // DataType: to.Ptr(armcarbonoptimization.ResponseDataTypeEnumResourceTopItemsSummaryData), + // LatestMonthEmissions: to.Ptr[float64](0.1), + // PreviousMonthEmissions: to.Ptr[float64](0.05), + // MonthOverMonthEmissionsChangeRatio: to.Ptr[float64](1), + // MonthlyEmissionsChangeValue: to.Ptr[float64](0.05), + // ItemName: to.Ptr("rgName3"), + // ResourceGroup: to.Ptr("rgGroup"), + // ResourceID: to.Ptr("/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rgGroup/providers/microsoft.storage/storageaccounts/rgName3"), + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000000"), + // CategoryType: to.Ptr(armcarbonoptimization.CategoryTypeEnumResource), + // }, + // &armcarbonoptimization.ResourceCarbonEmissionTopItemsSummaryData{ + // DataType: to.Ptr(armcarbonoptimization.ResponseDataTypeEnumResourceTopItemsSummaryData), + // LatestMonthEmissions: to.Ptr[float64](0.1), + // PreviousMonthEmissions: to.Ptr[float64](0.05), + // MonthOverMonthEmissionsChangeRatio: to.Ptr[float64](1), + // MonthlyEmissionsChangeValue: to.Ptr[float64](0.05), + // ItemName: to.Ptr("rgName4"), + // ResourceGroup: to.Ptr("rgGroup"), + // ResourceID: to.Ptr("/subscriptions/00000000-0000-0000-0000-000000000002/resourceGroups/rgGroup/providers/microsoft.storage/storageaccounts/rgName4"), + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000002"), + // CategoryType: to.Ptr(armcarbonoptimization.CategoryTypeEnumResource), + // }, + // &armcarbonoptimization.ResourceCarbonEmissionTopItemsSummaryData{ + // DataType: to.Ptr(armcarbonoptimization.ResponseDataTypeEnumResourceTopItemsSummaryData), + // LatestMonthEmissions: to.Ptr[float64](0.1), + // PreviousMonthEmissions: to.Ptr[float64](0.05), + // MonthOverMonthEmissionsChangeRatio: to.Ptr[float64](1), + // MonthlyEmissionsChangeValue: to.Ptr[float64](0.05), + // ItemName: to.Ptr("rgName5"), + // ResourceGroup: to.Ptr("rgGroup"), + // ResourceID: to.Ptr("/subscriptions/00000000-0000-0000-0000-000000000002/resourceGroups/rgGroup/providers/microsoft.storage/storageaccounts/rgName5"), + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000002"), + // CategoryType: to.Ptr(armcarbonoptimization.CategoryTypeEnumResource), + // }, + // }, + // }, + // } +} + +// Generated from example definition: 2025-04-01/queryCarbonEmissionsTopNResourceTypeItemsMonthlyReport.json +func ExampleCarbonServiceClient_QueryCarbonEmissionReports_queryCarbonEmissionTopNResourceTypeMonthlyReport() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armcarbonoptimization.NewClientFactory(cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + res, err := clientFactory.NewCarbonServiceClient().QueryCarbonEmissionReports(ctx, armcarbonoptimization.TopItemsMonthlySummaryReportQueryFilter{ + ReportType: to.Ptr(armcarbonoptimization.ReportTypeEnumTopItemsMonthlySummaryReport), + SubscriptionList: []*string{ + to.Ptr("00000000-0000-0000-0000-000000000000"), + to.Ptr("00000000-0000-0000-0000-000000000001,"), + to.Ptr("00000000-0000-0000-0000-000000000002"), + to.Ptr("00000000-0000-0000-0000-000000000003"), + to.Ptr("00000000-0000-0000-0000-000000000004"), + to.Ptr("00000000-0000-0000-0000-000000000005"), + to.Ptr("00000000-0000-0000-0000-000000000006"), + to.Ptr("00000000-0000-0000-0000-000000000007"), + to.Ptr("00000000-0000-0000-0000-000000000008"), + }, + CarbonScopeList: []*armcarbonoptimization.EmissionScopeEnum{ + to.Ptr(armcarbonoptimization.EmissionScopeEnumScope1), + to.Ptr(armcarbonoptimization.EmissionScopeEnumScope3), + }, + DateRange: &armcarbonoptimization.DateRange{ + Start: to.Ptr(func() time.Time { t, _ := time.Parse("2006-01-02", "2024-03-01"); return t }()), + End: to.Ptr(func() time.Time { t, _ := time.Parse("2006-01-02", "2024-05-01"); return t }()), + }, + CategoryType: to.Ptr(armcarbonoptimization.CategoryTypeEnumResourceType), + TopItems: to.Ptr[int32](2), + }, nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + // You could use response here. We use blank identifier for just demo purposes. + _ = res + // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // res = armcarbonoptimization.CarbonServiceClientQueryCarbonEmissionReportsResponse{ + // CarbonEmissionDataListResult: &armcarbonoptimization.CarbonEmissionDataListResult{ + // SubscriptionAccessDecisionList: []*armcarbonoptimization.SubscriptionAccessDecision{ + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000000"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumAllowed), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000001"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumAllowed), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000002"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumAllowed), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000003"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumAllowed), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000004"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumAllowed), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000005"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumAllowed), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000006"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumDenied), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000007"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumDenied), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000008"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumDenied), + // DenialReason: to.Ptr("Carbon Optimization Reader permisison required"), + // }, + // }, + // Value: []armcarbonoptimization.CarbonEmissionDataClassification{ + // &armcarbonoptimization.CarbonEmissionTopItemMonthlySummaryData{ + // DataType: to.Ptr(armcarbonoptimization.ResponseDataTypeEnumTopItemsMonthlySummaryData), + // LatestMonthEmissions: to.Ptr[float64](0.1), + // PreviousMonthEmissions: to.Ptr[float64](0.05), + // MonthOverMonthEmissionsChangeRatio: to.Ptr[float64](1), + // MonthlyEmissionsChangeValue: to.Ptr[float64](0.05), + // ItemName: to.Ptr("microsoft.storage/storageaccounts"), + // CategoryType: to.Ptr(armcarbonoptimization.CategoryTypeEnumResourceType), + // Date: to.Ptr("2024-05-01"), + // }, + // &armcarbonoptimization.CarbonEmissionTopItemMonthlySummaryData{ + // DataType: to.Ptr(armcarbonoptimization.ResponseDataTypeEnumTopItemsMonthlySummaryData), + // LatestMonthEmissions: to.Ptr[float64](0.1), + // PreviousMonthEmissions: to.Ptr[float64](0.05), + // MonthOverMonthEmissionsChangeRatio: to.Ptr[float64](1), + // MonthlyEmissionsChangeValue: to.Ptr[float64](0.05), + // ItemName: to.Ptr("microsoft.storage/storageaccounts"), + // CategoryType: to.Ptr(armcarbonoptimization.CategoryTypeEnumResourceType), + // Date: to.Ptr("2024-04-01"), + // }, + // &armcarbonoptimization.CarbonEmissionTopItemMonthlySummaryData{ + // DataType: to.Ptr(armcarbonoptimization.ResponseDataTypeEnumTopItemsMonthlySummaryData), + // LatestMonthEmissions: to.Ptr[float64](0.1), + // PreviousMonthEmissions: to.Ptr[float64](0.05), + // MonthOverMonthEmissionsChangeRatio: to.Ptr[float64](1), + // MonthlyEmissionsChangeValue: to.Ptr[float64](0.05), + // ItemName: to.Ptr("microsoft.storage/storageaccounts"), + // CategoryType: to.Ptr(armcarbonoptimization.CategoryTypeEnumResourceType), + // Date: to.Ptr("2024-03-01"), + // }, + // &armcarbonoptimization.CarbonEmissionTopItemMonthlySummaryData{ + // DataType: to.Ptr(armcarbonoptimization.ResponseDataTypeEnumTopItemsMonthlySummaryData), + // LatestMonthEmissions: to.Ptr[float64](0.1), + // PreviousMonthEmissions: to.Ptr[float64](0.05), + // MonthOverMonthEmissionsChangeRatio: to.Ptr[float64](1), + // MonthlyEmissionsChangeValue: to.Ptr[float64](0.05), + // ItemName: to.Ptr("microsoft.compute/disks"), + // CategoryType: to.Ptr(armcarbonoptimization.CategoryTypeEnumResourceType), + // Date: to.Ptr("2024-05-01"), + // }, + // &armcarbonoptimization.CarbonEmissionTopItemMonthlySummaryData{ + // DataType: to.Ptr(armcarbonoptimization.ResponseDataTypeEnumTopItemsMonthlySummaryData), + // LatestMonthEmissions: to.Ptr[float64](0.1), + // PreviousMonthEmissions: to.Ptr[float64](0.05), + // MonthOverMonthEmissionsChangeRatio: to.Ptr[float64](1), + // MonthlyEmissionsChangeValue: to.Ptr[float64](0.05), + // ItemName: to.Ptr("microsoft.compute/disks"), + // CategoryType: to.Ptr(armcarbonoptimization.CategoryTypeEnumResourceType), + // Date: to.Ptr("2024-04-01"), + // }, + // &armcarbonoptimization.CarbonEmissionTopItemMonthlySummaryData{ + // DataType: to.Ptr(armcarbonoptimization.ResponseDataTypeEnumTopItemsMonthlySummaryData), + // LatestMonthEmissions: to.Ptr[float64](0.1), + // PreviousMonthEmissions: to.Ptr[float64](0.05), + // MonthOverMonthEmissionsChangeRatio: to.Ptr[float64](1), + // MonthlyEmissionsChangeValue: to.Ptr[float64](0.05), + // ItemName: to.Ptr("microsoft.compute/disks"), + // CategoryType: to.Ptr(armcarbonoptimization.CategoryTypeEnumResourceType), + // Date: to.Ptr("2024-03-01"), + // }, + // }, + // }, + // } +} + +// Generated from example definition: 2025-04-01/queryCarbonEmissionsTopNResourceTypeItemsReport.json +func ExampleCarbonServiceClient_QueryCarbonEmissionReports_queryCarbonEmissionTopNResourceTypeReport() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armcarbonoptimization.NewClientFactory(cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + res, err := clientFactory.NewCarbonServiceClient().QueryCarbonEmissionReports(ctx, armcarbonoptimization.TopItemsSummaryReportQueryFilter{ + ReportType: to.Ptr(armcarbonoptimization.ReportTypeEnumTopItemsSummaryReport), + SubscriptionList: []*string{ + to.Ptr("00000000-0000-0000-0000-000000000000"), + to.Ptr("00000000-0000-0000-0000-000000000001,"), + to.Ptr("00000000-0000-0000-0000-000000000002"), + to.Ptr("00000000-0000-0000-0000-000000000003"), + to.Ptr("00000000-0000-0000-0000-000000000004"), + to.Ptr("00000000-0000-0000-0000-000000000005"), + to.Ptr("00000000-0000-0000-0000-000000000006"), + to.Ptr("00000000-0000-0000-0000-000000000007"), + to.Ptr("00000000-0000-0000-0000-000000000008"), + }, + CarbonScopeList: []*armcarbonoptimization.EmissionScopeEnum{ + to.Ptr(armcarbonoptimization.EmissionScopeEnumScope1), + to.Ptr(armcarbonoptimization.EmissionScopeEnumScope3), + }, + DateRange: &armcarbonoptimization.DateRange{ + Start: to.Ptr(func() time.Time { t, _ := time.Parse("2006-01-02", "2024-05-01"); return t }()), + End: to.Ptr(func() time.Time { t, _ := time.Parse("2006-01-02", "2024-05-01"); return t }()), + }, + CategoryType: to.Ptr(armcarbonoptimization.CategoryTypeEnumResourceType), + TopItems: to.Ptr[int32](5), + }, nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + // You could use response here. We use blank identifier for just demo purposes. + _ = res + // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // res = armcarbonoptimization.CarbonServiceClientQueryCarbonEmissionReportsResponse{ + // CarbonEmissionDataListResult: &armcarbonoptimization.CarbonEmissionDataListResult{ + // SubscriptionAccessDecisionList: []*armcarbonoptimization.SubscriptionAccessDecision{ + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000000"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumAllowed), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000001"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumAllowed), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000002"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumAllowed), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000003"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumAllowed), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000004"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumAllowed), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000005"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumAllowed), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000006"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumDenied), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000007"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumDenied), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000008"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumDenied), + // DenialReason: to.Ptr("Carbon Optimization Reader permisison required"), + // }, + // }, + // Value: []armcarbonoptimization.CarbonEmissionDataClassification{ + // &armcarbonoptimization.CarbonEmissionTopItemsSummaryData{ + // DataType: to.Ptr(armcarbonoptimization.ResponseDataTypeEnumTopItemsSummaryData), + // LatestMonthEmissions: to.Ptr[float64](0.1), + // PreviousMonthEmissions: to.Ptr[float64](0.05), + // MonthOverMonthEmissionsChangeRatio: to.Ptr[float64](1), + // MonthlyEmissionsChangeValue: to.Ptr[float64](0.05), + // ItemName: to.Ptr("microsoft.storage/storageaccounts"), + // CategoryType: to.Ptr(armcarbonoptimization.CategoryTypeEnumResourceType), + // }, + // &armcarbonoptimization.CarbonEmissionTopItemsSummaryData{ + // DataType: to.Ptr(armcarbonoptimization.ResponseDataTypeEnumTopItemsSummaryData), + // LatestMonthEmissions: to.Ptr[float64](0.1), + // PreviousMonthEmissions: to.Ptr[float64](0.05), + // MonthOverMonthEmissionsChangeRatio: to.Ptr[float64](1), + // MonthlyEmissionsChangeValue: to.Ptr[float64](0.05), + // ItemName: to.Ptr("microsoft.compute/disks"), + // CategoryType: to.Ptr(armcarbonoptimization.CategoryTypeEnumResourceType), + // }, + // &armcarbonoptimization.CarbonEmissionTopItemsSummaryData{ + // DataType: to.Ptr(armcarbonoptimization.ResponseDataTypeEnumTopItemsSummaryData), + // LatestMonthEmissions: to.Ptr[float64](0.1), + // PreviousMonthEmissions: to.Ptr[float64](0.05), + // MonthOverMonthEmissionsChangeRatio: to.Ptr[float64](1), + // MonthlyEmissionsChangeValue: to.Ptr[float64](0.05), + // ItemName: to.Ptr("microsoft.sql/servers"), + // CategoryType: to.Ptr(armcarbonoptimization.CategoryTypeEnumResourceType), + // }, + // &armcarbonoptimization.CarbonEmissionTopItemsSummaryData{ + // DataType: to.Ptr(armcarbonoptimization.ResponseDataTypeEnumTopItemsSummaryData), + // LatestMonthEmissions: to.Ptr[float64](0.1), + // PreviousMonthEmissions: to.Ptr[float64](0.05), + // MonthOverMonthEmissionsChangeRatio: to.Ptr[float64](1), + // MonthlyEmissionsChangeValue: to.Ptr[float64](0.05), + // ItemName: to.Ptr("microsoft.keyvault/vaults"), + // CategoryType: to.Ptr(armcarbonoptimization.CategoryTypeEnumResourceType), + // }, + // &armcarbonoptimization.CarbonEmissionTopItemsSummaryData{ + // DataType: to.Ptr(armcarbonoptimization.ResponseDataTypeEnumTopItemsSummaryData), + // LatestMonthEmissions: to.Ptr[float64](0.1), + // PreviousMonthEmissions: to.Ptr[float64](0.05), + // MonthOverMonthEmissionsChangeRatio: to.Ptr[float64](1), + // MonthlyEmissionsChangeValue: to.Ptr[float64](0.05), + // ItemName: to.Ptr("microsoft.compute/virtualmachines"), + // CategoryType: to.Ptr(armcarbonoptimization.CategoryTypeEnumResourceType), + // }, + // }, + // }, + // } +} + +// Generated from example definition: 2025-04-01/queryCarbonEmissionsTopNSubscriptionItemsMonthlyReport.json +func ExampleCarbonServiceClient_QueryCarbonEmissionReports_queryCarbonEmissionTopNSubscriptionsMonthlyReport() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armcarbonoptimization.NewClientFactory(cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + res, err := clientFactory.NewCarbonServiceClient().QueryCarbonEmissionReports(ctx, armcarbonoptimization.TopItemsMonthlySummaryReportQueryFilter{ + ReportType: to.Ptr(armcarbonoptimization.ReportTypeEnumTopItemsMonthlySummaryReport), + SubscriptionList: []*string{ + to.Ptr("00000000-0000-0000-0000-000000000000"), + to.Ptr("00000000-0000-0000-0000-000000000001,"), + to.Ptr("00000000-0000-0000-0000-000000000002"), + to.Ptr("00000000-0000-0000-0000-000000000003"), + to.Ptr("00000000-0000-0000-0000-000000000004"), + to.Ptr("00000000-0000-0000-0000-000000000005"), + to.Ptr("00000000-0000-0000-0000-000000000006"), + to.Ptr("00000000-0000-0000-0000-000000000007"), + to.Ptr("00000000-0000-0000-0000-000000000008"), + }, + CarbonScopeList: []*armcarbonoptimization.EmissionScopeEnum{ + to.Ptr(armcarbonoptimization.EmissionScopeEnumScope1), + to.Ptr(armcarbonoptimization.EmissionScopeEnumScope3), + }, + DateRange: &armcarbonoptimization.DateRange{ + Start: to.Ptr(func() time.Time { t, _ := time.Parse("2006-01-02", "2024-03-01"); return t }()), + End: to.Ptr(func() time.Time { t, _ := time.Parse("2006-01-02", "2024-05-01"); return t }()), + }, + CategoryType: to.Ptr(armcarbonoptimization.CategoryTypeEnumSubscription), + TopItems: to.Ptr[int32](2), + }, nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + // You could use response here. We use blank identifier for just demo purposes. + _ = res + // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // res = armcarbonoptimization.CarbonServiceClientQueryCarbonEmissionReportsResponse{ + // CarbonEmissionDataListResult: &armcarbonoptimization.CarbonEmissionDataListResult{ + // SubscriptionAccessDecisionList: []*armcarbonoptimization.SubscriptionAccessDecision{ + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000000"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumAllowed), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000001"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumAllowed), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000002"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumAllowed), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000003"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumAllowed), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000004"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumAllowed), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000005"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumAllowed), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000006"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumDenied), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000007"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumDenied), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000008"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumDenied), + // DenialReason: to.Ptr("Carbon Optimization Reader permisison required"), + // }, + // }, + // Value: []armcarbonoptimization.CarbonEmissionDataClassification{ + // &armcarbonoptimization.CarbonEmissionTopItemMonthlySummaryData{ + // DataType: to.Ptr(armcarbonoptimization.ResponseDataTypeEnumTopItemsMonthlySummaryData), + // LatestMonthEmissions: to.Ptr[float64](0.1), + // PreviousMonthEmissions: to.Ptr[float64](0.05), + // MonthOverMonthEmissionsChangeRatio: to.Ptr[float64](1), + // MonthlyEmissionsChangeValue: to.Ptr[float64](0.05), + // ItemName: to.Ptr("00000000-0000-0000-0000-000000000000"), + // CategoryType: to.Ptr(armcarbonoptimization.CategoryTypeEnumSubscription), + // Date: to.Ptr("2024-05-01"), + // }, + // &armcarbonoptimization.CarbonEmissionTopItemMonthlySummaryData{ + // DataType: to.Ptr(armcarbonoptimization.ResponseDataTypeEnumTopItemsMonthlySummaryData), + // LatestMonthEmissions: to.Ptr[float64](0.1), + // PreviousMonthEmissions: to.Ptr[float64](0.05), + // MonthOverMonthEmissionsChangeRatio: to.Ptr[float64](1), + // MonthlyEmissionsChangeValue: to.Ptr[float64](0.05), + // ItemName: to.Ptr("00000000-0000-0000-0000-000000000000"), + // CategoryType: to.Ptr(armcarbonoptimization.CategoryTypeEnumSubscription), + // Date: to.Ptr("2024-04-01"), + // }, + // &armcarbonoptimization.CarbonEmissionTopItemMonthlySummaryData{ + // DataType: to.Ptr(armcarbonoptimization.ResponseDataTypeEnumTopItemsMonthlySummaryData), + // LatestMonthEmissions: to.Ptr[float64](0.1), + // PreviousMonthEmissions: to.Ptr[float64](0.05), + // MonthOverMonthEmissionsChangeRatio: to.Ptr[float64](1), + // MonthlyEmissionsChangeValue: to.Ptr[float64](0.05), + // ItemName: to.Ptr("00000000-0000-0000-0000-000000000000"), + // CategoryType: to.Ptr(armcarbonoptimization.CategoryTypeEnumSubscription), + // Date: to.Ptr("2024-03-01"), + // }, + // &armcarbonoptimization.CarbonEmissionTopItemMonthlySummaryData{ + // DataType: to.Ptr(armcarbonoptimization.ResponseDataTypeEnumTopItemsMonthlySummaryData), + // LatestMonthEmissions: to.Ptr[float64](0.1), + // PreviousMonthEmissions: to.Ptr[float64](0.05), + // MonthOverMonthEmissionsChangeRatio: to.Ptr[float64](1), + // MonthlyEmissionsChangeValue: to.Ptr[float64](0.05), + // ItemName: to.Ptr("00000000-0000-0000-0000-000000000001"), + // CategoryType: to.Ptr(armcarbonoptimization.CategoryTypeEnumSubscription), + // Date: to.Ptr("2024-05-01"), + // }, + // &armcarbonoptimization.CarbonEmissionTopItemMonthlySummaryData{ + // DataType: to.Ptr(armcarbonoptimization.ResponseDataTypeEnumTopItemsMonthlySummaryData), + // LatestMonthEmissions: to.Ptr[float64](0.1), + // PreviousMonthEmissions: to.Ptr[float64](0.05), + // MonthOverMonthEmissionsChangeRatio: to.Ptr[float64](1), + // MonthlyEmissionsChangeValue: to.Ptr[float64](0.05), + // ItemName: to.Ptr("00000000-0000-0000-0000-000000000001"), + // CategoryType: to.Ptr(armcarbonoptimization.CategoryTypeEnumSubscription), + // Date: to.Ptr("2024-04-01"), + // }, + // &armcarbonoptimization.CarbonEmissionTopItemMonthlySummaryData{ + // DataType: to.Ptr(armcarbonoptimization.ResponseDataTypeEnumTopItemsMonthlySummaryData), + // LatestMonthEmissions: to.Ptr[float64](0.1), + // PreviousMonthEmissions: to.Ptr[float64](0.05), + // MonthOverMonthEmissionsChangeRatio: to.Ptr[float64](1), + // MonthlyEmissionsChangeValue: to.Ptr[float64](0.05), + // ItemName: to.Ptr("00000000-0000-0000-0000-000000000001"), + // CategoryType: to.Ptr(armcarbonoptimization.CategoryTypeEnumSubscription), + // Date: to.Ptr("2024-03-01"), + // }, + // }, + // }, + // } +} + +// Generated from example definition: 2025-04-01/queryCarbonEmissionsTopNSubscriptionItemsReport.json +func ExampleCarbonServiceClient_QueryCarbonEmissionReports_queryCarbonEmissionTopNSubscriptionsReport() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armcarbonoptimization.NewClientFactory(cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + res, err := clientFactory.NewCarbonServiceClient().QueryCarbonEmissionReports(ctx, armcarbonoptimization.TopItemsSummaryReportQueryFilter{ + ReportType: to.Ptr(armcarbonoptimization.ReportTypeEnumTopItemsSummaryReport), + SubscriptionList: []*string{ + to.Ptr("00000000-0000-0000-0000-000000000000"), + to.Ptr("00000000-0000-0000-0000-000000000001,"), + to.Ptr("00000000-0000-0000-0000-000000000002"), + to.Ptr("00000000-0000-0000-0000-000000000003"), + to.Ptr("00000000-0000-0000-0000-000000000004"), + to.Ptr("00000000-0000-0000-0000-000000000005"), + to.Ptr("00000000-0000-0000-0000-000000000006"), + to.Ptr("00000000-0000-0000-0000-000000000007"), + to.Ptr("00000000-0000-0000-0000-000000000008"), + }, + CarbonScopeList: []*armcarbonoptimization.EmissionScopeEnum{ + to.Ptr(armcarbonoptimization.EmissionScopeEnumScope1), + to.Ptr(armcarbonoptimization.EmissionScopeEnumScope3), + }, + DateRange: &armcarbonoptimization.DateRange{ + Start: to.Ptr(func() time.Time { t, _ := time.Parse("2006-01-02", "2024-05-01"); return t }()), + End: to.Ptr(func() time.Time { t, _ := time.Parse("2006-01-02", "2024-05-01"); return t }()), + }, + CategoryType: to.Ptr(armcarbonoptimization.CategoryTypeEnumSubscription), + TopItems: to.Ptr[int32](5), + }, nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + // You could use response here. We use blank identifier for just demo purposes. + _ = res + // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // res = armcarbonoptimization.CarbonServiceClientQueryCarbonEmissionReportsResponse{ + // CarbonEmissionDataListResult: &armcarbonoptimization.CarbonEmissionDataListResult{ + // SubscriptionAccessDecisionList: []*armcarbonoptimization.SubscriptionAccessDecision{ + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000000"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumAllowed), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000001"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumAllowed), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000002"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumAllowed), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000003"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumAllowed), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000004"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumAllowed), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000005"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumAllowed), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000006"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumDenied), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000007"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumDenied), + // }, + // { + // SubscriptionID: to.Ptr("00000000-0000-0000-0000-000000000008"), + // Decision: to.Ptr(armcarbonoptimization.AccessDecisionEnumDenied), + // DenialReason: to.Ptr("Carbon Optimization Reader permisison required"), + // }, + // }, + // Value: []armcarbonoptimization.CarbonEmissionDataClassification{ + // &armcarbonoptimization.CarbonEmissionTopItemsSummaryData{ + // DataType: to.Ptr(armcarbonoptimization.ResponseDataTypeEnumTopItemsSummaryData), + // LatestMonthEmissions: to.Ptr[float64](0.1), + // PreviousMonthEmissions: to.Ptr[float64](0.05), + // MonthOverMonthEmissionsChangeRatio: to.Ptr[float64](1), + // MonthlyEmissionsChangeValue: to.Ptr[float64](0.05), + // ItemName: to.Ptr("00000000-0000-0000-0000-000000000000"), + // CategoryType: to.Ptr(armcarbonoptimization.CategoryTypeEnumSubscription), + // }, + // &armcarbonoptimization.CarbonEmissionTopItemsSummaryData{ + // DataType: to.Ptr(armcarbonoptimization.ResponseDataTypeEnumTopItemsSummaryData), + // LatestMonthEmissions: to.Ptr[float64](0.1), + // PreviousMonthEmissions: to.Ptr[float64](0.05), + // MonthOverMonthEmissionsChangeRatio: to.Ptr[float64](1), + // MonthlyEmissionsChangeValue: to.Ptr[float64](0.05), + // ItemName: to.Ptr("00000000-0000-0000-0000-000000000001"), + // CategoryType: to.Ptr(armcarbonoptimization.CategoryTypeEnumSubscription), + // }, + // &armcarbonoptimization.CarbonEmissionTopItemsSummaryData{ + // DataType: to.Ptr(armcarbonoptimization.ResponseDataTypeEnumTopItemsSummaryData), + // LatestMonthEmissions: to.Ptr[float64](0.1), + // PreviousMonthEmissions: to.Ptr[float64](0.05), + // MonthOverMonthEmissionsChangeRatio: to.Ptr[float64](1), + // MonthlyEmissionsChangeValue: to.Ptr[float64](0.05), + // ItemName: to.Ptr("00000000-0000-0000-0000-000000000002"), + // CategoryType: to.Ptr(armcarbonoptimization.CategoryTypeEnumSubscription), + // }, + // &armcarbonoptimization.CarbonEmissionTopItemsSummaryData{ + // DataType: to.Ptr(armcarbonoptimization.ResponseDataTypeEnumTopItemsSummaryData), + // LatestMonthEmissions: to.Ptr[float64](0.1), + // PreviousMonthEmissions: to.Ptr[float64](0.05), + // MonthOverMonthEmissionsChangeRatio: to.Ptr[float64](1), + // MonthlyEmissionsChangeValue: to.Ptr[float64](0.05), + // ItemName: to.Ptr("00000000-0000-0000-0000-000000000003"), + // CategoryType: to.Ptr(armcarbonoptimization.CategoryTypeEnumSubscription), + // }, + // &armcarbonoptimization.CarbonEmissionTopItemsSummaryData{ + // DataType: to.Ptr(armcarbonoptimization.ResponseDataTypeEnumTopItemsSummaryData), + // LatestMonthEmissions: to.Ptr[float64](0.1), + // PreviousMonthEmissions: to.Ptr[float64](0.05), + // MonthOverMonthEmissionsChangeRatio: to.Ptr[float64](1), + // MonthlyEmissionsChangeValue: to.Ptr[float64](0.05), + // ItemName: to.Ptr("00000000-0000-0000-0000-000000000004"), + // CategoryType: to.Ptr(armcarbonoptimization.CategoryTypeEnumSubscription), + // }, + // }, + // }, + // } +} diff --git a/sdk/resourcemanager/carbonoptimization/armcarbonoptimization/ci.yml b/sdk/resourcemanager/carbonoptimization/armcarbonoptimization/ci.yml new file mode 100644 index 000000000000..976f5628da99 --- /dev/null +++ b/sdk/resourcemanager/carbonoptimization/armcarbonoptimization/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/carbonoptimization/armcarbonoptimization/ + +pr: + branches: + include: + - main + - feature/* + - hotfix/* + - release/* + paths: + include: + - sdk/resourcemanager/carbonoptimization/armcarbonoptimization/ + +extends: + template: /eng/pipelines/templates/jobs/archetype-sdk-client.yml + parameters: + ServiceDirectory: 'resourcemanager/carbonoptimization/armcarbonoptimization' diff --git a/sdk/resourcemanager/carbonoptimization/armcarbonoptimization/client_factory.go b/sdk/resourcemanager/carbonoptimization/armcarbonoptimization/client_factory.go new file mode 100644 index 000000000000..4a6f1fff0ea7 --- /dev/null +++ b/sdk/resourcemanager/carbonoptimization/armcarbonoptimization/client_factory.go @@ -0,0 +1,44 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcarbonoptimization + +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 { + 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. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - pass nil to accept the default values. +func NewClientFactory(credential azcore.TokenCredential, options *arm.ClientOptions) (*ClientFactory, error) { + internal, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + return &ClientFactory{ + internal: internal, + }, nil +} + +// NewCarbonServiceClient creates a new instance of CarbonServiceClient. +func (c *ClientFactory) NewCarbonServiceClient() *CarbonServiceClient { + return &CarbonServiceClient{ + internal: c.internal, + } +} + +// NewOperationsClient creates a new instance of OperationsClient. +func (c *ClientFactory) NewOperationsClient() *OperationsClient { + return &OperationsClient{ + internal: c.internal, + } +} diff --git a/sdk/resourcemanager/carbonoptimization/armcarbonoptimization/constants.go b/sdk/resourcemanager/carbonoptimization/armcarbonoptimization/constants.go new file mode 100644 index 000000000000..38c6191238d3 --- /dev/null +++ b/sdk/resourcemanager/carbonoptimization/armcarbonoptimization/constants.go @@ -0,0 +1,252 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcarbonoptimization + +const ( + moduleName = "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/carbonoptimization/armcarbonoptimization" + moduleVersion = "v0.1.0" +) + +// AccessDecisionEnum - Enum for Access Decision +type AccessDecisionEnum string + +const ( + // AccessDecisionEnumAllowed - Access allowed + AccessDecisionEnumAllowed AccessDecisionEnum = "Allowed" + // AccessDecisionEnumDenied - Access denied + AccessDecisionEnumDenied AccessDecisionEnum = "Denied" +) + +// PossibleAccessDecisionEnumValues returns the possible values for the AccessDecisionEnum const type. +func PossibleAccessDecisionEnumValues() []AccessDecisionEnum { + return []AccessDecisionEnum{ + AccessDecisionEnumAllowed, + AccessDecisionEnumDenied, + } +} + +// ActionType - Extensible enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. +type ActionType string + +const ( + // ActionTypeInternal - Actions are for internal-only APIs. + ActionTypeInternal ActionType = "Internal" +) + +// PossibleActionTypeValues returns the possible values for the ActionType const type. +func PossibleActionTypeValues() []ActionType { + return []ActionType{ + ActionTypeInternal, + } +} + +// CategoryTypeEnum - Supported category types to be used with QueryParameter. Each type represents a different level of emissions +// data aggregation. +type CategoryTypeEnum string + +const ( + // CategoryTypeEnumLocation - Emissions aggregated at the location level. + CategoryTypeEnumLocation CategoryTypeEnum = "Location" + // CategoryTypeEnumResource - Emissions aggregated at the resource level. + CategoryTypeEnumResource CategoryTypeEnum = "Resource" + // CategoryTypeEnumResourceGroup - Emissions aggregated at the resource group level. + CategoryTypeEnumResourceGroup CategoryTypeEnum = "ResourceGroup" + // CategoryTypeEnumResourceType - Emissions aggregated at the resource type level. + CategoryTypeEnumResourceType CategoryTypeEnum = "ResourceType" + // CategoryTypeEnumSubscription - Emissions aggregated at the subscription level. + CategoryTypeEnumSubscription CategoryTypeEnum = "Subscription" +) + +// PossibleCategoryTypeEnumValues returns the possible values for the CategoryTypeEnum const type. +func PossibleCategoryTypeEnumValues() []CategoryTypeEnum { + return []CategoryTypeEnum{ + CategoryTypeEnumLocation, + CategoryTypeEnumResource, + CategoryTypeEnumResourceGroup, + CategoryTypeEnumResourceType, + CategoryTypeEnumSubscription, + } +} + +// EmissionScopeEnum - Supported carbon emission scopes to be used with QueryParameter, as defined by the GHG Protocol. At +// least one scope must be specified. The output will return a total of all specified scopes. +type EmissionScopeEnum string + +const ( + // EmissionScopeEnumScope1 - Scope1 carbon emission + EmissionScopeEnumScope1 EmissionScopeEnum = "Scope1" + // EmissionScopeEnumScope2 - Scope2 carbon emission + EmissionScopeEnumScope2 EmissionScopeEnum = "Scope2" + // EmissionScopeEnumScope3 - Scope3 carbon emission + EmissionScopeEnumScope3 EmissionScopeEnum = "Scope3" +) + +// PossibleEmissionScopeEnumValues returns the possible values for the EmissionScopeEnum const type. +func PossibleEmissionScopeEnumValues() []EmissionScopeEnum { + return []EmissionScopeEnum{ + EmissionScopeEnumScope1, + EmissionScopeEnumScope2, + EmissionScopeEnumScope3, + } +} + +// OrderByColumnEnum - Sorting is supported for columns in ItemDetailsReport. This object includes the column names that sorting +// is allowed for. Select one of these supported values +type OrderByColumnEnum string + +const ( + // OrderByColumnEnumItemName - The itemName filed in ItemDetailsReport result, see CarbonEmissionItemDetailData for more information. + OrderByColumnEnumItemName OrderByColumnEnum = "ItemName" + // OrderByColumnEnumLatestMonthEmissions - The latestMonthEmissions filed in ItemDetailsReport result, see CarbonEmissionItemDetailData + // for more information. + OrderByColumnEnumLatestMonthEmissions OrderByColumnEnum = "LatestMonthEmissions" + // OrderByColumnEnumMonthOverMonthEmissionsChangeRatio - The monthOverMonthEmissionsChangeRatio filed in ItemDetailsReport + // result, see CarbonEmissionItemDetailData for more information. + OrderByColumnEnumMonthOverMonthEmissionsChangeRatio OrderByColumnEnum = "MonthOverMonthEmissionsChangeRatio" + // OrderByColumnEnumMonthlyEmissionsChangeValue - The monthlyEmissionsChangeValue filed in ItemDetailsReport result, see CarbonEmissionItemDetailData + // for more information. + OrderByColumnEnumMonthlyEmissionsChangeValue OrderByColumnEnum = "MonthlyEmissionsChangeValue" + // OrderByColumnEnumPreviousMonthEmissions - The previousMonthEmissions filed in ItemDetailsReport result, see CarbonEmissionItemDetailData + // for more information. + OrderByColumnEnumPreviousMonthEmissions OrderByColumnEnum = "PreviousMonthEmissions" + // OrderByColumnEnumResourceGroup - The resourceGroup filed in ResourceCarbonEmissionItemDetailData result, see ResourceCarbonEmissionItemDetailData + // for more information. + OrderByColumnEnumResourceGroup OrderByColumnEnum = "ResourceGroup" +) + +// PossibleOrderByColumnEnumValues returns the possible values for the OrderByColumnEnum const type. +func PossibleOrderByColumnEnumValues() []OrderByColumnEnum { + return []OrderByColumnEnum{ + OrderByColumnEnumItemName, + OrderByColumnEnumLatestMonthEmissions, + OrderByColumnEnumMonthOverMonthEmissionsChangeRatio, + OrderByColumnEnumMonthlyEmissionsChangeValue, + OrderByColumnEnumPreviousMonthEmissions, + OrderByColumnEnumResourceGroup, + } +} + +// 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 - Indicates the operation is initiated by a system. + OriginSystem Origin = "system" + // OriginUser - Indicates the operation is initiated by a user. + OriginUser Origin = "user" + // OriginUserSystem - Indicates the operation is initiated by a user or system. + OriginUserSystem Origin = "user,system" +) + +// PossibleOriginValues returns the possible values for the Origin const type. +func PossibleOriginValues() []Origin { + return []Origin{ + OriginSystem, + OriginUser, + OriginUserSystem, + } +} + +// ReportTypeEnum - Enum for Report Type, specifying different report formats for carbon emissions data. Each report type +// returns different aggregations of carbon emissions across various categories, date range, emissions scope, and other parameters. +type ReportTypeEnum string + +const ( + // ReportTypeEnumItemDetailsReport - ItemDetailsReport provides a granular list of items based on the specified CategoryType + // (e.g., Resource, ResourceGroup, ResourceType, Location, or Subscription) for the query filter. This report can be queried + // for only one month at a time, requiring the same values in the start and end fields within DateRange. + ReportTypeEnumItemDetailsReport ReportTypeEnum = "ItemDetailsReport" + // ReportTypeEnumMonthlySummaryReport - MonthlySummaryReport provides carbon emissions data by month for the specified query + // parameters. This report type can accept different values in the start and end fields within DateRange (e.g., start: 2024-03-01 + // and end: 2024-06-01). + ReportTypeEnumMonthlySummaryReport ReportTypeEnum = "MonthlySummaryReport" + // ReportTypeEnumOverallSummaryReport - Overall summary report provides total carbon emissions for the specified date range + // and query parameters, as well as comparative values for a high-level overview. This report type can accept different values + // in the start and end fields within DateRange (e.g., start: 2024-03-01 and end: 2024-06-01). + ReportTypeEnumOverallSummaryReport ReportTypeEnum = "OverallSummaryReport" + // ReportTypeEnumTopItemsMonthlySummaryReport - TopItemsMonthlyReport provides the N highest-emitting items by month for the + // specified query filter. Returns emissions data for the top N items by month within the given date range. A maximum of N=10 + // items can be returned at a time. + ReportTypeEnumTopItemsMonthlySummaryReport ReportTypeEnum = "TopItemsMonthlySummaryReport" + // ReportTypeEnumTopItemsSummaryReport - TopItemsSummaryReport provides the N highest-emitting items for the specified query + // filters. This report returns data for a single month at a time, so it requires the same values for the start and end fields + // within DateRange. A maximum of N=10 items can be returned at a time. + ReportTypeEnumTopItemsSummaryReport ReportTypeEnum = "TopItemsSummaryReport" +) + +// PossibleReportTypeEnumValues returns the possible values for the ReportTypeEnum const type. +func PossibleReportTypeEnumValues() []ReportTypeEnum { + return []ReportTypeEnum{ + ReportTypeEnumItemDetailsReport, + ReportTypeEnumMonthlySummaryReport, + ReportTypeEnumOverallSummaryReport, + ReportTypeEnumTopItemsMonthlySummaryReport, + ReportTypeEnumTopItemsSummaryReport, + } +} + +// ResponseDataTypeEnum - The response data type of Carbon emission data +type ResponseDataTypeEnum string + +const ( + // ResponseDataTypeEnumItemDetailsData - The response data type for ItemDetailsReport + ResponseDataTypeEnumItemDetailsData ResponseDataTypeEnum = "ItemDetailsData" + // ResponseDataTypeEnumMonthlySummaryData - The response data type for MonthlySummaryReport + ResponseDataTypeEnumMonthlySummaryData ResponseDataTypeEnum = "MonthlySummaryData" + // ResponseDataTypeEnumOverallSummaryData - The response data type for OverallSummaryReport + ResponseDataTypeEnumOverallSummaryData ResponseDataTypeEnum = "OverallSummaryData" + // ResponseDataTypeEnumResourceGroupItemDetailsData - The response data type for ResourceGroup's ItemDetailsReport + ResponseDataTypeEnumResourceGroupItemDetailsData ResponseDataTypeEnum = "ResourceGroupItemDetailsData" + // ResponseDataTypeEnumResourceGroupTopItemsMonthlySummaryData - The response data type for ResourceGroup's TopItemsMonthlySummaryReport + ResponseDataTypeEnumResourceGroupTopItemsMonthlySummaryData ResponseDataTypeEnum = "ResourceGroupTopItemsMonthlySummaryData" + // ResponseDataTypeEnumResourceGroupTopItemsSummaryData - The response data type for ResourceGroup's TopItemsSummaryReport + ResponseDataTypeEnumResourceGroupTopItemsSummaryData ResponseDataTypeEnum = "ResourceGroupTopItemsSummaryData" + // ResponseDataTypeEnumResourceItemDetailsData - The response data type for Resource's ItemDetailsReport + ResponseDataTypeEnumResourceItemDetailsData ResponseDataTypeEnum = "ResourceItemDetailsData" + // ResponseDataTypeEnumResourceTopItemsMonthlySummaryData - The response data type for Resource's TopItemsMonthlySummaryReport + ResponseDataTypeEnumResourceTopItemsMonthlySummaryData ResponseDataTypeEnum = "ResourceTopItemsMonthlySummaryData" + // ResponseDataTypeEnumResourceTopItemsSummaryData - The response data type for Resource's TopItemsSummaryReport + ResponseDataTypeEnumResourceTopItemsSummaryData ResponseDataTypeEnum = "ResourceTopItemsSummaryData" + // ResponseDataTypeEnumTopItemsMonthlySummaryData - The response data type for TopItemsMonthlySummaryReport + ResponseDataTypeEnumTopItemsMonthlySummaryData ResponseDataTypeEnum = "TopItemsMonthlySummaryData" + // ResponseDataTypeEnumTopItemsSummaryData - The response data type for TopItemsSummaryReport + ResponseDataTypeEnumTopItemsSummaryData ResponseDataTypeEnum = "TopItemsSummaryData" +) + +// PossibleResponseDataTypeEnumValues returns the possible values for the ResponseDataTypeEnum const type. +func PossibleResponseDataTypeEnumValues() []ResponseDataTypeEnum { + return []ResponseDataTypeEnum{ + ResponseDataTypeEnumItemDetailsData, + ResponseDataTypeEnumMonthlySummaryData, + ResponseDataTypeEnumOverallSummaryData, + ResponseDataTypeEnumResourceGroupItemDetailsData, + ResponseDataTypeEnumResourceGroupTopItemsMonthlySummaryData, + ResponseDataTypeEnumResourceGroupTopItemsSummaryData, + ResponseDataTypeEnumResourceItemDetailsData, + ResponseDataTypeEnumResourceTopItemsMonthlySummaryData, + ResponseDataTypeEnumResourceTopItemsSummaryData, + ResponseDataTypeEnumTopItemsMonthlySummaryData, + ResponseDataTypeEnumTopItemsSummaryData, + } +} + +// SortDirectionEnum - Sorting is supported for columns in ItemDetailsReport. This object define sorting direction. +type SortDirectionEnum string + +const ( + // SortDirectionEnumAsc - Ascending order for query result. + SortDirectionEnumAsc SortDirectionEnum = "Asc" + // SortDirectionEnumDesc - Descending order for query result. + SortDirectionEnumDesc SortDirectionEnum = "Desc" +) + +// PossibleSortDirectionEnumValues returns the possible values for the SortDirectionEnum const type. +func PossibleSortDirectionEnumValues() []SortDirectionEnum { + return []SortDirectionEnum{ + SortDirectionEnumAsc, + SortDirectionEnumDesc, + } +} diff --git a/sdk/resourcemanager/carbonoptimization/armcarbonoptimization/date_type.go b/sdk/resourcemanager/carbonoptimization/armcarbonoptimization/date_type.go new file mode 100644 index 000000000000..6da2af3e6e0f --- /dev/null +++ b/sdk/resourcemanager/carbonoptimization/armcarbonoptimization/date_type.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) Go Code Generator. DO NOT EDIT. + +package armcarbonoptimization + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "reflect" + "time" +) + +const ( + fullDateJSON = `"2006-01-02"` + jsonFormat = `"%04d-%02d-%02d"` +) + +type dateType time.Time + +func (t dateType) MarshalJSON() ([]byte, error) { + return []byte(fmt.Sprintf(jsonFormat, time.Time(t).Year(), time.Time(t).Month(), time.Time(t).Day())), nil +} + +func (d *dateType) UnmarshalJSON(data []byte) (err error) { + t, err := time.Parse(fullDateJSON, string(data)) + *d = (dateType)(t) + return err +} + +func populateDateType(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] = (*dateType)(t) +} + +func unpopulateDateType(data json.RawMessage, fn string, t **time.Time) error { + if data == nil || string(data) == "null" { + return nil + } + var aux dateType + if err := json.Unmarshal(data, &aux); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + *t = (*time.Time)(&aux) + return nil +} diff --git a/sdk/resourcemanager/carbonoptimization/armcarbonoptimization/fake/carbonservice_server.go b/sdk/resourcemanager/carbonoptimization/armcarbonoptimization/fake/carbonservice_server.go new file mode 100644 index 000000000000..83be4e8293fd --- /dev/null +++ b/sdk/resourcemanager/carbonoptimization/armcarbonoptimization/fake/carbonservice_server.go @@ -0,0 +1,138 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/carbonoptimization/armcarbonoptimization" + "net/http" +) + +// CarbonServiceServer is a fake server for instances of the armcarbonoptimization.CarbonServiceClient type. +type CarbonServiceServer struct { + // QueryCarbonEmissionDataAvailableDateRange is the fake for method CarbonServiceClient.QueryCarbonEmissionDataAvailableDateRange + // HTTP status codes to indicate success: http.StatusOK + QueryCarbonEmissionDataAvailableDateRange func(ctx context.Context, options *armcarbonoptimization.CarbonServiceClientQueryCarbonEmissionDataAvailableDateRangeOptions) (resp azfake.Responder[armcarbonoptimization.CarbonServiceClientQueryCarbonEmissionDataAvailableDateRangeResponse], errResp azfake.ErrorResponder) + + // QueryCarbonEmissionReports is the fake for method CarbonServiceClient.QueryCarbonEmissionReports + // HTTP status codes to indicate success: http.StatusOK + QueryCarbonEmissionReports func(ctx context.Context, queryParameters armcarbonoptimization.QueryFilterClassification, options *armcarbonoptimization.CarbonServiceClientQueryCarbonEmissionReportsOptions) (resp azfake.Responder[armcarbonoptimization.CarbonServiceClientQueryCarbonEmissionReportsResponse], errResp azfake.ErrorResponder) +} + +// NewCarbonServiceServerTransport creates a new instance of CarbonServiceServerTransport with the provided implementation. +// The returned CarbonServiceServerTransport instance is connected to an instance of armcarbonoptimization.CarbonServiceClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewCarbonServiceServerTransport(srv *CarbonServiceServer) *CarbonServiceServerTransport { + return &CarbonServiceServerTransport{srv: srv} +} + +// CarbonServiceServerTransport connects instances of armcarbonoptimization.CarbonServiceClient to instances of CarbonServiceServer. +// Don't use this type directly, use NewCarbonServiceServerTransport instead. +type CarbonServiceServerTransport struct { + srv *CarbonServiceServer +} + +// Do implements the policy.Transporter interface for CarbonServiceServerTransport. +func (c *CarbonServiceServerTransport) 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 c.dispatchToMethodFake(req, method) +} + +func (c *CarbonServiceServerTransport) 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 carbonServiceServerTransportInterceptor != nil { + res.resp, res.err, intercepted = carbonServiceServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "CarbonServiceClient.QueryCarbonEmissionDataAvailableDateRange": + res.resp, res.err = c.dispatchQueryCarbonEmissionDataAvailableDateRange(req) + case "CarbonServiceClient.QueryCarbonEmissionReports": + res.resp, res.err = c.dispatchQueryCarbonEmissionReports(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 (c *CarbonServiceServerTransport) dispatchQueryCarbonEmissionDataAvailableDateRange(req *http.Request) (*http.Response, error) { + if c.srv.QueryCarbonEmissionDataAvailableDateRange == nil { + return nil, &nonRetriableError{errors.New("fake for method QueryCarbonEmissionDataAvailableDateRange not implemented")} + } + respr, errRespr := c.srv.QueryCarbonEmissionDataAvailableDateRange(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).CarbonEmissionDataAvailableDateRange, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (c *CarbonServiceServerTransport) dispatchQueryCarbonEmissionReports(req *http.Request) (*http.Response, error) { + if c.srv.QueryCarbonEmissionReports == nil { + return nil, &nonRetriableError{errors.New("fake for method QueryCarbonEmissionReports not implemented")} + } + raw, err := readRequestBody(req) + if err != nil { + return nil, err + } + body, err := unmarshalQueryFilterClassification(raw) + if err != nil { + return nil, err + } + respr, errRespr := c.srv.QueryCarbonEmissionReports(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).CarbonEmissionDataListResult, req) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to CarbonServiceServerTransport +var carbonServiceServerTransportInterceptor 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/carbonoptimization/armcarbonoptimization/fake/date_type.go b/sdk/resourcemanager/carbonoptimization/armcarbonoptimization/fake/date_type.go new file mode 100644 index 000000000000..1364caea1a04 --- /dev/null +++ b/sdk/resourcemanager/carbonoptimization/armcarbonoptimization/fake/date_type.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) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "reflect" + "time" +) + +const ( + fullDateJSON = `"2006-01-02"` + jsonFormat = `"%04d-%02d-%02d"` +) + +type dateType time.Time + +func (t dateType) MarshalJSON() ([]byte, error) { + return []byte(fmt.Sprintf(jsonFormat, time.Time(t).Year(), time.Time(t).Month(), time.Time(t).Day())), nil +} + +func (d *dateType) UnmarshalJSON(data []byte) (err error) { + t, err := time.Parse(fullDateJSON, string(data)) + *d = (dateType)(t) + return err +} + +func populateDateType(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] = (*dateType)(t) +} + +func unpopulateDateType(data json.RawMessage, fn string, t **time.Time) error { + if data == nil || string(data) == "null" { + return nil + } + var aux dateType + if err := json.Unmarshal(data, &aux); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + *t = (*time.Time)(&aux) + return nil +} diff --git a/sdk/resourcemanager/carbonoptimization/armcarbonoptimization/fake/internal.go b/sdk/resourcemanager/carbonoptimization/armcarbonoptimization/fake/internal.go new file mode 100644 index 000000000000..1ffebab5709c --- /dev/null +++ b/sdk/resourcemanager/carbonoptimization/armcarbonoptimization/fake/internal.go @@ -0,0 +1,78 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "io" + "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 readRequestBody(req *http.Request) ([]byte, error) { + if req.Body == nil { + return nil, nil + } + body, err := io.ReadAll(req.Body) + if err != nil { + return nil, err + } + req.Body.Close() + return body, nil +} + +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/carbonoptimization/armcarbonoptimization/fake/operations_server.go b/sdk/resourcemanager/carbonoptimization/armcarbonoptimization/fake/operations_server.go new file mode 100644 index 000000000000..a273af010678 --- /dev/null +++ b/sdk/resourcemanager/carbonoptimization/armcarbonoptimization/fake/operations_server.go @@ -0,0 +1,117 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/carbonoptimization/armcarbonoptimization" + "net/http" +) + +// OperationsServer is a fake server for instances of the armcarbonoptimization.OperationsClient type. +type OperationsServer struct { + // NewListPager is the fake for method OperationsClient.NewListPager + // HTTP status codes to indicate success: http.StatusOK + NewListPager func(options *armcarbonoptimization.OperationsClientListOptions) (resp azfake.PagerResponder[armcarbonoptimization.OperationsClientListResponse]) +} + +// NewOperationsServerTransport creates a new instance of OperationsServerTransport with the provided implementation. +// The returned OperationsServerTransport instance is connected to an instance of armcarbonoptimization.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[armcarbonoptimization.OperationsClientListResponse]](), + } +} + +// OperationsServerTransport connects instances of armcarbonoptimization.OperationsClient to instances of OperationsServer. +// Don't use this type directly, use NewOperationsServerTransport instead. +type OperationsServerTransport struct { + srv *OperationsServer + newListPager *tracker[azfake.PagerResponder[armcarbonoptimization.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 *armcarbonoptimization.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/carbonoptimization/armcarbonoptimization/fake/polymorphic_helpers.go b/sdk/resourcemanager/carbonoptimization/armcarbonoptimization/fake/polymorphic_helpers.go new file mode 100644 index 000000000000..aa8c29b766a5 --- /dev/null +++ b/sdk/resourcemanager/carbonoptimization/armcarbonoptimization/fake/polymorphic_helpers.go @@ -0,0 +1,39 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "encoding/json" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/carbonoptimization/armcarbonoptimization" +) + +func unmarshalQueryFilterClassification(rawMsg json.RawMessage) (armcarbonoptimization.QueryFilterClassification, 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 armcarbonoptimization.QueryFilterClassification + switch m["reportType"] { + case string(armcarbonoptimization.ReportTypeEnumOverallSummaryReport): + b = &armcarbonoptimization.OverallSummaryReportQueryFilter{} + case string(armcarbonoptimization.ReportTypeEnumMonthlySummaryReport): + b = &armcarbonoptimization.MonthlySummaryReportQueryFilter{} + case string(armcarbonoptimization.ReportTypeEnumTopItemsSummaryReport): + b = &armcarbonoptimization.TopItemsSummaryReportQueryFilter{} + case string(armcarbonoptimization.ReportTypeEnumTopItemsMonthlySummaryReport): + b = &armcarbonoptimization.TopItemsMonthlySummaryReportQueryFilter{} + case string(armcarbonoptimization.ReportTypeEnumItemDetailsReport): + b = &armcarbonoptimization.ItemDetailsQueryFilter{} + default: + b = &armcarbonoptimization.QueryFilter{} + } + if err := json.Unmarshal(rawMsg, b); err != nil { + return nil, err + } + return b, nil +} diff --git a/sdk/resourcemanager/carbonoptimization/armcarbonoptimization/fake/server_factory.go b/sdk/resourcemanager/carbonoptimization/armcarbonoptimization/fake/server_factory.go new file mode 100644 index 000000000000..529824983cda --- /dev/null +++ b/sdk/resourcemanager/carbonoptimization/armcarbonoptimization/fake/server_factory.go @@ -0,0 +1,81 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "errors" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" + "sync" +) + +// ServerFactory is a fake server for instances of the armcarbonoptimization.ClientFactory type. +type ServerFactory struct { + // CarbonServiceServer contains the fakes for client CarbonServiceClient + CarbonServiceServer CarbonServiceServer + + // OperationsServer contains the fakes for client OperationsClient + OperationsServer OperationsServer +} + +// NewServerFactoryTransport creates a new instance of ServerFactoryTransport with the provided implementation. +// The returned ServerFactoryTransport instance is connected to an instance of armcarbonoptimization.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 armcarbonoptimization.ClientFactory to instances of ServerFactory. +// Don't use this type directly, use NewServerFactoryTransport instead. +type ServerFactoryTransport struct { + srv *ServerFactory + trMu sync.Mutex + trCarbonServiceServer *CarbonServiceServerTransport + trOperationsServer *OperationsServerTransport +} + +// 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 "CarbonServiceClient": + initServer(s, &s.trCarbonServiceServer, func() *CarbonServiceServerTransport { + return NewCarbonServiceServerTransport(&s.srv.CarbonServiceServer) + }) + resp, err = s.trCarbonServiceServer.Do(req) + case "OperationsClient": + initServer(s, &s.trOperationsServer, func() *OperationsServerTransport { return NewOperationsServerTransport(&s.srv.OperationsServer) }) + resp, err = s.trOperationsServer.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/carbonoptimization/armcarbonoptimization/go.mod b/sdk/resourcemanager/carbonoptimization/armcarbonoptimization/go.mod new file mode 100644 index 000000000000..a1e35f232e0b --- /dev/null +++ b/sdk/resourcemanager/carbonoptimization/armcarbonoptimization/go.mod @@ -0,0 +1,23 @@ +module github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/carbonoptimization/armcarbonoptimization + +go 1.23.0 + +toolchain go1.23.8 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.17.1 + github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.7.0 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.10.0 // indirect + github.com/AzureAD/microsoft-authentication-library-for-go v1.2.2 // indirect + github.com/golang-jwt/jwt/v5 v5.2.1 // indirect + github.com/google/uuid v1.6.0 // indirect + github.com/kylelemons/godebug v1.1.0 // indirect + github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c // indirect + golang.org/x/crypto v0.36.0 // indirect + golang.org/x/net v0.37.0 // indirect + golang.org/x/sys v0.31.0 // indirect + golang.org/x/text v0.23.0 // indirect +) diff --git a/sdk/resourcemanager/carbonoptimization/armcarbonoptimization/go.sum b/sdk/resourcemanager/carbonoptimization/armcarbonoptimization/go.sum new file mode 100644 index 000000000000..1f92486fbbcf --- /dev/null +++ b/sdk/resourcemanager/carbonoptimization/armcarbonoptimization/go.sum @@ -0,0 +1,33 @@ +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/azidentity v1.7.0 h1:tfLQ34V6F7tVSwoTf/4lH5sE0o6eCJuNDTmH09nDpbc= +github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.7.0/go.mod h1:9kIvujWAA58nmPmWB1m23fyWic1kYZMxD9CxaWn4Qpg= +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/AzureAD/microsoft-authentication-library-for-go v1.2.2 h1:XHOnouVk1mxXfQidrMEnLlPk9UMeRtyBTnEFtxkV0kU= +github.com/AzureAD/microsoft-authentication-library-for-go v1.2.2/go.mod h1:wP83P5OoQ5p6ip3ScPr0BAq0BvuPAvacpEuSzyouqAI= +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/golang-jwt/jwt/v5 v5.2.1 h1:OuVbFODueb089Lh128TAcimifWaLhJwVflnrgM17wHk= +github.com/golang-jwt/jwt/v5 v5.2.1/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk= +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc= +github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= +github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c h1:+mdjkGKdHQG3305AYmdv1U2eRNDiU2ErMBj1gwrq8eQ= +github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c/go.mod h1:7rwL4CYBLnjLxUqIJNnCWiEdr3bn6IUYi15bNlnbCCU= +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/crypto v0.36.0 h1:AnAEvhDddvBdpY+uR+MyHmuZzzNqXSe/GvuDeob5L34= +golang.org/x/crypto v0.36.0/go.mod h1:Y4J0ReaxCR1IMaabaSMugxJES1EpwhBHhv2bDHklZvc= +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/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.31.0 h1:ioabZlmFYtWhL+TRYpcnNlLwhyxaM9kWTDEmfnprqik= +golang.org/x/sys v0.31.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= +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/carbonoptimization/armcarbonoptimization/interfaces.go b/sdk/resourcemanager/carbonoptimization/armcarbonoptimization/interfaces.go new file mode 100644 index 000000000000..854423f6d95f --- /dev/null +++ b/sdk/resourcemanager/carbonoptimization/armcarbonoptimization/interfaces.go @@ -0,0 +1,27 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcarbonoptimization + +// CarbonEmissionDataClassification provides polymorphic access to related types. +// Call the interface's GetCarbonEmissionData() method to access the common type. +// Use a type switch to determine the concrete type. The possible types are: +// - *CarbonEmissionData, *CarbonEmissionItemDetailData, *CarbonEmissionMonthlySummaryData, *CarbonEmissionOverallSummaryData, +// - *CarbonEmissionTopItemMonthlySummaryData, *CarbonEmissionTopItemsSummaryData, *ResourceCarbonEmissionItemDetailData, +// - *ResourceCarbonEmissionTopItemMonthlySummaryData, *ResourceCarbonEmissionTopItemsSummaryData, *ResourceGroupCarbonEmissionItemDetailData, +// - *ResourceGroupCarbonEmissionTopItemMonthlySummaryData, *ResourceGroupCarbonEmissionTopItemsSummaryData +type CarbonEmissionDataClassification interface { + // GetCarbonEmissionData returns the CarbonEmissionData content of the underlying type. + GetCarbonEmissionData() *CarbonEmissionData +} + +// QueryFilterClassification provides polymorphic access to related types. +// Call the interface's GetQueryFilter() method to access the common type. +// Use a type switch to determine the concrete type. The possible types are: +// - *ItemDetailsQueryFilter, *MonthlySummaryReportQueryFilter, *OverallSummaryReportQueryFilter, *QueryFilter, *TopItemsMonthlySummaryReportQueryFilter, +// - *TopItemsSummaryReportQueryFilter +type QueryFilterClassification interface { + // GetQueryFilter returns the QueryFilter content of the underlying type. + GetQueryFilter() *QueryFilter +} diff --git a/sdk/resourcemanager/carbonoptimization/armcarbonoptimization/models.go b/sdk/resourcemanager/carbonoptimization/armcarbonoptimization/models.go new file mode 100644 index 000000000000..1c79bd9ede25 --- /dev/null +++ b/sdk/resourcemanager/carbonoptimization/armcarbonoptimization/models.go @@ -0,0 +1,904 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcarbonoptimization + +import "time" + +// CarbonEmissionData - The basic response for different query report, all query report result will have these information +type CarbonEmissionData struct { + // REQUIRED; The data type of the query result, indicating the format of the returned response. + DataType *ResponseDataTypeEnum + + // REQUIRED; Total carbon emissions for the specified query parameters, measured in kgCO2E. This value represents total emissions + // over the specified date range (e.g., March-June). + LatestMonthEmissions *float64 + + // REQUIRED; Total carbon emissions for the previous month’s date range, which is the same period as the specified date range + // but shifted left by one month (e.g., if the specified range is March - June, the previous month’s range will be Feb - May). + // The value is measured in kgCO2E. + PreviousMonthEmissions *float64 + + // The percentage change in carbon emissions between the current and previous DateRange. This is calculated as: (latestMonthEmissions + // - previousMonthEmissions) / previousMonthEmissions. + MonthOverMonthEmissionsChangeRatio *float64 + + // The change in carbon emissions between the current and previous period, calculated as: latestMonthEmissions - previousMonthEmissions. + MonthlyEmissionsChangeValue *float64 +} + +// GetCarbonEmissionData implements the CarbonEmissionDataClassification interface for type CarbonEmissionData. +func (c *CarbonEmissionData) GetCarbonEmissionData() *CarbonEmissionData { return c } + +// CarbonEmissionDataAvailableDateRange - Response for available date range of carbon emission data +type CarbonEmissionDataAvailableDateRange struct { + // REQUIRED; End date parameter, format is yyyy-MM-dd + EndDate *string + + // REQUIRED; Start date parameter, format is yyyy-MM-dd + StartDate *string +} + +// CarbonEmissionDataListResult - List of carbon emission results +type CarbonEmissionDataListResult struct { + // REQUIRED; The CarbonEmissionData items on this page + Value []CarbonEmissionDataClassification + + // The pagination token to fetch next page data, it's null or empty if it doesn't have next page data + SkipToken *string + + // The access decision list for each input subscription + SubscriptionAccessDecisionList []*SubscriptionAccessDecision +} + +// CarbonEmissionItemDetailData - Response for detailed carbon emissions +type CarbonEmissionItemDetailData struct { + // REQUIRED; Item category, see supported type value defined in CategoryTypeEnum + CategoryType *CategoryTypeEnum + + // REQUIRED; Item details data + DataType *ResponseDataTypeEnum + + // REQUIRED; Item name, it can be resource name, resource type name, location, resource group name or subscriptionId. It depends + // on category type. + ItemName *string + + // REQUIRED; Total carbon emissions for the specified query parameters, measured in kgCO2E. This value represents total emissions + // over the specified date range (e.g., March-June). + LatestMonthEmissions *float64 + + // REQUIRED; Total carbon emissions for the previous month’s date range, which is the same period as the specified date range + // but shifted left by one month (e.g., if the specified range is March - June, the previous month’s range will be Feb - May). + // The value is measured in kgCO2E. + PreviousMonthEmissions *float64 + + // The percentage change in carbon emissions between the current and previous DateRange. This is calculated as: (latestMonthEmissions + // - previousMonthEmissions) / previousMonthEmissions. + MonthOverMonthEmissionsChangeRatio *float64 + + // The change in carbon emissions between the current and previous period, calculated as: latestMonthEmissions - previousMonthEmissions. + MonthlyEmissionsChangeValue *float64 +} + +// GetCarbonEmissionData implements the CarbonEmissionDataClassification interface for type CarbonEmissionItemDetailData. +func (c *CarbonEmissionItemDetailData) GetCarbonEmissionData() *CarbonEmissionData { + return &CarbonEmissionData{ + DataType: c.DataType, + LatestMonthEmissions: c.LatestMonthEmissions, + MonthOverMonthEmissionsChangeRatio: c.MonthOverMonthEmissionsChangeRatio, + MonthlyEmissionsChangeValue: c.MonthlyEmissionsChangeValue, + PreviousMonthEmissions: c.PreviousMonthEmissions, + } +} + +// CarbonEmissionMonthlySummaryData - Response for Monthly Carbon Emissions Summary +type CarbonEmissionMonthlySummaryData struct { + // REQUIRED; Carbon intensity for the specified month, typically in units of kgCO2E per unit of normalized usage + CarbonIntensity *float64 + + // REQUIRED; Monthly summary data + DataType *ResponseDataTypeEnum + + // REQUIRED; The date, representing the month, for which the emissions data is reported, formatted as yyyy-MM-dd (e.g., 2024-03-01) + Date *string + + // REQUIRED; Total carbon emissions for the specified query parameters, measured in kgCO2E. This value represents total emissions + // over the specified date range (e.g., March-June). + LatestMonthEmissions *float64 + + // REQUIRED; Total carbon emissions for the previous month’s date range, which is the same period as the specified date range + // but shifted left by one month (e.g., if the specified range is March - June, the previous month’s range will be Feb - May). + // The value is measured in kgCO2E. + PreviousMonthEmissions *float64 + + // The percentage change in carbon emissions between the current and previous DateRange. This is calculated as: (latestMonthEmissions + // - previousMonthEmissions) / previousMonthEmissions. + MonthOverMonthEmissionsChangeRatio *float64 + + // The change in carbon emissions between the current and previous period, calculated as: latestMonthEmissions - previousMonthEmissions. + MonthlyEmissionsChangeValue *float64 +} + +// GetCarbonEmissionData implements the CarbonEmissionDataClassification interface for type CarbonEmissionMonthlySummaryData. +func (c *CarbonEmissionMonthlySummaryData) GetCarbonEmissionData() *CarbonEmissionData { + return &CarbonEmissionData{ + DataType: c.DataType, + LatestMonthEmissions: c.LatestMonthEmissions, + MonthOverMonthEmissionsChangeRatio: c.MonthOverMonthEmissionsChangeRatio, + MonthlyEmissionsChangeValue: c.MonthlyEmissionsChangeValue, + PreviousMonthEmissions: c.PreviousMonthEmissions, + } +} + +// CarbonEmissionOverallSummaryData - Response for Overall Carbon Emissions Summary +type CarbonEmissionOverallSummaryData struct { + // REQUIRED; Overall summary data + DataType *ResponseDataTypeEnum + + // REQUIRED; Total carbon emissions for the specified query parameters, measured in kgCO2E. This value represents total emissions + // over the specified date range (e.g., March-June). + LatestMonthEmissions *float64 + + // REQUIRED; Total carbon emissions for the previous month’s date range, which is the same period as the specified date range + // but shifted left by one month (e.g., if the specified range is March - June, the previous month’s range will be Feb - May). + // The value is measured in kgCO2E. + PreviousMonthEmissions *float64 + + // The percentage change in carbon emissions between the current and previous DateRange. This is calculated as: (latestMonthEmissions + // - previousMonthEmissions) / previousMonthEmissions. + MonthOverMonthEmissionsChangeRatio *float64 + + // The change in carbon emissions between the current and previous period, calculated as: latestMonthEmissions - previousMonthEmissions. + MonthlyEmissionsChangeValue *float64 +} + +// GetCarbonEmissionData implements the CarbonEmissionDataClassification interface for type CarbonEmissionOverallSummaryData. +func (c *CarbonEmissionOverallSummaryData) GetCarbonEmissionData() *CarbonEmissionData { + return &CarbonEmissionData{ + DataType: c.DataType, + LatestMonthEmissions: c.LatestMonthEmissions, + MonthOverMonthEmissionsChangeRatio: c.MonthOverMonthEmissionsChangeRatio, + MonthlyEmissionsChangeValue: c.MonthlyEmissionsChangeValue, + PreviousMonthEmissions: c.PreviousMonthEmissions, + } +} + +// CarbonEmissionTopItemMonthlySummaryData - Response for Top Items Carbon Emissions by Month +type CarbonEmissionTopItemMonthlySummaryData struct { + // REQUIRED; Item category, see supported type value defined in CategoryTypeEnum + CategoryType *CategoryTypeEnum + + // REQUIRED; Top items Monthly summary data + DataType *ResponseDataTypeEnum + + // REQUIRED; The date, representing the month, for which the emissions data is reported, formatted as yyyy-MM-dd (e.g., 2024-03-01) + Date *string + + // REQUIRED; Item name, it can be resource name, resource type name, location, resource group name or subscriptionId. It depends + // on category type. + ItemName *string + + // REQUIRED; Total carbon emissions for the specified query parameters, measured in kgCO2E. This value represents total emissions + // over the specified date range (e.g., March-June). + LatestMonthEmissions *float64 + + // REQUIRED; Total carbon emissions for the previous month’s date range, which is the same period as the specified date range + // but shifted left by one month (e.g., if the specified range is March - June, the previous month’s range will be Feb - May). + // The value is measured in kgCO2E. + PreviousMonthEmissions *float64 + + // The percentage change in carbon emissions between the current and previous DateRange. This is calculated as: (latestMonthEmissions + // - previousMonthEmissions) / previousMonthEmissions. + MonthOverMonthEmissionsChangeRatio *float64 + + // The change in carbon emissions between the current and previous period, calculated as: latestMonthEmissions - previousMonthEmissions. + MonthlyEmissionsChangeValue *float64 +} + +// GetCarbonEmissionData implements the CarbonEmissionDataClassification interface for type CarbonEmissionTopItemMonthlySummaryData. +func (c *CarbonEmissionTopItemMonthlySummaryData) GetCarbonEmissionData() *CarbonEmissionData { + return &CarbonEmissionData{ + DataType: c.DataType, + LatestMonthEmissions: c.LatestMonthEmissions, + MonthOverMonthEmissionsChangeRatio: c.MonthOverMonthEmissionsChangeRatio, + MonthlyEmissionsChangeValue: c.MonthlyEmissionsChangeValue, + PreviousMonthEmissions: c.PreviousMonthEmissions, + } +} + +// CarbonEmissionTopItemsSummaryData - Response for Top Items by Category Type +type CarbonEmissionTopItemsSummaryData struct { + // REQUIRED; The category type of the item. This defines which dimension the emissions are aggregated by, and the supported + // values are defined in CategoryTypeEnum (e.g., Subscription, ResourceGroup, Resource, etc.). + CategoryType *CategoryTypeEnum + + // REQUIRED; Top items summary data + DataType *ResponseDataTypeEnum + + // REQUIRED; The identifier of the item being reported on, which could refer to the resource name, resource type name, location, + // resource group name, or subscription ID, depending on the specified category type. + ItemName *string + + // REQUIRED; Total carbon emissions for the specified query parameters, measured in kgCO2E. This value represents total emissions + // over the specified date range (e.g., March-June). + LatestMonthEmissions *float64 + + // REQUIRED; Total carbon emissions for the previous month’s date range, which is the same period as the specified date range + // but shifted left by one month (e.g., if the specified range is March - June, the previous month’s range will be Feb - May). + // The value is measured in kgCO2E. + PreviousMonthEmissions *float64 + + // The percentage change in carbon emissions between the current and previous DateRange. This is calculated as: (latestMonthEmissions + // - previousMonthEmissions) / previousMonthEmissions. + MonthOverMonthEmissionsChangeRatio *float64 + + // The change in carbon emissions between the current and previous period, calculated as: latestMonthEmissions - previousMonthEmissions. + MonthlyEmissionsChangeValue *float64 +} + +// GetCarbonEmissionData implements the CarbonEmissionDataClassification interface for type CarbonEmissionTopItemsSummaryData. +func (c *CarbonEmissionTopItemsSummaryData) GetCarbonEmissionData() *CarbonEmissionData { + return &CarbonEmissionData{ + DataType: c.DataType, + LatestMonthEmissions: c.LatestMonthEmissions, + MonthOverMonthEmissionsChangeRatio: c.MonthOverMonthEmissionsChangeRatio, + MonthlyEmissionsChangeValue: c.MonthlyEmissionsChangeValue, + PreviousMonthEmissions: c.PreviousMonthEmissions, + } +} + +// DateRange - Date range to be used with QueryParameter, it should be within 12 months between start and end date. In certain +// cases, start and end dates must be the same date. +type DateRange struct { + // REQUIRED; End date parameter in yyyy-MM-01 format. Only the first day of each month is accepted. + End *time.Time + + // REQUIRED; Start date parameter in yyyy-MM-01 format. Only the first day of each month is accepted. + Start *time.Time +} + +// ItemDetailsQueryFilter - Query Parameters for ItemDetailsReport +type ItemDetailsQueryFilter struct { + // REQUIRED; List of carbon emission scopes. Required. Accepts one or more values from EmissionScopeEnum (e.g., Scope1, Scope2, + // Scope3) in list form. The output will include the total emissions for the specified scopes. + CarbonScopeList []*EmissionScopeEnum + + // REQUIRED; Specifies the category type for detailed emissions data, such as Resource, ResourceGroup, ResourceType, Location, + // or Subscription. See supported types in CategoryTypeEnum. + CategoryType *CategoryTypeEnum + + // REQUIRED; The start and end dates for carbon emissions data. Required. For ItemDetailsReport and TopItemsSummaryReport, + // only one month of data is supported at a time, so start and end dates should be equal within DateRange (e.g., start: 2024-06-01 + // and end: 2024-06-01). + DateRange *DateRange + + // REQUIRED; The column name to order the results by. See supported values in OrderByColumnEnum. + OrderBy *OrderByColumnEnum + + // REQUIRED; Number of items to return in one request, max value is 5000. + PageSize *int32 + + // CONSTANT; Specifies that the report type is an item details report for granular carbon emissions data. This is a paginated + // report. + // Field has constant value ReportTypeEnumItemDetailsReport, any specified value is ignored. + ReportType *ReportTypeEnum + + // REQUIRED; Direction for sorting results. See supported values in SortDirectionEnum. + SortDirection *SortDirectionEnum + + // REQUIRED; List of subscription IDs for which carbon emissions data is requested. Required. Each subscription ID should + // be in lowercase format. The max length of list is 100. + SubscriptionList []*string + + // List of locations(Azure Region Display Name) for carbon emissions data, with each location specified in lowercase (e.g., + // 'east us'). Optional. You can use the command 'az account list-locations -o table' to find Azure Region Display Names. + LocationList []*string + + // List of resource group URLs for carbon emissions data. Optional. Each URL must follow the format '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroup}', + // and should be in all lowercase. + ResourceGroupURLList []*string + + // List of resource types for carbon emissions data. Optional. Each resource type should be specified in lowercase, following + // the format 'microsoft.{service}/{resourceType}', e.g., 'microsoft.storage/storageaccounts'. + ResourceTypeList []*string + + // Pagination token for fetching the next page of data. This token is nullable and will be returned in the previous response + // if additional data pages are available. + SkipToken *string +} + +// GetQueryFilter implements the QueryFilterClassification interface for type ItemDetailsQueryFilter. +func (i *ItemDetailsQueryFilter) GetQueryFilter() *QueryFilter { + return &QueryFilter{ + CarbonScopeList: i.CarbonScopeList, + DateRange: i.DateRange, + LocationList: i.LocationList, + ReportType: i.ReportType, + ResourceGroupURLList: i.ResourceGroupURLList, + ResourceTypeList: i.ResourceTypeList, + SubscriptionList: i.SubscriptionList, + } +} + +// MonthlySummaryReportQueryFilter - Query filter parameter to configure MonthlySummaryReport queries. +type MonthlySummaryReportQueryFilter struct { + // REQUIRED; List of carbon emission scopes. Required. Accepts one or more values from EmissionScopeEnum (e.g., Scope1, Scope2, + // Scope3) in list form. The output will include the total emissions for the specified scopes. + CarbonScopeList []*EmissionScopeEnum + + // REQUIRED; The start and end dates for carbon emissions data. Required. For ItemDetailsReport and TopItemsSummaryReport, + // only one month of data is supported at a time, so start and end dates should be equal within DateRange (e.g., start: 2024-06-01 + // and end: 2024-06-01). + DateRange *DateRange + + // CONSTANT; Specifies that the report type is a monthly summary report for carbon emissions data. + // Field has constant value ReportTypeEnumMonthlySummaryReport, any specified value is ignored. + ReportType *ReportTypeEnum + + // REQUIRED; List of subscription IDs for which carbon emissions data is requested. Required. Each subscription ID should + // be in lowercase format. The max length of list is 100. + SubscriptionList []*string + + // List of locations(Azure Region Display Name) for carbon emissions data, with each location specified in lowercase (e.g., + // 'east us'). Optional. You can use the command 'az account list-locations -o table' to find Azure Region Display Names. + LocationList []*string + + // List of resource group URLs for carbon emissions data. Optional. Each URL must follow the format '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroup}', + // and should be in all lowercase. + ResourceGroupURLList []*string + + // List of resource types for carbon emissions data. Optional. Each resource type should be specified in lowercase, following + // the format 'microsoft.{service}/{resourceType}', e.g., 'microsoft.storage/storageaccounts'. + ResourceTypeList []*string +} + +// GetQueryFilter implements the QueryFilterClassification interface for type MonthlySummaryReportQueryFilter. +func (m *MonthlySummaryReportQueryFilter) GetQueryFilter() *QueryFilter { + return &QueryFilter{ + CarbonScopeList: m.CarbonScopeList, + DateRange: m.DateRange, + LocationList: m.LocationList, + ReportType: m.ReportType, + ResourceGroupURLList: m.ResourceGroupURLList, + ResourceTypeList: m.ResourceTypeList, + SubscriptionList: m.SubscriptionList, + } +} + +// 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; Extensible 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 Azure + // Resource Manager/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 and 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 { + // REQUIRED; The Operation items on this page + Value []*Operation + + // The link to the next page of items + NextLink *string +} + +// OverallSummaryReportQueryFilter - Query filter parameter to configure OverallSummaryReport queries. +type OverallSummaryReportQueryFilter struct { + // REQUIRED; List of carbon emission scopes. Required. Accepts one or more values from EmissionScopeEnum (e.g., Scope1, Scope2, + // Scope3) in list form. The output will include the total emissions for the specified scopes. + CarbonScopeList []*EmissionScopeEnum + + // REQUIRED; The start and end dates for carbon emissions data. Required. For ItemDetailsReport and TopItemsSummaryReport, + // only one month of data is supported at a time, so start and end dates should be equal within DateRange (e.g., start: 2024-06-01 + // and end: 2024-06-01). + DateRange *DateRange + + // CONSTANT; Specifies that the report type is a overall summary report for carbon emissions data. + // Field has constant value ReportTypeEnumOverallSummaryReport, any specified value is ignored. + ReportType *ReportTypeEnum + + // REQUIRED; List of subscription IDs for which carbon emissions data is requested. Required. Each subscription ID should + // be in lowercase format. The max length of list is 100. + SubscriptionList []*string + + // List of locations(Azure Region Display Name) for carbon emissions data, with each location specified in lowercase (e.g., + // 'east us'). Optional. You can use the command 'az account list-locations -o table' to find Azure Region Display Names. + LocationList []*string + + // List of resource group URLs for carbon emissions data. Optional. Each URL must follow the format '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroup}', + // and should be in all lowercase. + ResourceGroupURLList []*string + + // List of resource types for carbon emissions data. Optional. Each resource type should be specified in lowercase, following + // the format 'microsoft.{service}/{resourceType}', e.g., 'microsoft.storage/storageaccounts'. + ResourceTypeList []*string +} + +// GetQueryFilter implements the QueryFilterClassification interface for type OverallSummaryReportQueryFilter. +func (o *OverallSummaryReportQueryFilter) GetQueryFilter() *QueryFilter { + return &QueryFilter{ + CarbonScopeList: o.CarbonScopeList, + DateRange: o.DateRange, + LocationList: o.LocationList, + ReportType: o.ReportType, + ResourceGroupURLList: o.ResourceGroupURLList, + ResourceTypeList: o.ResourceTypeList, + SubscriptionList: o.SubscriptionList, + } +} + +// QueryFilter - Shared query filter parameter to configure carbon emissions data queries for all different report type defined +// in ReportTypeEnum. +type QueryFilter struct { + // REQUIRED; List of carbon emission scopes. Required. Accepts one or more values from EmissionScopeEnum (e.g., Scope1, Scope2, + // Scope3) in list form. The output will include the total emissions for the specified scopes. + CarbonScopeList []*EmissionScopeEnum + + // REQUIRED; The start and end dates for carbon emissions data. Required. For ItemDetailsReport and TopItemsSummaryReport, + // only one month of data is supported at a time, so start and end dates should be equal within DateRange (e.g., start: 2024-06-01 + // and end: 2024-06-01). + DateRange *DateRange + + // REQUIRED; The ReportType requested for carbon emissions data. Required. Specifies how data is aggregated and displayed + // in the output, as explained in the ReportTypeEnum. + ReportType *ReportTypeEnum + + // REQUIRED; List of subscription IDs for which carbon emissions data is requested. Required. Each subscription ID should + // be in lowercase format. The max length of list is 100. + SubscriptionList []*string + + // List of locations(Azure Region Display Name) for carbon emissions data, with each location specified in lowercase (e.g., + // 'east us'). Optional. You can use the command 'az account list-locations -o table' to find Azure Region Display Names. + LocationList []*string + + // List of resource group URLs for carbon emissions data. Optional. Each URL must follow the format '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroup}', + // and should be in all lowercase. + ResourceGroupURLList []*string + + // List of resource types for carbon emissions data. Optional. Each resource type should be specified in lowercase, following + // the format 'microsoft.{service}/{resourceType}', e.g., 'microsoft.storage/storageaccounts'. + ResourceTypeList []*string +} + +// GetQueryFilter implements the QueryFilterClassification interface for type QueryFilter. +func (q *QueryFilter) GetQueryFilter() *QueryFilter { return q } + +// ResourceCarbonEmissionItemDetailData - Response for Resource detailed carbon emissions +type ResourceCarbonEmissionItemDetailData struct { + // REQUIRED; Resource Item category, see supported value defined in CategoryTypeEnum + CategoryType *CategoryTypeEnum + + // REQUIRED; ResourceGroup's item details data + DataType *ResponseDataTypeEnum + + // REQUIRED; It's resource name. + ItemName *string + + // REQUIRED; Total carbon emissions for the specified query parameters, measured in kgCO2E. This value represents total emissions + // over the specified date range (e.g., March-June). + LatestMonthEmissions *float64 + + // REQUIRED; Total carbon emissions for the previous month’s date range, which is the same period as the specified date range + // but shifted left by one month (e.g., if the specified range is March - June, the previous month’s range will be Feb - May). + // The value is measured in kgCO2E. + PreviousMonthEmissions *float64 + + // REQUIRED; Resource Group + ResourceGroup *string + + // REQUIRED; The fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ResourceID *string + + // REQUIRED; Subscription Id + SubscriptionID *string + + // Resource Location (e.g., 'east us'). + Location *string + + // The percentage change in carbon emissions between the current and previous DateRange. This is calculated as: (latestMonthEmissions + // - previousMonthEmissions) / previousMonthEmissions. + MonthOverMonthEmissionsChangeRatio *float64 + + // The change in carbon emissions between the current and previous period, calculated as: latestMonthEmissions - previousMonthEmissions. + MonthlyEmissionsChangeValue *float64 + + // The type of resource, for example: microsoft.storage/storageaccounts + ResourceType *string +} + +// GetCarbonEmissionData implements the CarbonEmissionDataClassification interface for type ResourceCarbonEmissionItemDetailData. +func (r *ResourceCarbonEmissionItemDetailData) GetCarbonEmissionData() *CarbonEmissionData { + return &CarbonEmissionData{ + DataType: r.DataType, + LatestMonthEmissions: r.LatestMonthEmissions, + MonthOverMonthEmissionsChangeRatio: r.MonthOverMonthEmissionsChangeRatio, + MonthlyEmissionsChangeValue: r.MonthlyEmissionsChangeValue, + PreviousMonthEmissions: r.PreviousMonthEmissions, + } +} + +// ResourceCarbonEmissionTopItemMonthlySummaryData - Response for top items carbon emissions by month for resource +type ResourceCarbonEmissionTopItemMonthlySummaryData struct { + // REQUIRED; Resource Item category + CategoryType *CategoryTypeEnum + + // REQUIRED; Resource top items Monthly summary data + DataType *ResponseDataTypeEnum + + // REQUIRED; Monthly date string, format is yyyy-MM-dd + Date *string + + // REQUIRED; The resource name of resource for Resource Category + ItemName *string + + // REQUIRED; Total carbon emissions for the specified query parameters, measured in kgCO2E. This value represents total emissions + // over the specified date range (e.g., March-June). + LatestMonthEmissions *float64 + + // REQUIRED; Total carbon emissions for the previous month’s date range, which is the same period as the specified date range + // but shifted left by one month (e.g., if the specified range is March - June, the previous month’s range will be Feb - May). + // The value is measured in kgCO2E. + PreviousMonthEmissions *float64 + + // REQUIRED; Resource Group + ResourceGroup *string + + // REQUIRED; The fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ResourceID *string + + // REQUIRED; Subscription Id + SubscriptionID *string + + // The percentage change in carbon emissions between the current and previous DateRange. This is calculated as: (latestMonthEmissions + // - previousMonthEmissions) / previousMonthEmissions. + MonthOverMonthEmissionsChangeRatio *float64 + + // The change in carbon emissions between the current and previous period, calculated as: latestMonthEmissions - previousMonthEmissions. + MonthlyEmissionsChangeValue *float64 +} + +// GetCarbonEmissionData implements the CarbonEmissionDataClassification interface for type ResourceCarbonEmissionTopItemMonthlySummaryData. +func (r *ResourceCarbonEmissionTopItemMonthlySummaryData) GetCarbonEmissionData() *CarbonEmissionData { + return &CarbonEmissionData{ + DataType: r.DataType, + LatestMonthEmissions: r.LatestMonthEmissions, + MonthOverMonthEmissionsChangeRatio: r.MonthOverMonthEmissionsChangeRatio, + MonthlyEmissionsChangeValue: r.MonthlyEmissionsChangeValue, + PreviousMonthEmissions: r.PreviousMonthEmissions, + } +} + +// ResourceCarbonEmissionTopItemsSummaryData - Response for Top Items For Resource Category +type ResourceCarbonEmissionTopItemsSummaryData struct { + // REQUIRED; The category type of the item. This defines which dimension the emissions are aggregated by, and the supported + // values are defined in CategoryTypeEnum (e.g., Subscription, ResourceGroup, Resource, etc.). + CategoryType *CategoryTypeEnum + + // REQUIRED; Data for the top items carbon emissions summary report specific to resource category + DataType *ResponseDataTypeEnum + + // REQUIRED; The resource name of the resource for the Resource Category. + ItemName *string + + // REQUIRED; Total carbon emissions for the specified query parameters, measured in kgCO2E. This value represents total emissions + // over the specified date range (e.g., March-June). + LatestMonthEmissions *float64 + + // REQUIRED; Total carbon emissions for the previous month’s date range, which is the same period as the specified date range + // but shifted left by one month (e.g., if the specified range is March - June, the previous month’s range will be Feb - May). + // The value is measured in kgCO2E. + PreviousMonthEmissions *float64 + + // REQUIRED; Resource group name + ResourceGroup *string + + // REQUIRED; Resource Id, The URI of the resource for the Resource Category. This identifies the resource being reported. + ResourceID *string + + // REQUIRED; Subscription Id + SubscriptionID *string + + // The percentage change in carbon emissions between the current and previous DateRange. This is calculated as: (latestMonthEmissions + // - previousMonthEmissions) / previousMonthEmissions. + MonthOverMonthEmissionsChangeRatio *float64 + + // The change in carbon emissions between the current and previous period, calculated as: latestMonthEmissions - previousMonthEmissions. + MonthlyEmissionsChangeValue *float64 +} + +// GetCarbonEmissionData implements the CarbonEmissionDataClassification interface for type ResourceCarbonEmissionTopItemsSummaryData. +func (r *ResourceCarbonEmissionTopItemsSummaryData) GetCarbonEmissionData() *CarbonEmissionData { + return &CarbonEmissionData{ + DataType: r.DataType, + LatestMonthEmissions: r.LatestMonthEmissions, + MonthOverMonthEmissionsChangeRatio: r.MonthOverMonthEmissionsChangeRatio, + MonthlyEmissionsChangeValue: r.MonthlyEmissionsChangeValue, + PreviousMonthEmissions: r.PreviousMonthEmissions, + } +} + +// ResourceGroupCarbonEmissionItemDetailData - Response for Resource Group detailed carbon emissions +type ResourceGroupCarbonEmissionItemDetailData struct { + // REQUIRED; ResourceGroup Item category + CategoryType *CategoryTypeEnum + + // REQUIRED; ResourceGroup item details data + DataType *ResponseDataTypeEnum + + // REQUIRED; It's resource group name + ItemName *string + + // REQUIRED; Total carbon emissions for the specified query parameters, measured in kgCO2E. This value represents total emissions + // over the specified date range (e.g., March-June). + LatestMonthEmissions *float64 + + // REQUIRED; Total carbon emissions for the previous month’s date range, which is the same period as the specified date range + // but shifted left by one month (e.g., if the specified range is March - June, the previous month’s range will be Feb - May). + // The value is measured in kgCO2E. + PreviousMonthEmissions *float64 + + // REQUIRED; Resource Group url, value format is '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroup}' + ResourceGroupURL *string + + // REQUIRED; Subscription Id + SubscriptionID *string + + // The percentage change in carbon emissions between the current and previous DateRange. This is calculated as: (latestMonthEmissions + // - previousMonthEmissions) / previousMonthEmissions. + MonthOverMonthEmissionsChangeRatio *float64 + + // The change in carbon emissions between the current and previous period, calculated as: latestMonthEmissions - previousMonthEmissions. + MonthlyEmissionsChangeValue *float64 +} + +// GetCarbonEmissionData implements the CarbonEmissionDataClassification interface for type ResourceGroupCarbonEmissionItemDetailData. +func (r *ResourceGroupCarbonEmissionItemDetailData) GetCarbonEmissionData() *CarbonEmissionData { + return &CarbonEmissionData{ + DataType: r.DataType, + LatestMonthEmissions: r.LatestMonthEmissions, + MonthOverMonthEmissionsChangeRatio: r.MonthOverMonthEmissionsChangeRatio, + MonthlyEmissionsChangeValue: r.MonthlyEmissionsChangeValue, + PreviousMonthEmissions: r.PreviousMonthEmissions, + } +} + +// ResourceGroupCarbonEmissionTopItemMonthlySummaryData - Response for top items carbon emissions by month for resource group +type ResourceGroupCarbonEmissionTopItemMonthlySummaryData struct { + // REQUIRED; ResourceGroup Item category + CategoryType *CategoryTypeEnum + + // REQUIRED; Resource group top items Monthly summary data + DataType *ResponseDataTypeEnum + + // REQUIRED; Monthly date string, format is yyyy-MM-dd + Date *string + + // REQUIRED; It's resource group name for ResourceGroup category + ItemName *string + + // REQUIRED; Total carbon emissions for the specified query parameters, measured in kgCO2E. This value represents total emissions + // over the specified date range (e.g., March-June). + LatestMonthEmissions *float64 + + // REQUIRED; Total carbon emissions for the previous month’s date range, which is the same period as the specified date range + // but shifted left by one month (e.g., if the specified range is March - June, the previous month’s range will be Feb - May). + // The value is measured in kgCO2E. + PreviousMonthEmissions *float64 + + // REQUIRED; Resource Group url, the format is '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroup}' + ResourceGroupURL *string + + // REQUIRED; Subscription Id + SubscriptionID *string + + // The percentage change in carbon emissions between the current and previous DateRange. This is calculated as: (latestMonthEmissions + // - previousMonthEmissions) / previousMonthEmissions. + MonthOverMonthEmissionsChangeRatio *float64 + + // The change in carbon emissions between the current and previous period, calculated as: latestMonthEmissions - previousMonthEmissions. + MonthlyEmissionsChangeValue *float64 +} + +// GetCarbonEmissionData implements the CarbonEmissionDataClassification interface for type ResourceGroupCarbonEmissionTopItemMonthlySummaryData. +func (r *ResourceGroupCarbonEmissionTopItemMonthlySummaryData) GetCarbonEmissionData() *CarbonEmissionData { + return &CarbonEmissionData{ + DataType: r.DataType, + LatestMonthEmissions: r.LatestMonthEmissions, + MonthOverMonthEmissionsChangeRatio: r.MonthOverMonthEmissionsChangeRatio, + MonthlyEmissionsChangeValue: r.MonthlyEmissionsChangeValue, + PreviousMonthEmissions: r.PreviousMonthEmissions, + } +} + +// ResourceGroupCarbonEmissionTopItemsSummaryData - Response for Top Items For ResourceGroup +type ResourceGroupCarbonEmissionTopItemsSummaryData struct { + // REQUIRED; ResourceGroup Item category + CategoryType *CategoryTypeEnum + + // REQUIRED; Resource group top items summary data + DataType *ResponseDataTypeEnum + + // REQUIRED; The resourceGroup name of the resource for ResourceGroup Category + ItemName *string + + // REQUIRED; Total carbon emissions for the specified query parameters, measured in kgCO2E. This value represents total emissions + // over the specified date range (e.g., March-June). + LatestMonthEmissions *float64 + + // REQUIRED; Total carbon emissions for the previous month’s date range, which is the same period as the specified date range + // but shifted left by one month (e.g., if the specified range is March - June, the previous month’s range will be Feb - May). + // The value is measured in kgCO2E. + PreviousMonthEmissions *float64 + + // REQUIRED; Resource Group url, value format is '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroup}' + ResourceGroupURL *string + + // REQUIRED; Subscription Id + SubscriptionID *string + + // The percentage change in carbon emissions between the current and previous DateRange. This is calculated as: (latestMonthEmissions + // - previousMonthEmissions) / previousMonthEmissions. + MonthOverMonthEmissionsChangeRatio *float64 + + // The change in carbon emissions between the current and previous period, calculated as: latestMonthEmissions - previousMonthEmissions. + MonthlyEmissionsChangeValue *float64 +} + +// GetCarbonEmissionData implements the CarbonEmissionDataClassification interface for type ResourceGroupCarbonEmissionTopItemsSummaryData. +func (r *ResourceGroupCarbonEmissionTopItemsSummaryData) GetCarbonEmissionData() *CarbonEmissionData { + return &CarbonEmissionData{ + DataType: r.DataType, + LatestMonthEmissions: r.LatestMonthEmissions, + MonthOverMonthEmissionsChangeRatio: r.MonthOverMonthEmissionsChangeRatio, + MonthlyEmissionsChangeValue: r.MonthlyEmissionsChangeValue, + PreviousMonthEmissions: r.PreviousMonthEmissions, + } +} + +// SubscriptionAccessDecision - Access Decision for each Subscription +type SubscriptionAccessDecision struct { + // REQUIRED; Access decision to subscription + Decision *AccessDecisionEnum + + // REQUIRED; Id of Subscription + SubscriptionID *string + + // The reason why access request got denied + DenialReason *string +} + +// TopItemsMonthlySummaryReportQueryFilter - Query filter parameter to configure TopItemsMonthlySummaryReport queries. +type TopItemsMonthlySummaryReportQueryFilter struct { + // REQUIRED; List of carbon emission scopes. Required. Accepts one or more values from EmissionScopeEnum (e.g., Scope1, Scope2, + // Scope3) in list form. The output will include the total emissions for the specified scopes. + CarbonScopeList []*EmissionScopeEnum + + // REQUIRED; Specifies the category type to retrieve top-emitting items, aggregated by month. See supported types in CategoryTypeEnum. + CategoryType *CategoryTypeEnum + + // REQUIRED; The start and end dates for carbon emissions data. Required. For ItemDetailsReport and TopItemsSummaryReport, + // only one month of data is supported at a time, so start and end dates should be equal within DateRange (e.g., start: 2024-06-01 + // and end: 2024-06-01). + DateRange *DateRange + + // CONSTANT; Specifies that the report type is a top items monthly summary report for carbon emissions data. + // Field has constant value ReportTypeEnumTopItemsMonthlySummaryReport, any specified value is ignored. + ReportType *ReportTypeEnum + + // REQUIRED; List of subscription IDs for which carbon emissions data is requested. Required. Each subscription ID should + // be in lowercase format. The max length of list is 100. + SubscriptionList []*string + + // REQUIRED; The number of top items to return, based on emissions. Must be between 1 and 10. + TopItems *int32 + + // List of locations(Azure Region Display Name) for carbon emissions data, with each location specified in lowercase (e.g., + // 'east us'). Optional. You can use the command 'az account list-locations -o table' to find Azure Region Display Names. + LocationList []*string + + // List of resource group URLs for carbon emissions data. Optional. Each URL must follow the format '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroup}', + // and should be in all lowercase. + ResourceGroupURLList []*string + + // List of resource types for carbon emissions data. Optional. Each resource type should be specified in lowercase, following + // the format 'microsoft.{service}/{resourceType}', e.g., 'microsoft.storage/storageaccounts'. + ResourceTypeList []*string +} + +// GetQueryFilter implements the QueryFilterClassification interface for type TopItemsMonthlySummaryReportQueryFilter. +func (t *TopItemsMonthlySummaryReportQueryFilter) GetQueryFilter() *QueryFilter { + return &QueryFilter{ + CarbonScopeList: t.CarbonScopeList, + DateRange: t.DateRange, + LocationList: t.LocationList, + ReportType: t.ReportType, + ResourceGroupURLList: t.ResourceGroupURLList, + ResourceTypeList: t.ResourceTypeList, + SubscriptionList: t.SubscriptionList, + } +} + +// TopItemsSummaryReportQueryFilter - Query filter parameter to configure TopItemsSummaryReport queries. +type TopItemsSummaryReportQueryFilter struct { + // REQUIRED; List of carbon emission scopes. Required. Accepts one or more values from EmissionScopeEnum (e.g., Scope1, Scope2, + // Scope3) in list form. The output will include the total emissions for the specified scopes. + CarbonScopeList []*EmissionScopeEnum + + // REQUIRED; Specifies the category type for which to retrieve top-emitting items. See supported values defined in CategoryTypeEnum. + CategoryType *CategoryTypeEnum + + // REQUIRED; The start and end dates for carbon emissions data. Required. For ItemDetailsReport and TopItemsSummaryReport, + // only one month of data is supported at a time, so start and end dates should be equal within DateRange (e.g., start: 2024-06-01 + // and end: 2024-06-01). + DateRange *DateRange + + // CONSTANT; Specifies that the report type is a top items summary report for carbon emissions data, aggregated by category + // type. + // Field has constant value ReportTypeEnumTopItemsSummaryReport, any specified value is ignored. + ReportType *ReportTypeEnum + + // REQUIRED; List of subscription IDs for which carbon emissions data is requested. Required. Each subscription ID should + // be in lowercase format. The max length of list is 100. + SubscriptionList []*string + + // REQUIRED; The number of top items to return, based on emissions. This value must be between 1 and 10. + TopItems *int32 + + // List of locations(Azure Region Display Name) for carbon emissions data, with each location specified in lowercase (e.g., + // 'east us'). Optional. You can use the command 'az account list-locations -o table' to find Azure Region Display Names. + LocationList []*string + + // List of resource group URLs for carbon emissions data. Optional. Each URL must follow the format '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroup}', + // and should be in all lowercase. + ResourceGroupURLList []*string + + // List of resource types for carbon emissions data. Optional. Each resource type should be specified in lowercase, following + // the format 'microsoft.{service}/{resourceType}', e.g., 'microsoft.storage/storageaccounts'. + ResourceTypeList []*string +} + +// GetQueryFilter implements the QueryFilterClassification interface for type TopItemsSummaryReportQueryFilter. +func (t *TopItemsSummaryReportQueryFilter) GetQueryFilter() *QueryFilter { + return &QueryFilter{ + CarbonScopeList: t.CarbonScopeList, + DateRange: t.DateRange, + LocationList: t.LocationList, + ReportType: t.ReportType, + ResourceGroupURLList: t.ResourceGroupURLList, + ResourceTypeList: t.ResourceTypeList, + SubscriptionList: t.SubscriptionList, + } +} diff --git a/sdk/resourcemanager/carbonoptimization/armcarbonoptimization/models_serde.go b/sdk/resourcemanager/carbonoptimization/armcarbonoptimization/models_serde.go new file mode 100644 index 000000000000..d7b6b0b85473 --- /dev/null +++ b/sdk/resourcemanager/carbonoptimization/armcarbonoptimization/models_serde.go @@ -0,0 +1,1295 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcarbonoptimization + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "reflect" +) + +// MarshalJSON implements the json.Marshaller interface for type CarbonEmissionData. +func (c CarbonEmissionData) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "dataType", c.DataType) + populate(objectMap, "latestMonthEmissions", c.LatestMonthEmissions) + populate(objectMap, "monthOverMonthEmissionsChangeRatio", c.MonthOverMonthEmissionsChangeRatio) + populate(objectMap, "monthlyEmissionsChangeValue", c.MonthlyEmissionsChangeValue) + populate(objectMap, "previousMonthEmissions", c.PreviousMonthEmissions) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CarbonEmissionData. +func (c *CarbonEmissionData) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "dataType": + err = unpopulate(val, "DataType", &c.DataType) + delete(rawMsg, key) + case "latestMonthEmissions": + err = unpopulate(val, "LatestMonthEmissions", &c.LatestMonthEmissions) + delete(rawMsg, key) + case "monthOverMonthEmissionsChangeRatio": + err = unpopulate(val, "MonthOverMonthEmissionsChangeRatio", &c.MonthOverMonthEmissionsChangeRatio) + delete(rawMsg, key) + case "monthlyEmissionsChangeValue": + err = unpopulate(val, "MonthlyEmissionsChangeValue", &c.MonthlyEmissionsChangeValue) + delete(rawMsg, key) + case "previousMonthEmissions": + err = unpopulate(val, "PreviousMonthEmissions", &c.PreviousMonthEmissions) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CarbonEmissionDataAvailableDateRange. +func (c CarbonEmissionDataAvailableDateRange) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "endDate", c.EndDate) + populate(objectMap, "startDate", c.StartDate) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CarbonEmissionDataAvailableDateRange. +func (c *CarbonEmissionDataAvailableDateRange) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "endDate": + err = unpopulate(val, "EndDate", &c.EndDate) + delete(rawMsg, key) + case "startDate": + err = unpopulate(val, "StartDate", &c.StartDate) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CarbonEmissionDataListResult. +func (c CarbonEmissionDataListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "skipToken", c.SkipToken) + populate(objectMap, "subscriptionAccessDecisionList", c.SubscriptionAccessDecisionList) + populate(objectMap, "value", c.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CarbonEmissionDataListResult. +func (c *CarbonEmissionDataListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "skipToken": + err = unpopulate(val, "SkipToken", &c.SkipToken) + delete(rawMsg, key) + case "subscriptionAccessDecisionList": + err = unpopulate(val, "SubscriptionAccessDecisionList", &c.SubscriptionAccessDecisionList) + delete(rawMsg, key) + case "value": + c.Value, err = unmarshalCarbonEmissionDataClassificationArray(val) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CarbonEmissionItemDetailData. +func (c CarbonEmissionItemDetailData) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "categoryType", c.CategoryType) + objectMap["dataType"] = ResponseDataTypeEnumItemDetailsData + populate(objectMap, "itemName", c.ItemName) + populate(objectMap, "latestMonthEmissions", c.LatestMonthEmissions) + populate(objectMap, "monthOverMonthEmissionsChangeRatio", c.MonthOverMonthEmissionsChangeRatio) + populate(objectMap, "monthlyEmissionsChangeValue", c.MonthlyEmissionsChangeValue) + populate(objectMap, "previousMonthEmissions", c.PreviousMonthEmissions) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CarbonEmissionItemDetailData. +func (c *CarbonEmissionItemDetailData) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "categoryType": + err = unpopulate(val, "CategoryType", &c.CategoryType) + delete(rawMsg, key) + case "dataType": + err = unpopulate(val, "DataType", &c.DataType) + delete(rawMsg, key) + case "itemName": + err = unpopulate(val, "ItemName", &c.ItemName) + delete(rawMsg, key) + case "latestMonthEmissions": + err = unpopulate(val, "LatestMonthEmissions", &c.LatestMonthEmissions) + delete(rawMsg, key) + case "monthOverMonthEmissionsChangeRatio": + err = unpopulate(val, "MonthOverMonthEmissionsChangeRatio", &c.MonthOverMonthEmissionsChangeRatio) + delete(rawMsg, key) + case "monthlyEmissionsChangeValue": + err = unpopulate(val, "MonthlyEmissionsChangeValue", &c.MonthlyEmissionsChangeValue) + delete(rawMsg, key) + case "previousMonthEmissions": + err = unpopulate(val, "PreviousMonthEmissions", &c.PreviousMonthEmissions) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CarbonEmissionMonthlySummaryData. +func (c CarbonEmissionMonthlySummaryData) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "carbonIntensity", c.CarbonIntensity) + objectMap["dataType"] = ResponseDataTypeEnumMonthlySummaryData + populate(objectMap, "date", c.Date) + populate(objectMap, "latestMonthEmissions", c.LatestMonthEmissions) + populate(objectMap, "monthOverMonthEmissionsChangeRatio", c.MonthOverMonthEmissionsChangeRatio) + populate(objectMap, "monthlyEmissionsChangeValue", c.MonthlyEmissionsChangeValue) + populate(objectMap, "previousMonthEmissions", c.PreviousMonthEmissions) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CarbonEmissionMonthlySummaryData. +func (c *CarbonEmissionMonthlySummaryData) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "carbonIntensity": + err = unpopulate(val, "CarbonIntensity", &c.CarbonIntensity) + delete(rawMsg, key) + case "dataType": + err = unpopulate(val, "DataType", &c.DataType) + delete(rawMsg, key) + case "date": + err = unpopulate(val, "Date", &c.Date) + delete(rawMsg, key) + case "latestMonthEmissions": + err = unpopulate(val, "LatestMonthEmissions", &c.LatestMonthEmissions) + delete(rawMsg, key) + case "monthOverMonthEmissionsChangeRatio": + err = unpopulate(val, "MonthOverMonthEmissionsChangeRatio", &c.MonthOverMonthEmissionsChangeRatio) + delete(rawMsg, key) + case "monthlyEmissionsChangeValue": + err = unpopulate(val, "MonthlyEmissionsChangeValue", &c.MonthlyEmissionsChangeValue) + delete(rawMsg, key) + case "previousMonthEmissions": + err = unpopulate(val, "PreviousMonthEmissions", &c.PreviousMonthEmissions) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CarbonEmissionOverallSummaryData. +func (c CarbonEmissionOverallSummaryData) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + objectMap["dataType"] = ResponseDataTypeEnumOverallSummaryData + populate(objectMap, "latestMonthEmissions", c.LatestMonthEmissions) + populate(objectMap, "monthOverMonthEmissionsChangeRatio", c.MonthOverMonthEmissionsChangeRatio) + populate(objectMap, "monthlyEmissionsChangeValue", c.MonthlyEmissionsChangeValue) + populate(objectMap, "previousMonthEmissions", c.PreviousMonthEmissions) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CarbonEmissionOverallSummaryData. +func (c *CarbonEmissionOverallSummaryData) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "dataType": + err = unpopulate(val, "DataType", &c.DataType) + delete(rawMsg, key) + case "latestMonthEmissions": + err = unpopulate(val, "LatestMonthEmissions", &c.LatestMonthEmissions) + delete(rawMsg, key) + case "monthOverMonthEmissionsChangeRatio": + err = unpopulate(val, "MonthOverMonthEmissionsChangeRatio", &c.MonthOverMonthEmissionsChangeRatio) + delete(rawMsg, key) + case "monthlyEmissionsChangeValue": + err = unpopulate(val, "MonthlyEmissionsChangeValue", &c.MonthlyEmissionsChangeValue) + delete(rawMsg, key) + case "previousMonthEmissions": + err = unpopulate(val, "PreviousMonthEmissions", &c.PreviousMonthEmissions) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CarbonEmissionTopItemMonthlySummaryData. +func (c CarbonEmissionTopItemMonthlySummaryData) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "categoryType", c.CategoryType) + objectMap["dataType"] = ResponseDataTypeEnumTopItemsMonthlySummaryData + populate(objectMap, "date", c.Date) + populate(objectMap, "itemName", c.ItemName) + populate(objectMap, "latestMonthEmissions", c.LatestMonthEmissions) + populate(objectMap, "monthOverMonthEmissionsChangeRatio", c.MonthOverMonthEmissionsChangeRatio) + populate(objectMap, "monthlyEmissionsChangeValue", c.MonthlyEmissionsChangeValue) + populate(objectMap, "previousMonthEmissions", c.PreviousMonthEmissions) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CarbonEmissionTopItemMonthlySummaryData. +func (c *CarbonEmissionTopItemMonthlySummaryData) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "categoryType": + err = unpopulate(val, "CategoryType", &c.CategoryType) + delete(rawMsg, key) + case "dataType": + err = unpopulate(val, "DataType", &c.DataType) + delete(rawMsg, key) + case "date": + err = unpopulate(val, "Date", &c.Date) + delete(rawMsg, key) + case "itemName": + err = unpopulate(val, "ItemName", &c.ItemName) + delete(rawMsg, key) + case "latestMonthEmissions": + err = unpopulate(val, "LatestMonthEmissions", &c.LatestMonthEmissions) + delete(rawMsg, key) + case "monthOverMonthEmissionsChangeRatio": + err = unpopulate(val, "MonthOverMonthEmissionsChangeRatio", &c.MonthOverMonthEmissionsChangeRatio) + delete(rawMsg, key) + case "monthlyEmissionsChangeValue": + err = unpopulate(val, "MonthlyEmissionsChangeValue", &c.MonthlyEmissionsChangeValue) + delete(rawMsg, key) + case "previousMonthEmissions": + err = unpopulate(val, "PreviousMonthEmissions", &c.PreviousMonthEmissions) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CarbonEmissionTopItemsSummaryData. +func (c CarbonEmissionTopItemsSummaryData) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "categoryType", c.CategoryType) + objectMap["dataType"] = ResponseDataTypeEnumTopItemsSummaryData + populate(objectMap, "itemName", c.ItemName) + populate(objectMap, "latestMonthEmissions", c.LatestMonthEmissions) + populate(objectMap, "monthOverMonthEmissionsChangeRatio", c.MonthOverMonthEmissionsChangeRatio) + populate(objectMap, "monthlyEmissionsChangeValue", c.MonthlyEmissionsChangeValue) + populate(objectMap, "previousMonthEmissions", c.PreviousMonthEmissions) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CarbonEmissionTopItemsSummaryData. +func (c *CarbonEmissionTopItemsSummaryData) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "categoryType": + err = unpopulate(val, "CategoryType", &c.CategoryType) + delete(rawMsg, key) + case "dataType": + err = unpopulate(val, "DataType", &c.DataType) + delete(rawMsg, key) + case "itemName": + err = unpopulate(val, "ItemName", &c.ItemName) + delete(rawMsg, key) + case "latestMonthEmissions": + err = unpopulate(val, "LatestMonthEmissions", &c.LatestMonthEmissions) + delete(rawMsg, key) + case "monthOverMonthEmissionsChangeRatio": + err = unpopulate(val, "MonthOverMonthEmissionsChangeRatio", &c.MonthOverMonthEmissionsChangeRatio) + delete(rawMsg, key) + case "monthlyEmissionsChangeValue": + err = unpopulate(val, "MonthlyEmissionsChangeValue", &c.MonthlyEmissionsChangeValue) + delete(rawMsg, key) + case "previousMonthEmissions": + err = unpopulate(val, "PreviousMonthEmissions", &c.PreviousMonthEmissions) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DateRange. +func (d DateRange) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateDateType(objectMap, "end", d.End) + populateDateType(objectMap, "start", d.Start) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DateRange. +func (d *DateRange) 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 "end": + err = unpopulateDateType(val, "End", &d.End) + delete(rawMsg, key) + case "start": + err = unpopulateDateType(val, "Start", &d.Start) + 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 ItemDetailsQueryFilter. +func (i ItemDetailsQueryFilter) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "carbonScopeList", i.CarbonScopeList) + populate(objectMap, "categoryType", i.CategoryType) + populate(objectMap, "dateRange", i.DateRange) + populate(objectMap, "locationList", i.LocationList) + populate(objectMap, "orderBy", i.OrderBy) + populate(objectMap, "pageSize", i.PageSize) + objectMap["reportType"] = ReportTypeEnumItemDetailsReport + populate(objectMap, "resourceGroupUrlList", i.ResourceGroupURLList) + populate(objectMap, "resourceTypeList", i.ResourceTypeList) + populate(objectMap, "skipToken", i.SkipToken) + populate(objectMap, "sortDirection", i.SortDirection) + populate(objectMap, "subscriptionList", i.SubscriptionList) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ItemDetailsQueryFilter. +func (i *ItemDetailsQueryFilter) 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 "carbonScopeList": + err = unpopulate(val, "CarbonScopeList", &i.CarbonScopeList) + delete(rawMsg, key) + case "categoryType": + err = unpopulate(val, "CategoryType", &i.CategoryType) + delete(rawMsg, key) + case "dateRange": + err = unpopulate(val, "DateRange", &i.DateRange) + delete(rawMsg, key) + case "locationList": + err = unpopulate(val, "LocationList", &i.LocationList) + delete(rawMsg, key) + case "orderBy": + err = unpopulate(val, "OrderBy", &i.OrderBy) + delete(rawMsg, key) + case "pageSize": + err = unpopulate(val, "PageSize", &i.PageSize) + delete(rawMsg, key) + case "reportType": + err = unpopulate(val, "ReportType", &i.ReportType) + delete(rawMsg, key) + case "resourceGroupUrlList": + err = unpopulate(val, "ResourceGroupURLList", &i.ResourceGroupURLList) + delete(rawMsg, key) + case "resourceTypeList": + err = unpopulate(val, "ResourceTypeList", &i.ResourceTypeList) + delete(rawMsg, key) + case "skipToken": + err = unpopulate(val, "SkipToken", &i.SkipToken) + delete(rawMsg, key) + case "sortDirection": + err = unpopulate(val, "SortDirection", &i.SortDirection) + delete(rawMsg, key) + case "subscriptionList": + err = unpopulate(val, "SubscriptionList", &i.SubscriptionList) + 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 MonthlySummaryReportQueryFilter. +func (m MonthlySummaryReportQueryFilter) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "carbonScopeList", m.CarbonScopeList) + populate(objectMap, "dateRange", m.DateRange) + populate(objectMap, "locationList", m.LocationList) + objectMap["reportType"] = ReportTypeEnumMonthlySummaryReport + populate(objectMap, "resourceGroupUrlList", m.ResourceGroupURLList) + populate(objectMap, "resourceTypeList", m.ResourceTypeList) + populate(objectMap, "subscriptionList", m.SubscriptionList) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type MonthlySummaryReportQueryFilter. +func (m *MonthlySummaryReportQueryFilter) 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 "carbonScopeList": + err = unpopulate(val, "CarbonScopeList", &m.CarbonScopeList) + delete(rawMsg, key) + case "dateRange": + err = unpopulate(val, "DateRange", &m.DateRange) + delete(rawMsg, key) + case "locationList": + err = unpopulate(val, "LocationList", &m.LocationList) + delete(rawMsg, key) + case "reportType": + err = unpopulate(val, "ReportType", &m.ReportType) + delete(rawMsg, key) + case "resourceGroupUrlList": + err = unpopulate(val, "ResourceGroupURLList", &m.ResourceGroupURLList) + delete(rawMsg, key) + case "resourceTypeList": + err = unpopulate(val, "ResourceTypeList", &m.ResourceTypeList) + delete(rawMsg, key) + case "subscriptionList": + err = unpopulate(val, "SubscriptionList", &m.SubscriptionList) + 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 OverallSummaryReportQueryFilter. +func (o OverallSummaryReportQueryFilter) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "carbonScopeList", o.CarbonScopeList) + populate(objectMap, "dateRange", o.DateRange) + populate(objectMap, "locationList", o.LocationList) + objectMap["reportType"] = ReportTypeEnumOverallSummaryReport + populate(objectMap, "resourceGroupUrlList", o.ResourceGroupURLList) + populate(objectMap, "resourceTypeList", o.ResourceTypeList) + populate(objectMap, "subscriptionList", o.SubscriptionList) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OverallSummaryReportQueryFilter. +func (o *OverallSummaryReportQueryFilter) 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 "carbonScopeList": + err = unpopulate(val, "CarbonScopeList", &o.CarbonScopeList) + delete(rawMsg, key) + case "dateRange": + err = unpopulate(val, "DateRange", &o.DateRange) + delete(rawMsg, key) + case "locationList": + err = unpopulate(val, "LocationList", &o.LocationList) + delete(rawMsg, key) + case "reportType": + err = unpopulate(val, "ReportType", &o.ReportType) + delete(rawMsg, key) + case "resourceGroupUrlList": + err = unpopulate(val, "ResourceGroupURLList", &o.ResourceGroupURLList) + delete(rawMsg, key) + case "resourceTypeList": + err = unpopulate(val, "ResourceTypeList", &o.ResourceTypeList) + delete(rawMsg, key) + case "subscriptionList": + err = unpopulate(val, "SubscriptionList", &o.SubscriptionList) + 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 QueryFilter. +func (q QueryFilter) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "carbonScopeList", q.CarbonScopeList) + populate(objectMap, "dateRange", q.DateRange) + populate(objectMap, "locationList", q.LocationList) + populate(objectMap, "reportType", q.ReportType) + populate(objectMap, "resourceGroupUrlList", q.ResourceGroupURLList) + populate(objectMap, "resourceTypeList", q.ResourceTypeList) + populate(objectMap, "subscriptionList", q.SubscriptionList) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type QueryFilter. +func (q *QueryFilter) 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", q, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "carbonScopeList": + err = unpopulate(val, "CarbonScopeList", &q.CarbonScopeList) + delete(rawMsg, key) + case "dateRange": + err = unpopulate(val, "DateRange", &q.DateRange) + delete(rawMsg, key) + case "locationList": + err = unpopulate(val, "LocationList", &q.LocationList) + delete(rawMsg, key) + case "reportType": + err = unpopulate(val, "ReportType", &q.ReportType) + delete(rawMsg, key) + case "resourceGroupUrlList": + err = unpopulate(val, "ResourceGroupURLList", &q.ResourceGroupURLList) + delete(rawMsg, key) + case "resourceTypeList": + err = unpopulate(val, "ResourceTypeList", &q.ResourceTypeList) + delete(rawMsg, key) + case "subscriptionList": + err = unpopulate(val, "SubscriptionList", &q.SubscriptionList) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", q, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ResourceCarbonEmissionItemDetailData. +func (r ResourceCarbonEmissionItemDetailData) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "categoryType", r.CategoryType) + objectMap["dataType"] = ResponseDataTypeEnumResourceItemDetailsData + populate(objectMap, "itemName", r.ItemName) + populate(objectMap, "latestMonthEmissions", r.LatestMonthEmissions) + populate(objectMap, "location", r.Location) + populate(objectMap, "monthOverMonthEmissionsChangeRatio", r.MonthOverMonthEmissionsChangeRatio) + populate(objectMap, "monthlyEmissionsChangeValue", r.MonthlyEmissionsChangeValue) + populate(objectMap, "previousMonthEmissions", r.PreviousMonthEmissions) + populate(objectMap, "resourceGroup", r.ResourceGroup) + populate(objectMap, "resourceId", r.ResourceID) + populate(objectMap, "resourceType", r.ResourceType) + populate(objectMap, "subscriptionId", r.SubscriptionID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ResourceCarbonEmissionItemDetailData. +func (r *ResourceCarbonEmissionItemDetailData) 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 "categoryType": + err = unpopulate(val, "CategoryType", &r.CategoryType) + delete(rawMsg, key) + case "dataType": + err = unpopulate(val, "DataType", &r.DataType) + delete(rawMsg, key) + case "itemName": + err = unpopulate(val, "ItemName", &r.ItemName) + delete(rawMsg, key) + case "latestMonthEmissions": + err = unpopulate(val, "LatestMonthEmissions", &r.LatestMonthEmissions) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &r.Location) + delete(rawMsg, key) + case "monthOverMonthEmissionsChangeRatio": + err = unpopulate(val, "MonthOverMonthEmissionsChangeRatio", &r.MonthOverMonthEmissionsChangeRatio) + delete(rawMsg, key) + case "monthlyEmissionsChangeValue": + err = unpopulate(val, "MonthlyEmissionsChangeValue", &r.MonthlyEmissionsChangeValue) + delete(rawMsg, key) + case "previousMonthEmissions": + err = unpopulate(val, "PreviousMonthEmissions", &r.PreviousMonthEmissions) + delete(rawMsg, key) + case "resourceGroup": + err = unpopulate(val, "ResourceGroup", &r.ResourceGroup) + delete(rawMsg, key) + case "resourceId": + err = unpopulate(val, "ResourceID", &r.ResourceID) + delete(rawMsg, key) + case "resourceType": + err = unpopulate(val, "ResourceType", &r.ResourceType) + delete(rawMsg, key) + case "subscriptionId": + err = unpopulate(val, "SubscriptionID", &r.SubscriptionID) + 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 ResourceCarbonEmissionTopItemMonthlySummaryData. +func (r ResourceCarbonEmissionTopItemMonthlySummaryData) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "categoryType", r.CategoryType) + objectMap["dataType"] = ResponseDataTypeEnumResourceTopItemsMonthlySummaryData + populate(objectMap, "date", r.Date) + populate(objectMap, "itemName", r.ItemName) + populate(objectMap, "latestMonthEmissions", r.LatestMonthEmissions) + populate(objectMap, "monthOverMonthEmissionsChangeRatio", r.MonthOverMonthEmissionsChangeRatio) + populate(objectMap, "monthlyEmissionsChangeValue", r.MonthlyEmissionsChangeValue) + populate(objectMap, "previousMonthEmissions", r.PreviousMonthEmissions) + populate(objectMap, "resourceGroup", r.ResourceGroup) + populate(objectMap, "resourceId", r.ResourceID) + populate(objectMap, "subscriptionId", r.SubscriptionID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ResourceCarbonEmissionTopItemMonthlySummaryData. +func (r *ResourceCarbonEmissionTopItemMonthlySummaryData) 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 "categoryType": + err = unpopulate(val, "CategoryType", &r.CategoryType) + delete(rawMsg, key) + case "dataType": + err = unpopulate(val, "DataType", &r.DataType) + delete(rawMsg, key) + case "date": + err = unpopulate(val, "Date", &r.Date) + delete(rawMsg, key) + case "itemName": + err = unpopulate(val, "ItemName", &r.ItemName) + delete(rawMsg, key) + case "latestMonthEmissions": + err = unpopulate(val, "LatestMonthEmissions", &r.LatestMonthEmissions) + delete(rawMsg, key) + case "monthOverMonthEmissionsChangeRatio": + err = unpopulate(val, "MonthOverMonthEmissionsChangeRatio", &r.MonthOverMonthEmissionsChangeRatio) + delete(rawMsg, key) + case "monthlyEmissionsChangeValue": + err = unpopulate(val, "MonthlyEmissionsChangeValue", &r.MonthlyEmissionsChangeValue) + delete(rawMsg, key) + case "previousMonthEmissions": + err = unpopulate(val, "PreviousMonthEmissions", &r.PreviousMonthEmissions) + delete(rawMsg, key) + case "resourceGroup": + err = unpopulate(val, "ResourceGroup", &r.ResourceGroup) + delete(rawMsg, key) + case "resourceId": + err = unpopulate(val, "ResourceID", &r.ResourceID) + delete(rawMsg, key) + case "subscriptionId": + err = unpopulate(val, "SubscriptionID", &r.SubscriptionID) + 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 ResourceCarbonEmissionTopItemsSummaryData. +func (r ResourceCarbonEmissionTopItemsSummaryData) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "categoryType", r.CategoryType) + objectMap["dataType"] = ResponseDataTypeEnumResourceTopItemsSummaryData + populate(objectMap, "itemName", r.ItemName) + populate(objectMap, "latestMonthEmissions", r.LatestMonthEmissions) + populate(objectMap, "monthOverMonthEmissionsChangeRatio", r.MonthOverMonthEmissionsChangeRatio) + populate(objectMap, "monthlyEmissionsChangeValue", r.MonthlyEmissionsChangeValue) + populate(objectMap, "previousMonthEmissions", r.PreviousMonthEmissions) + populate(objectMap, "resourceGroup", r.ResourceGroup) + populate(objectMap, "resourceId", r.ResourceID) + populate(objectMap, "subscriptionId", r.SubscriptionID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ResourceCarbonEmissionTopItemsSummaryData. +func (r *ResourceCarbonEmissionTopItemsSummaryData) 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 "categoryType": + err = unpopulate(val, "CategoryType", &r.CategoryType) + delete(rawMsg, key) + case "dataType": + err = unpopulate(val, "DataType", &r.DataType) + delete(rawMsg, key) + case "itemName": + err = unpopulate(val, "ItemName", &r.ItemName) + delete(rawMsg, key) + case "latestMonthEmissions": + err = unpopulate(val, "LatestMonthEmissions", &r.LatestMonthEmissions) + delete(rawMsg, key) + case "monthOverMonthEmissionsChangeRatio": + err = unpopulate(val, "MonthOverMonthEmissionsChangeRatio", &r.MonthOverMonthEmissionsChangeRatio) + delete(rawMsg, key) + case "monthlyEmissionsChangeValue": + err = unpopulate(val, "MonthlyEmissionsChangeValue", &r.MonthlyEmissionsChangeValue) + delete(rawMsg, key) + case "previousMonthEmissions": + err = unpopulate(val, "PreviousMonthEmissions", &r.PreviousMonthEmissions) + delete(rawMsg, key) + case "resourceGroup": + err = unpopulate(val, "ResourceGroup", &r.ResourceGroup) + delete(rawMsg, key) + case "resourceId": + err = unpopulate(val, "ResourceID", &r.ResourceID) + delete(rawMsg, key) + case "subscriptionId": + err = unpopulate(val, "SubscriptionID", &r.SubscriptionID) + 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 ResourceGroupCarbonEmissionItemDetailData. +func (r ResourceGroupCarbonEmissionItemDetailData) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "categoryType", r.CategoryType) + objectMap["dataType"] = ResponseDataTypeEnumResourceGroupItemDetailsData + populate(objectMap, "itemName", r.ItemName) + populate(objectMap, "latestMonthEmissions", r.LatestMonthEmissions) + populate(objectMap, "monthOverMonthEmissionsChangeRatio", r.MonthOverMonthEmissionsChangeRatio) + populate(objectMap, "monthlyEmissionsChangeValue", r.MonthlyEmissionsChangeValue) + populate(objectMap, "previousMonthEmissions", r.PreviousMonthEmissions) + populate(objectMap, "resourceGroupUrl", r.ResourceGroupURL) + populate(objectMap, "subscriptionId", r.SubscriptionID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ResourceGroupCarbonEmissionItemDetailData. +func (r *ResourceGroupCarbonEmissionItemDetailData) 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 "categoryType": + err = unpopulate(val, "CategoryType", &r.CategoryType) + delete(rawMsg, key) + case "dataType": + err = unpopulate(val, "DataType", &r.DataType) + delete(rawMsg, key) + case "itemName": + err = unpopulate(val, "ItemName", &r.ItemName) + delete(rawMsg, key) + case "latestMonthEmissions": + err = unpopulate(val, "LatestMonthEmissions", &r.LatestMonthEmissions) + delete(rawMsg, key) + case "monthOverMonthEmissionsChangeRatio": + err = unpopulate(val, "MonthOverMonthEmissionsChangeRatio", &r.MonthOverMonthEmissionsChangeRatio) + delete(rawMsg, key) + case "monthlyEmissionsChangeValue": + err = unpopulate(val, "MonthlyEmissionsChangeValue", &r.MonthlyEmissionsChangeValue) + delete(rawMsg, key) + case "previousMonthEmissions": + err = unpopulate(val, "PreviousMonthEmissions", &r.PreviousMonthEmissions) + delete(rawMsg, key) + case "resourceGroupUrl": + err = unpopulate(val, "ResourceGroupURL", &r.ResourceGroupURL) + delete(rawMsg, key) + case "subscriptionId": + err = unpopulate(val, "SubscriptionID", &r.SubscriptionID) + 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 ResourceGroupCarbonEmissionTopItemMonthlySummaryData. +func (r ResourceGroupCarbonEmissionTopItemMonthlySummaryData) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "categoryType", r.CategoryType) + objectMap["dataType"] = ResponseDataTypeEnumResourceGroupTopItemsMonthlySummaryData + populate(objectMap, "date", r.Date) + populate(objectMap, "itemName", r.ItemName) + populate(objectMap, "latestMonthEmissions", r.LatestMonthEmissions) + populate(objectMap, "monthOverMonthEmissionsChangeRatio", r.MonthOverMonthEmissionsChangeRatio) + populate(objectMap, "monthlyEmissionsChangeValue", r.MonthlyEmissionsChangeValue) + populate(objectMap, "previousMonthEmissions", r.PreviousMonthEmissions) + populate(objectMap, "resourceGroupUrl", r.ResourceGroupURL) + populate(objectMap, "subscriptionId", r.SubscriptionID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ResourceGroupCarbonEmissionTopItemMonthlySummaryData. +func (r *ResourceGroupCarbonEmissionTopItemMonthlySummaryData) 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 "categoryType": + err = unpopulate(val, "CategoryType", &r.CategoryType) + delete(rawMsg, key) + case "dataType": + err = unpopulate(val, "DataType", &r.DataType) + delete(rawMsg, key) + case "date": + err = unpopulate(val, "Date", &r.Date) + delete(rawMsg, key) + case "itemName": + err = unpopulate(val, "ItemName", &r.ItemName) + delete(rawMsg, key) + case "latestMonthEmissions": + err = unpopulate(val, "LatestMonthEmissions", &r.LatestMonthEmissions) + delete(rawMsg, key) + case "monthOverMonthEmissionsChangeRatio": + err = unpopulate(val, "MonthOverMonthEmissionsChangeRatio", &r.MonthOverMonthEmissionsChangeRatio) + delete(rawMsg, key) + case "monthlyEmissionsChangeValue": + err = unpopulate(val, "MonthlyEmissionsChangeValue", &r.MonthlyEmissionsChangeValue) + delete(rawMsg, key) + case "previousMonthEmissions": + err = unpopulate(val, "PreviousMonthEmissions", &r.PreviousMonthEmissions) + delete(rawMsg, key) + case "resourceGroupUrl": + err = unpopulate(val, "ResourceGroupURL", &r.ResourceGroupURL) + delete(rawMsg, key) + case "subscriptionId": + err = unpopulate(val, "SubscriptionID", &r.SubscriptionID) + 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 ResourceGroupCarbonEmissionTopItemsSummaryData. +func (r ResourceGroupCarbonEmissionTopItemsSummaryData) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "categoryType", r.CategoryType) + objectMap["dataType"] = ResponseDataTypeEnumResourceGroupTopItemsSummaryData + populate(objectMap, "itemName", r.ItemName) + populate(objectMap, "latestMonthEmissions", r.LatestMonthEmissions) + populate(objectMap, "monthOverMonthEmissionsChangeRatio", r.MonthOverMonthEmissionsChangeRatio) + populate(objectMap, "monthlyEmissionsChangeValue", r.MonthlyEmissionsChangeValue) + populate(objectMap, "previousMonthEmissions", r.PreviousMonthEmissions) + populate(objectMap, "resourceGroupUrl", r.ResourceGroupURL) + populate(objectMap, "subscriptionId", r.SubscriptionID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ResourceGroupCarbonEmissionTopItemsSummaryData. +func (r *ResourceGroupCarbonEmissionTopItemsSummaryData) 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 "categoryType": + err = unpopulate(val, "CategoryType", &r.CategoryType) + delete(rawMsg, key) + case "dataType": + err = unpopulate(val, "DataType", &r.DataType) + delete(rawMsg, key) + case "itemName": + err = unpopulate(val, "ItemName", &r.ItemName) + delete(rawMsg, key) + case "latestMonthEmissions": + err = unpopulate(val, "LatestMonthEmissions", &r.LatestMonthEmissions) + delete(rawMsg, key) + case "monthOverMonthEmissionsChangeRatio": + err = unpopulate(val, "MonthOverMonthEmissionsChangeRatio", &r.MonthOverMonthEmissionsChangeRatio) + delete(rawMsg, key) + case "monthlyEmissionsChangeValue": + err = unpopulate(val, "MonthlyEmissionsChangeValue", &r.MonthlyEmissionsChangeValue) + delete(rawMsg, key) + case "previousMonthEmissions": + err = unpopulate(val, "PreviousMonthEmissions", &r.PreviousMonthEmissions) + delete(rawMsg, key) + case "resourceGroupUrl": + err = unpopulate(val, "ResourceGroupURL", &r.ResourceGroupURL) + delete(rawMsg, key) + case "subscriptionId": + err = unpopulate(val, "SubscriptionID", &r.SubscriptionID) + 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 SubscriptionAccessDecision. +func (s SubscriptionAccessDecision) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "decision", s.Decision) + populate(objectMap, "denialReason", s.DenialReason) + populate(objectMap, "subscriptionId", s.SubscriptionID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SubscriptionAccessDecision. +func (s *SubscriptionAccessDecision) 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 "decision": + err = unpopulate(val, "Decision", &s.Decision) + delete(rawMsg, key) + case "denialReason": + err = unpopulate(val, "DenialReason", &s.DenialReason) + delete(rawMsg, key) + case "subscriptionId": + err = unpopulate(val, "SubscriptionID", &s.SubscriptionID) + 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 TopItemsMonthlySummaryReportQueryFilter. +func (t TopItemsMonthlySummaryReportQueryFilter) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "carbonScopeList", t.CarbonScopeList) + populate(objectMap, "categoryType", t.CategoryType) + populate(objectMap, "dateRange", t.DateRange) + populate(objectMap, "locationList", t.LocationList) + objectMap["reportType"] = ReportTypeEnumTopItemsMonthlySummaryReport + populate(objectMap, "resourceGroupUrlList", t.ResourceGroupURLList) + populate(objectMap, "resourceTypeList", t.ResourceTypeList) + populate(objectMap, "subscriptionList", t.SubscriptionList) + populate(objectMap, "topItems", t.TopItems) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type TopItemsMonthlySummaryReportQueryFilter. +func (t *TopItemsMonthlySummaryReportQueryFilter) 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 "carbonScopeList": + err = unpopulate(val, "CarbonScopeList", &t.CarbonScopeList) + delete(rawMsg, key) + case "categoryType": + err = unpopulate(val, "CategoryType", &t.CategoryType) + delete(rawMsg, key) + case "dateRange": + err = unpopulate(val, "DateRange", &t.DateRange) + delete(rawMsg, key) + case "locationList": + err = unpopulate(val, "LocationList", &t.LocationList) + delete(rawMsg, key) + case "reportType": + err = unpopulate(val, "ReportType", &t.ReportType) + delete(rawMsg, key) + case "resourceGroupUrlList": + err = unpopulate(val, "ResourceGroupURLList", &t.ResourceGroupURLList) + delete(rawMsg, key) + case "resourceTypeList": + err = unpopulate(val, "ResourceTypeList", &t.ResourceTypeList) + delete(rawMsg, key) + case "subscriptionList": + err = unpopulate(val, "SubscriptionList", &t.SubscriptionList) + delete(rawMsg, key) + case "topItems": + err = unpopulate(val, "TopItems", &t.TopItems) + 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 TopItemsSummaryReportQueryFilter. +func (t TopItemsSummaryReportQueryFilter) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "carbonScopeList", t.CarbonScopeList) + populate(objectMap, "categoryType", t.CategoryType) + populate(objectMap, "dateRange", t.DateRange) + populate(objectMap, "locationList", t.LocationList) + objectMap["reportType"] = ReportTypeEnumTopItemsSummaryReport + populate(objectMap, "resourceGroupUrlList", t.ResourceGroupURLList) + populate(objectMap, "resourceTypeList", t.ResourceTypeList) + populate(objectMap, "subscriptionList", t.SubscriptionList) + populate(objectMap, "topItems", t.TopItems) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type TopItemsSummaryReportQueryFilter. +func (t *TopItemsSummaryReportQueryFilter) 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 "carbonScopeList": + err = unpopulate(val, "CarbonScopeList", &t.CarbonScopeList) + delete(rawMsg, key) + case "categoryType": + err = unpopulate(val, "CategoryType", &t.CategoryType) + delete(rawMsg, key) + case "dateRange": + err = unpopulate(val, "DateRange", &t.DateRange) + delete(rawMsg, key) + case "locationList": + err = unpopulate(val, "LocationList", &t.LocationList) + delete(rawMsg, key) + case "reportType": + err = unpopulate(val, "ReportType", &t.ReportType) + delete(rawMsg, key) + case "resourceGroupUrlList": + err = unpopulate(val, "ResourceGroupURLList", &t.ResourceGroupURLList) + delete(rawMsg, key) + case "resourceTypeList": + err = unpopulate(val, "ResourceTypeList", &t.ResourceTypeList) + delete(rawMsg, key) + case "subscriptionList": + err = unpopulate(val, "SubscriptionList", &t.SubscriptionList) + delete(rawMsg, key) + case "topItems": + err = unpopulate(val, "TopItems", &t.TopItems) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + } + return nil +} + +func populate(m map[string]any, k string, v any) { + if v == nil { + return + } 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/carbonoptimization/armcarbonoptimization/operations_client.go b/sdk/resourcemanager/carbonoptimization/armcarbonoptimization/operations_client.go new file mode 100644 index 000000000000..018fff05e87e --- /dev/null +++ b/sdk/resourcemanager/carbonoptimization/armcarbonoptimization/operations_client.go @@ -0,0 +1,84 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcarbonoptimization + +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 2025-04-01 +// - options - OperationsClientListOptions contains the optional parameters for the OperationsClient.NewListPager method. +func (client *OperationsClient) NewListPager(options *OperationsClientListOptions) *runtime.Pager[OperationsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[OperationsClientListResponse]{ + 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.Carbon/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", "2025-04-01") + 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/carbonoptimization/armcarbonoptimization/operations_client_example_test.go b/sdk/resourcemanager/carbonoptimization/armcarbonoptimization/operations_client_example_test.go new file mode 100644 index 000000000000..7871685132f1 --- /dev/null +++ b/sdk/resourcemanager/carbonoptimization/armcarbonoptimization/operations_client_example_test.go @@ -0,0 +1,63 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcarbonoptimization_test + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azidentity" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/carbonoptimization/armcarbonoptimization" + "log" +) + +// Generated from example definition: 2025-04-01/listOperations.json +func ExampleOperationsClient_NewListPager() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armcarbonoptimization.NewClientFactory(cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + pager := clientFactory.NewOperationsClient().NewListPager(nil) + for pager.More() { + page, err := pager.NextPage(ctx) + if err != nil { + log.Fatalf("failed to advance page: %v", err) + } + for _, v := range page.Value { + // You could use page here. We use blank identifier for just demo purposes. + _ = v + } + // If the HTTP response code is 200 as defined in example definition, your page structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // page = armcarbonoptimization.OperationsClientListResponse{ + // OperationListResult: armcarbonoptimization.OperationListResult{ + // Value: []*armcarbonoptimization.Operation{ + // { + // Name: to.Ptr("Microsoft.Carbon/action"), + // IsDataAction: to.Ptr(false), + // Display: &armcarbonoptimization.OperationDisplay{ + // Provider: to.Ptr("Microsoft.Carbon"), + // Resource: to.Ptr("queryCarbonEmissionReport"), + // Operation: to.Ptr("CarbonService_ListCarbonEmissionReports"), + // Description: to.Ptr("Returns carbon emission reports."), + // }, + // }, + // { + // Name: to.Ptr("Microsoft.Carbon/action"), + // IsDataAction: to.Ptr(false), + // Display: &armcarbonoptimization.OperationDisplay{ + // Provider: to.Ptr("Microsoft.Carbon"), + // Resource: to.Ptr("QueryCarbonEmissionDataAvailableDateRange"), + // Operation: to.Ptr("CarbonService_QueryCarbonEmissionDataAvailableDateRange"), + // Description: to.Ptr("Returns carbon emission data available date range."), + // }, + // }, + // }, + // }, + // } + } +} diff --git a/sdk/resourcemanager/carbonoptimization/armcarbonoptimization/options.go b/sdk/resourcemanager/carbonoptimization/armcarbonoptimization/options.go new file mode 100644 index 000000000000..49151fa58ede --- /dev/null +++ b/sdk/resourcemanager/carbonoptimization/armcarbonoptimization/options.go @@ -0,0 +1,22 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcarbonoptimization + +// CarbonServiceClientQueryCarbonEmissionDataAvailableDateRangeOptions contains the optional parameters for the CarbonServiceClient.QueryCarbonEmissionDataAvailableDateRange +// method. +type CarbonServiceClientQueryCarbonEmissionDataAvailableDateRangeOptions struct { + // placeholder for future optional parameters +} + +// CarbonServiceClientQueryCarbonEmissionReportsOptions contains the optional parameters for the CarbonServiceClient.QueryCarbonEmissionReports +// method. +type CarbonServiceClientQueryCarbonEmissionReportsOptions struct { + // placeholder for future optional parameters +} + +// OperationsClientListOptions contains the optional parameters for the OperationsClient.NewListPager method. +type OperationsClientListOptions struct { + // placeholder for future optional parameters +} diff --git a/sdk/resourcemanager/carbonoptimization/armcarbonoptimization/polymorphic_helpers.go b/sdk/resourcemanager/carbonoptimization/armcarbonoptimization/polymorphic_helpers.go new file mode 100644 index 000000000000..9ff520862753 --- /dev/null +++ b/sdk/resourcemanager/carbonoptimization/armcarbonoptimization/polymorphic_helpers.go @@ -0,0 +1,67 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcarbonoptimization + +import "encoding/json" + +func unmarshalCarbonEmissionDataClassification(rawMsg json.RawMessage) (CarbonEmissionDataClassification, 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 CarbonEmissionDataClassification + switch m["dataType"] { + case string(ResponseDataTypeEnumOverallSummaryData): + b = &CarbonEmissionOverallSummaryData{} + case string(ResponseDataTypeEnumMonthlySummaryData): + b = &CarbonEmissionMonthlySummaryData{} + case string(ResponseDataTypeEnumTopItemsSummaryData): + b = &CarbonEmissionTopItemsSummaryData{} + case string(ResponseDataTypeEnumResourceTopItemsSummaryData): + b = &ResourceCarbonEmissionTopItemsSummaryData{} + case string(ResponseDataTypeEnumResourceGroupTopItemsSummaryData): + b = &ResourceGroupCarbonEmissionTopItemsSummaryData{} + case string(ResponseDataTypeEnumTopItemsMonthlySummaryData): + b = &CarbonEmissionTopItemMonthlySummaryData{} + case string(ResponseDataTypeEnumResourceTopItemsMonthlySummaryData): + b = &ResourceCarbonEmissionTopItemMonthlySummaryData{} + case string(ResponseDataTypeEnumResourceGroupTopItemsMonthlySummaryData): + b = &ResourceGroupCarbonEmissionTopItemMonthlySummaryData{} + case string(ResponseDataTypeEnumItemDetailsData): + b = &CarbonEmissionItemDetailData{} + case string(ResponseDataTypeEnumResourceItemDetailsData): + b = &ResourceCarbonEmissionItemDetailData{} + case string(ResponseDataTypeEnumResourceGroupItemDetailsData): + b = &ResourceGroupCarbonEmissionItemDetailData{} + default: + b = &CarbonEmissionData{} + } + if err := json.Unmarshal(rawMsg, b); err != nil { + return nil, err + } + return b, nil +} + +func unmarshalCarbonEmissionDataClassificationArray(rawMsg json.RawMessage) ([]CarbonEmissionDataClassification, error) { + if rawMsg == nil || string(rawMsg) == "null" { + return nil, nil + } + var rawMessages []json.RawMessage + if err := json.Unmarshal(rawMsg, &rawMessages); err != nil { + return nil, err + } + fArray := make([]CarbonEmissionDataClassification, len(rawMessages)) + for index, rawMessage := range rawMessages { + f, err := unmarshalCarbonEmissionDataClassification(rawMessage) + if err != nil { + return nil, err + } + fArray[index] = f + } + return fArray, nil +} diff --git a/sdk/resourcemanager/carbonoptimization/armcarbonoptimization/responses.go b/sdk/resourcemanager/carbonoptimization/armcarbonoptimization/responses.go new file mode 100644 index 000000000000..49cee7799ba4 --- /dev/null +++ b/sdk/resourcemanager/carbonoptimization/armcarbonoptimization/responses.go @@ -0,0 +1,23 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcarbonoptimization + +// CarbonServiceClientQueryCarbonEmissionDataAvailableDateRangeResponse contains the response from method CarbonServiceClient.QueryCarbonEmissionDataAvailableDateRange. +type CarbonServiceClientQueryCarbonEmissionDataAvailableDateRangeResponse struct { + // Response for available date range of carbon emission data + CarbonEmissionDataAvailableDateRange +} + +// CarbonServiceClientQueryCarbonEmissionReportsResponse contains the response from method CarbonServiceClient.QueryCarbonEmissionReports. +type CarbonServiceClientQueryCarbonEmissionReportsResponse struct { + // List of carbon emission results + CarbonEmissionDataListResult +} + +// 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 +} diff --git a/sdk/resourcemanager/carbonoptimization/armcarbonoptimization/tsp-location.yaml b/sdk/resourcemanager/carbonoptimization/armcarbonoptimization/tsp-location.yaml new file mode 100644 index 000000000000..83e2bd63addb --- /dev/null +++ b/sdk/resourcemanager/carbonoptimization/armcarbonoptimization/tsp-location.yaml @@ -0,0 +1,4 @@ +directory: specification/carbon/Carbon.Management +commit: 1f578543d267d08febc1bebf4e33ffe14363ddfc +repo: Azure/azure-rest-api-specs +additionalDirectories: diff --git a/sdk/resourcemanager/chaos/armchaos/CHANGELOG.md b/sdk/resourcemanager/chaos/armchaos/CHANGELOG.md index 66d880b0bc91..c432f33f27c9 100644 --- a/sdk/resourcemanager/chaos/armchaos/CHANGELOG.md +++ b/sdk/resourcemanager/chaos/armchaos/CHANGELOG.md @@ -1,5 +1,50 @@ # Release History +## 2.0.0 (2025-04-27) +### Breaking Changes + +- Type of `ContinuousAction.Type` has been changed from `*string` to `*ExperimentActionType` +- Type of `DelayAction.Type` has been changed from `*string` to `*ExperimentActionType` +- Type of `DiscreteAction.Type` has been changed from `*string` to `*ExperimentActionType` +- Type of `ErrorAdditionalInfo.Info` has been changed from `any` to `*ErrorAdditionalInfoInfo` +- Type of `Experiment.Identity` has been changed from `*ResourceIdentity` to `*ManagedServiceIdentity` +- Type of `ExperimentAction.Type` has been changed from `*string` to `*ExperimentActionType` +- Type of `ExperimentUpdate.Identity` has been changed from `*ResourceIdentity` to `*ManagedServiceIdentity` +- Enum `ResourceIdentityType` has been removed +- Function `*ExperimentsClient.ExecutionDetails` has been removed +- Function `*ExperimentsClient.GetExecution` has been removed +- Function `*ExperimentsClient.NewListAllExecutionsPager` has been removed +- Function `*OperationsClient.NewListAllPager` has been removed +- Struct `ErrorResponse` has been removed +- Struct `OperationStatus` has been removed +- Struct `Resource` has been removed +- Struct `ResourceIdentity` has been removed +- Struct `TrackedResource` has been removed +- Field `Location` of struct `CapabilityType` has been removed +- Field `OperationStatus` of struct `OperationStatusesClientGetResponse` has been removed +- Field `AdditionalProperties` of struct `TargetListSelector` has been removed +- Field `AdditionalProperties` of struct `TargetQuerySelector` has been removed +- Field `AdditionalProperties` of struct `TargetSelector` has been removed +- Field `Location` of struct `TargetType` has been removed + +### Features Added + +- New enum type `ExperimentActionType` with values `ExperimentActionTypeContinuous`, `ExperimentActionTypeDelay`, `ExperimentActionTypeDiscrete` +- New enum type `ManagedServiceIdentityType` with values `ManagedServiceIdentityTypeNone`, `ManagedServiceIdentityTypeSystemAssigned`, `ManagedServiceIdentityTypeSystemAssignedUserAssigned`, `ManagedServiceIdentityTypeUserAssigned` +- New function `*ClientFactory.NewExperimentExecutionsClient() *ExperimentExecutionsClient` +- New function `NewExperimentExecutionsClient(string, azcore.TokenCredential, *arm.ClientOptions) (*ExperimentExecutionsClient, error)` +- New function `*ExperimentExecutionsClient.GetExecution(context.Context, string, string, string, *ExperimentExecutionsClientGetExecutionOptions) (ExperimentExecutionsClientGetExecutionResponse, error)` +- New function `*ExperimentExecutionsClient.GetExecutionDetails(context.Context, string, string, string, *ExperimentExecutionsClientGetExecutionDetailsOptions) (ExperimentExecutionsClientGetExecutionDetailsResponse, error)` +- New function `*ExperimentExecutionsClient.NewListAllExecutionsPager(string, string, *ExperimentExecutionsClientListAllExecutionsOptions) *runtime.Pager[ExperimentExecutionsClientListAllExecutionsResponse]` +- New function `*OperationsClient.NewListPager(*OperationsClientListOptions) *runtime.Pager[OperationsClientListResponse]` +- New struct `ErrorAdditionalInfoInfo` +- New struct `ManagedServiceIdentity` +- New struct `OperationStatusResult` +- New field `RequiredAzureRoleDefinitionIDs` in struct `CapabilityTypeProperties` +- New field `SystemData` in struct `ExperimentExecution` +- New anonymous field `OperationStatusResult` in struct `OperationStatusesClientGetResponse` + + ## 1.1.0 (2024-03-22) ### Features Added diff --git a/sdk/resourcemanager/chaos/armchaos/README.md b/sdk/resourcemanager/chaos/armchaos/README.md index f2f15e905827..b527df1268d1 100644 --- a/sdk/resourcemanager/chaos/armchaos/README.md +++ b/sdk/resourcemanager/chaos/armchaos/README.md @@ -19,7 +19,7 @@ This project uses [Go modules](https://github.com/golang/go/wiki/Modules) for ve Install the Azure Chaos module: ```sh -go get github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/chaos/armchaos +go get github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/chaos/armchaos/v2 ``` ## Authorization diff --git a/sdk/resourcemanager/chaos/armchaos/autorest.md b/sdk/resourcemanager/chaos/armchaos/autorest.md deleted file mode 100644 index b9f219695dcc..000000000000 --- a/sdk/resourcemanager/chaos/armchaos/autorest.md +++ /dev/null @@ -1,13 +0,0 @@ -### AutoRest Configuration - -> see https://aka.ms/autorest - -``` yaml -azure-arm: true -require: -- https://github.com/Azure/azure-rest-api-specs/blob/e4009d2f8d3bf0271757e522c7d1c1997e193d44/specification/chaos/resource-manager/readme.md -- https://github.com/Azure/azure-rest-api-specs/blob/e4009d2f8d3bf0271757e522c7d1c1997e193d44/specification/chaos/resource-manager/readme.go.md -license-header: MICROSOFT_MIT_NO_VERSION -module-version: 1.1.0 -tag: package-2024-01 -``` \ No newline at end of file diff --git a/sdk/resourcemanager/chaos/armchaos/build.go b/sdk/resourcemanager/chaos/armchaos/build.go deleted file mode 100644 index 87e4894b9e63..000000000000 --- a/sdk/resourcemanager/chaos/armchaos/build.go +++ /dev/null @@ -1,7 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. - -// This file enables 'go generate' to regenerate this specific SDK -//go:generate pwsh ../../../../eng/scripts/build.ps1 -skipBuild -cleanGenerated -format -tidy -generate resourcemanager/chaos/armchaos - -package armchaos diff --git a/sdk/resourcemanager/chaos/armchaos/capabilities_client.go b/sdk/resourcemanager/chaos/armchaos/capabilities_client.go index 74d548e166ec..fd03bbca018d 100644 --- a/sdk/resourcemanager/chaos/armchaos/capabilities_client.go +++ b/sdk/resourcemanager/chaos/armchaos/capabilities_client.go @@ -1,10 +1,6 @@ -//go:build go1.18 -// +build go1.18 - // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. -// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. package armchaos @@ -28,7 +24,7 @@ type CapabilitiesClient struct { } // NewCapabilitiesClient creates a new instance of CapabilitiesClient with the specified values. -// - subscriptionID - GUID that represents an Azure subscription ID. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. // - credential - used to authorize requests. Usually a credential from azidentity. // - options - pass nil to accept the default values. func NewCapabilitiesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*CapabilitiesClient, error) { @@ -46,23 +42,23 @@ func NewCapabilitiesClient(subscriptionID string, credential azcore.TokenCredent // CreateOrUpdate - Create or update a Capability resource that extends a Target resource. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2024-01-01 -// - resourceGroupName - String that represents an Azure resource group. -// - parentProviderNamespace - String that represents a resource provider namespace. -// - parentResourceType - String that represents a resource type. -// - parentResourceName - String that represents a resource name. +// Generated from API version 2025-01-01 +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - parentProviderNamespace - The parent resource provider namespace. +// - parentResourceType - The parent resource type. +// - parentResourceName - The parent resource name. // - targetName - String that represents a Target resource name. // - capabilityName - String that represents a Capability resource name. -// - capability - Capability resource to be created or updated. +// - resource - Capability resource to be created or updated. // - options - CapabilitiesClientCreateOrUpdateOptions contains the optional parameters for the CapabilitiesClient.CreateOrUpdate // method. -func (client *CapabilitiesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, parentProviderNamespace string, parentResourceType string, parentResourceName string, targetName string, capabilityName string, capability Capability, options *CapabilitiesClientCreateOrUpdateOptions) (CapabilitiesClientCreateOrUpdateResponse, error) { +func (client *CapabilitiesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, parentProviderNamespace string, parentResourceType string, parentResourceName string, targetName string, capabilityName string, resource Capability, options *CapabilitiesClientCreateOrUpdateOptions) (CapabilitiesClientCreateOrUpdateResponse, error) { var err error const operationName = "CapabilitiesClient.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, parentProviderNamespace, parentResourceType, parentResourceName, targetName, capabilityName, capability, options) + req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, parentProviderNamespace, parentResourceType, parentResourceName, targetName, capabilityName, resource, options) if err != nil { return CapabilitiesClientCreateOrUpdateResponse{}, err } @@ -70,7 +66,7 @@ func (client *CapabilitiesClient) CreateOrUpdate(ctx context.Context, resourceGr if err != nil { return CapabilitiesClientCreateOrUpdateResponse{}, err } - if !runtime.HasStatusCode(httpResp, http.StatusOK) { + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { err = runtime.NewResponseError(httpResp) return CapabilitiesClientCreateOrUpdateResponse{}, err } @@ -79,7 +75,7 @@ func (client *CapabilitiesClient) CreateOrUpdate(ctx context.Context, resourceGr } // createOrUpdateCreateRequest creates the CreateOrUpdate request. -func (client *CapabilitiesClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, parentProviderNamespace string, parentResourceType string, parentResourceName string, targetName string, capabilityName string, capability Capability, options *CapabilitiesClientCreateOrUpdateOptions) (*policy.Request, error) { +func (client *CapabilitiesClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, parentProviderNamespace string, parentResourceType string, parentResourceName string, targetName string, capabilityName string, resource Capability, _ *CapabilitiesClientCreateOrUpdateOptions) (*policy.Request, error) { urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{parentProviderNamespace}/{parentResourceType}/{parentResourceName}/providers/Microsoft.Chaos/targets/{targetName}/capabilities/{capabilityName}" if client.subscriptionID == "" { return nil, errors.New("parameter client.subscriptionID cannot be empty") @@ -114,10 +110,11 @@ func (client *CapabilitiesClient) createOrUpdateCreateRequest(ctx context.Contex return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2024-01-01") + reqQP.Set("api-version", "2025-01-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} - if err := runtime.MarshalAsJSON(req, capability); err != nil { + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, resource); err != nil { return nil, err } return req, nil @@ -135,11 +132,11 @@ func (client *CapabilitiesClient) createOrUpdateHandleResponse(resp *http.Respon // Delete - Delete a Capability that extends a Target resource. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2024-01-01 -// - resourceGroupName - String that represents an Azure resource group. -// - parentProviderNamespace - String that represents a resource provider namespace. -// - parentResourceType - String that represents a resource type. -// - parentResourceName - String that represents a resource name. +// Generated from API version 2025-01-01 +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - parentProviderNamespace - The parent resource provider namespace. +// - parentResourceType - The parent resource type. +// - parentResourceName - The parent resource name. // - targetName - String that represents a Target resource name. // - capabilityName - String that represents a Capability resource name. // - options - CapabilitiesClientDeleteOptions contains the optional parameters for the CapabilitiesClient.Delete method. @@ -165,7 +162,7 @@ func (client *CapabilitiesClient) Delete(ctx context.Context, resourceGroupName } // deleteCreateRequest creates the Delete request. -func (client *CapabilitiesClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, parentProviderNamespace string, parentResourceType string, parentResourceName string, targetName string, capabilityName string, options *CapabilitiesClientDeleteOptions) (*policy.Request, error) { +func (client *CapabilitiesClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, parentProviderNamespace string, parentResourceType string, parentResourceName string, targetName string, capabilityName string, _ *CapabilitiesClientDeleteOptions) (*policy.Request, error) { urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{parentProviderNamespace}/{parentResourceType}/{parentResourceName}/providers/Microsoft.Chaos/targets/{targetName}/capabilities/{capabilityName}" if client.subscriptionID == "" { return nil, errors.New("parameter client.subscriptionID cannot be empty") @@ -200,7 +197,7 @@ func (client *CapabilitiesClient) deleteCreateRequest(ctx context.Context, resou return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2024-01-01") + reqQP.Set("api-version", "2025-01-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -209,11 +206,11 @@ func (client *CapabilitiesClient) deleteCreateRequest(ctx context.Context, resou // Get - Get a Capability resource that extends a Target resource. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2024-01-01 -// - resourceGroupName - String that represents an Azure resource group. -// - parentProviderNamespace - String that represents a resource provider namespace. -// - parentResourceType - String that represents a resource type. -// - parentResourceName - String that represents a resource name. +// Generated from API version 2025-01-01 +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - parentProviderNamespace - The parent resource provider namespace. +// - parentResourceType - The parent resource type. +// - parentResourceName - The parent resource name. // - targetName - String that represents a Target resource name. // - capabilityName - String that represents a Capability resource name. // - options - CapabilitiesClientGetOptions contains the optional parameters for the CapabilitiesClient.Get method. @@ -240,7 +237,7 @@ func (client *CapabilitiesClient) Get(ctx context.Context, resourceGroupName str } // getCreateRequest creates the Get request. -func (client *CapabilitiesClient) getCreateRequest(ctx context.Context, resourceGroupName string, parentProviderNamespace string, parentResourceType string, parentResourceName string, targetName string, capabilityName string, options *CapabilitiesClientGetOptions) (*policy.Request, error) { +func (client *CapabilitiesClient) getCreateRequest(ctx context.Context, resourceGroupName string, parentProviderNamespace string, parentResourceType string, parentResourceName string, targetName string, capabilityName string, _ *CapabilitiesClientGetOptions) (*policy.Request, error) { urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{parentProviderNamespace}/{parentResourceType}/{parentResourceName}/providers/Microsoft.Chaos/targets/{targetName}/capabilities/{capabilityName}" if client.subscriptionID == "" { return nil, errors.New("parameter client.subscriptionID cannot be empty") @@ -275,7 +272,7 @@ func (client *CapabilitiesClient) getCreateRequest(ctx context.Context, resource return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2024-01-01") + reqQP.Set("api-version", "2025-01-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -290,13 +287,13 @@ func (client *CapabilitiesClient) getHandleResponse(resp *http.Response) (Capabi return result, nil } -// NewListPager - Get a list of Capability resources that extend a Target resource.. +// NewListPager - Get a list of Capability resources that extend a Target resource. // -// Generated from API version 2024-01-01 -// - resourceGroupName - String that represents an Azure resource group. -// - parentProviderNamespace - String that represents a resource provider namespace. -// - parentResourceType - String that represents a resource type. -// - parentResourceName - String that represents a resource name. +// Generated from API version 2025-01-01 +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - parentProviderNamespace - The parent resource provider namespace. +// - parentResourceType - The parent resource type. +// - parentResourceName - The parent resource name. // - targetName - String that represents a Target resource name. // - options - CapabilitiesClientListOptions contains the optional parameters for the CapabilitiesClient.NewListPager method. func (client *CapabilitiesClient) NewListPager(resourceGroupName string, parentProviderNamespace string, parentResourceType string, parentResourceName string, targetName string, options *CapabilitiesClientListOptions) *runtime.Pager[CapabilitiesClientListResponse] { @@ -354,7 +351,7 @@ func (client *CapabilitiesClient) listCreateRequest(ctx context.Context, resourc return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2024-01-01") + reqQP.Set("api-version", "2025-01-01") if options != nil && options.ContinuationToken != nil { reqQP.Set("continuationToken", *options.ContinuationToken) } diff --git a/sdk/resourcemanager/chaos/armchaos/capabilities_client_example_test.go b/sdk/resourcemanager/chaos/armchaos/capabilities_client_example_test.go index b4d2220e83e1..5ce39b17dfcc 100644 --- a/sdk/resourcemanager/chaos/armchaos/capabilities_client_example_test.go +++ b/sdk/resourcemanager/chaos/armchaos/capabilities_client_example_test.go @@ -1,153 +1,160 @@ -//go:build go1.18 -// +build go1.18 - // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. -// DO NOT EDIT. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. package armchaos_test import ( "context" - "log" - "github.com/Azure/azure-sdk-for-go/sdk/azidentity" - "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/chaos/armchaos" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/chaos/armchaos/v2" + "log" ) -// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/e4009d2f8d3bf0271757e522c7d1c1997e193d44/specification/chaos/resource-manager/Microsoft.Chaos/stable/2024-01-01/examples/ListCapabilities.json -func ExampleCapabilitiesClient_NewListPager() { +// Generated from example definition: 2025-01-01/Capabilities_CreateOrUpdate.json +func ExampleCapabilitiesClient_CreateOrUpdate() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() - clientFactory, err := armchaos.NewClientFactory("", cred, nil) + clientFactory, err := armchaos.NewClientFactory("6b052e15-03d3-4f17-b2e1-be7f07588291", cred, nil) if err != nil { log.Fatalf("failed to create client: %v", err) } - pager := clientFactory.NewCapabilitiesClient().NewListPager("exampleRG", "Microsoft.Compute", "virtualMachines", "exampleVM", "Microsoft-VirtualMachine", &armchaos.CapabilitiesClientListOptions{ContinuationToken: nil}) - for pager.More() { - page, err := pager.NextPage(ctx) - if err != nil { - log.Fatalf("failed to advance page: %v", err) - } - for _, v := range page.Value { - // You could use page here. We use blank identifier for just demo purposes. - _ = v - } - // If the HTTP response code is 200 as defined in example definition, your page structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. - // page.CapabilityListResult = armchaos.CapabilityListResult{ - // Value: []*armchaos.Capability{ - // { - // Name: to.Ptr("Shutdown-1.0"), - // Type: to.Ptr("Microsoft.Chaos/targets/capabilities"), - // ID: to.Ptr("/subscriptions/6b052e15-03d3-4f17-b2e1-be7f07588291/resourceGroups/exampleRG/providers/Microsoft.Compute/virtualMachines/exampleVM/providers/Microsoft.Chaos/targets/Microsoft-VirtualMachine/capabilities/Shutdown-1.0"), - // Properties: &armchaos.CapabilityProperties{ - // Description: to.Ptr("Shutdown an Azure Virtual Machine for a defined period of time."), - // ParametersSchema: to.Ptr("https://schema.centralus.chaos-prod.azure.com/targets/Microsoft-VirtualMachine/capabilities/Shutdown-1.0.json"), - // Publisher: to.Ptr("Microsoft"), - // TargetType: to.Ptr("VirtualMachine"), - // Urn: to.Ptr("urn:csci:microsoft:virtualMachine:shutdown/1.0"), - // }, - // SystemData: &armchaos.SystemData{ - // CreatedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2020-05-14T05:08:38.466Z"); return t}()), - // LastModifiedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2020-05-14T05:08:38.466Z"); return t}()), - // }, - // }}, - // } + res, err := clientFactory.NewCapabilitiesClient().CreateOrUpdate(ctx, "exampleRG", "Microsoft.Compute", "virtualMachines", "exampleVM", "Microsoft-VirtualMachine", "Shutdown-1.0", armchaos.Capability{ + Properties: &armchaos.CapabilityProperties{}, + }, nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) } + // You could use response here. We use blank identifier for just demo purposes. + _ = res + // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // res = armchaos.CapabilitiesClientCreateOrUpdateResponse{ + // Capability: &armchaos.Capability{ + // Name: to.Ptr("Shutdown-1.0"), + // Type: to.Ptr("Microsoft.Chaos/targets/capabilities"), + // ID: to.Ptr("/subscriptions/6b052e15-03d3-4f17-b2e1-be7f07588291/resourceGroups/exampleRG/providers/Microsoft.Compute/virtualMachines/exampleVM/providers/Microsoft.Chaos/targets/Microsoft-VirtualMachine/capabilities/Shutdown-1.0"), + // Properties: &armchaos.CapabilityProperties{ + // Description: to.Ptr("Shutdown an Azure Virtual Machine for a defined period of time."), + // ParametersSchema: to.Ptr("https://schema.centralus.chaos-prod.azure.com/targets/Microsoft-VirtualMachine/capabilities/Shutdown-1.0.json"), + // Publisher: to.Ptr("Microsoft"), + // TargetType: to.Ptr("VirtualMachine"), + // Urn: to.Ptr("urn:csci:microsoft:virtualMachine:shutdown/1.0"), + // }, + // SystemData: &armchaos.SystemData{ + // CreatedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2020-05-14T05:08:38.4662189Z"); return t}()), + // LastModifiedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2020-05-14T05:08:38.4662189Z"); return t}()), + // }, + // }, + // } } -// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/e4009d2f8d3bf0271757e522c7d1c1997e193d44/specification/chaos/resource-manager/Microsoft.Chaos/stable/2024-01-01/examples/GetCapability.json -func ExampleCapabilitiesClient_Get() { +// Generated from example definition: 2025-01-01/Capabilities_Delete.json +func ExampleCapabilitiesClient_Delete() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() - clientFactory, err := armchaos.NewClientFactory("", cred, nil) + clientFactory, err := armchaos.NewClientFactory("6b052e15-03d3-4f17-b2e1-be7f07588291", cred, nil) if err != nil { log.Fatalf("failed to create client: %v", err) } - res, err := clientFactory.NewCapabilitiesClient().Get(ctx, "exampleRG", "Microsoft.Compute", "virtualMachines", "exampleVM", "Microsoft-VirtualMachine", "Shutdown-1.0", nil) + res, err := clientFactory.NewCapabilitiesClient().Delete(ctx, "exampleRG", "Microsoft.Compute", "virtualMachines", "exampleVM", "Microsoft-VirtualMachine", "Shutdown-1.0", nil) if err != nil { log.Fatalf("failed to finish the request: %v", err) } // You could use response here. We use blank identifier for just demo purposes. _ = res // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. - // res.Capability = armchaos.Capability{ - // Name: to.Ptr("Shutdown-1.0"), - // Type: to.Ptr("Microsoft.Chaos/targets/capabilities"), - // ID: to.Ptr("/subscriptions/6b052e15-03d3-4f17-b2e1-be7f07588291/resourceGroups/exampleRG/providers/Microsoft.Compute/virtualMachines/exampleVM/providers/Microsoft.Chaos/targets/Microsoft-VirtualMachine/capabilities/Shutdown-1.0"), - // Properties: &armchaos.CapabilityProperties{ - // Description: to.Ptr("Shutdown an Azure Virtual Machine for a defined period of time."), - // ParametersSchema: to.Ptr("https://schema.centralus.chaos-prod.azure.com/targets/Microsoft-VirtualMachine/capabilities/Shutdown-1.0.json"), - // Publisher: to.Ptr("Microsoft"), - // TargetType: to.Ptr("VirtualMachine"), - // Urn: to.Ptr("urn:csci:microsoft:virtualMachine:shutdown/1.0"), - // }, - // SystemData: &armchaos.SystemData{ - // CreatedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2020-05-14T05:08:38.466Z"); return t}()), - // LastModifiedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2020-05-14T05:08:38.466Z"); return t}()), - // }, + // res = armchaos.CapabilitiesClientDeleteResponse{ // } } -// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/e4009d2f8d3bf0271757e522c7d1c1997e193d44/specification/chaos/resource-manager/Microsoft.Chaos/stable/2024-01-01/examples/DeleteCapability.json -func ExampleCapabilitiesClient_Delete() { +// Generated from example definition: 2025-01-01/Capabilities_Get.json +func ExampleCapabilitiesClient_Get() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() - clientFactory, err := armchaos.NewClientFactory("", cred, nil) + clientFactory, err := armchaos.NewClientFactory("6b052e15-03d3-4f17-b2e1-be7f07588291", cred, nil) if err != nil { log.Fatalf("failed to create client: %v", err) } - _, err = clientFactory.NewCapabilitiesClient().Delete(ctx, "exampleRG", "Microsoft.Compute", "virtualMachines", "exampleVM", "Microsoft-VirtualMachine", "Shutdown-1.0", nil) + res, err := clientFactory.NewCapabilitiesClient().Get(ctx, "exampleRG", "Microsoft.Compute", "virtualMachines", "exampleVM", "Microsoft-VirtualMachine", "Shutdown-1.0", nil) if err != nil { log.Fatalf("failed to finish the request: %v", err) } + // You could use response here. We use blank identifier for just demo purposes. + _ = res + // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // res = armchaos.CapabilitiesClientGetResponse{ + // Capability: &armchaos.Capability{ + // Name: to.Ptr("Shutdown-1.0"), + // Type: to.Ptr("Microsoft.Chaos/targets/capabilities"), + // ID: to.Ptr("/subscriptions/6b052e15-03d3-4f17-b2e1-be7f07588291/resourceGroups/exampleRG/providers/Microsoft.Compute/virtualMachines/exampleVM/providers/Microsoft.Chaos/targets/Microsoft-VirtualMachine/capabilities/Shutdown-1.0"), + // Properties: &armchaos.CapabilityProperties{ + // Description: to.Ptr("Shutdown an Azure Virtual Machine for a defined period of time."), + // ParametersSchema: to.Ptr("https://schema.centralus.chaos-prod.azure.com/targets/Microsoft-VirtualMachine/capabilities/Shutdown-1.0.json"), + // Publisher: to.Ptr("Microsoft"), + // TargetType: to.Ptr("VirtualMachine"), + // Urn: to.Ptr("urn:csci:microsoft:virtualMachine:shutdown/1.0"), + // }, + // SystemData: &armchaos.SystemData{ + // CreatedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2020-05-14T05:08:38.4662189Z"); return t}()), + // LastModifiedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2020-05-14T05:08:38.4662189Z"); return t}()), + // }, + // }, + // } } -// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/e4009d2f8d3bf0271757e522c7d1c1997e193d44/specification/chaos/resource-manager/Microsoft.Chaos/stable/2024-01-01/examples/CreateUpdateCapability.json -func ExampleCapabilitiesClient_CreateOrUpdate() { +// Generated from example definition: 2025-01-01/Capabilities_List.json +func ExampleCapabilitiesClient_NewListPager() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() - clientFactory, err := armchaos.NewClientFactory("", cred, nil) + clientFactory, err := armchaos.NewClientFactory("6b052e15-03d3-4f17-b2e1-be7f07588291", cred, nil) if err != nil { log.Fatalf("failed to create client: %v", err) } - res, err := clientFactory.NewCapabilitiesClient().CreateOrUpdate(ctx, "exampleRG", "Microsoft.Compute", "virtualMachines", "exampleVM", "Microsoft-VirtualMachine", "Shutdown-1.0", armchaos.Capability{ - Properties: &armchaos.CapabilityProperties{}, - }, nil) - if err != nil { - log.Fatalf("failed to finish the request: %v", err) + pager := clientFactory.NewCapabilitiesClient().NewListPager("exampleRG", "Microsoft.Compute", "virtualMachines", "exampleVM", "Microsoft-VirtualMachine", nil) + for pager.More() { + page, err := pager.NextPage(ctx) + if err != nil { + log.Fatalf("failed to advance page: %v", err) + } + for _, v := range page.Value { + // You could use page here. We use blank identifier for just demo purposes. + _ = v + } + // If the HTTP response code is 200 as defined in example definition, your page structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // page = armchaos.CapabilitiesClientListResponse{ + // CapabilityListResult: armchaos.CapabilityListResult{ + // NextLink: to.Ptr("https://management.azure.com/subscriptions/6b052e15-03d3-4f17-b2e1-be7f07588291/resourceGroups/exampleRG/providers/Microsoft.Compute/virtualMachines/exampleVM/providers/Microsoft.Chaos/targets/Microsoft-VirtualMachine/capabilities?continuationToken=&api-version=2024-11-01-preview"), + // Value: []*armchaos.Capability{ + // { + // Name: to.Ptr("Shutdown-1.0"), + // Type: to.Ptr("Microsoft.Chaos/targets/capabilities"), + // ID: to.Ptr("/subscriptions/6b052e15-03d3-4f17-b2e1-be7f07588291/resourceGroups/exampleRG/providers/Microsoft.Compute/virtualMachines/exampleVM/providers/Microsoft.Chaos/targets/Microsoft-VirtualMachine/capabilities/Shutdown-1.0"), + // Properties: &armchaos.CapabilityProperties{ + // Description: to.Ptr("Shutdown an Azure Virtual Machine for a defined period of time."), + // ParametersSchema: to.Ptr("https://schema.centralus.chaos-prod.azure.com/targets/Microsoft-VirtualMachine/capabilities/Shutdown-1.0.json"), + // Publisher: to.Ptr("Microsoft"), + // TargetType: to.Ptr("VirtualMachine"), + // Urn: to.Ptr("urn:csci:microsoft:virtualMachine:shutdown/1.0"), + // }, + // SystemData: &armchaos.SystemData{ + // CreatedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2020-05-14T05:08:38.4662189Z"); return t}()), + // LastModifiedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2020-05-14T05:08:38.4662189Z"); return t}()), + // }, + // }, + // }, + // }, + // } } - // You could use response here. We use blank identifier for just demo purposes. - _ = res - // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. - // res.Capability = armchaos.Capability{ - // Name: to.Ptr("Shutdown-1.0"), - // Type: to.Ptr("Microsoft.Chaos/targets/capabilities"), - // ID: to.Ptr("/subscriptions/6b052e15-03d3-4f17-b2e1-be7f07588291/resourceGroups/exampleRG/providers/Microsoft.Compute/virtualMachines/exampleVM/providers/Microsoft.Chaos/targets/Microsoft-VirtualMachine/capabilities/Shutdown-1.0"), - // Properties: &armchaos.CapabilityProperties{ - // Description: to.Ptr("Shutdown an Azure Virtual Machine for a defined period of time."), - // ParametersSchema: to.Ptr("https://schema.centralus.chaos-prod.azure.com/targets/Microsoft-VirtualMachine/capabilities/Shutdown-1.0.json"), - // Publisher: to.Ptr("Microsoft"), - // TargetType: to.Ptr("VirtualMachine"), - // Urn: to.Ptr("urn:csci:microsoft:virtualMachine:shutdown/1.0"), - // }, - // SystemData: &armchaos.SystemData{ - // CreatedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2020-05-14T05:08:38.466Z"); return t}()), - // LastModifiedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2020-05-14T05:08:38.466Z"); return t}()), - // }, - // } } diff --git a/sdk/resourcemanager/chaos/armchaos/capabilities_live_test.go b/sdk/resourcemanager/chaos/armchaos/capabilities_live_test.go index a81b322e53d5..d29576907918 100644 --- a/sdk/resourcemanager/chaos/armchaos/capabilities_live_test.go +++ b/sdk/resourcemanager/chaos/armchaos/capabilities_live_test.go @@ -15,7 +15,7 @@ import ( "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" "github.com/Azure/azure-sdk-for-go/sdk/internal/recording" - "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/chaos/armchaos" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/chaos/armchaos/v2" "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/internal/v3/testutil" "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/resources/armresources" "github.com/stretchr/testify/suite" diff --git a/sdk/resourcemanager/chaos/armchaos/capabilitytypes_client.go b/sdk/resourcemanager/chaos/armchaos/capabilitytypes_client.go index e5573ac5209b..c42329958d65 100644 --- a/sdk/resourcemanager/chaos/armchaos/capabilitytypes_client.go +++ b/sdk/resourcemanager/chaos/armchaos/capabilitytypes_client.go @@ -1,10 +1,6 @@ -//go:build go1.18 -// +build go1.18 - // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. -// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. package armchaos @@ -28,7 +24,7 @@ type CapabilityTypesClient struct { } // NewCapabilityTypesClient creates a new instance of CapabilityTypesClient with the specified values. -// - subscriptionID - GUID that represents an Azure subscription ID. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. // - credential - used to authorize requests. Usually a credential from azidentity. // - options - pass nil to accept the default values. func NewCapabilityTypesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*CapabilityTypesClient, error) { @@ -46,18 +42,18 @@ func NewCapabilityTypesClient(subscriptionID string, credential azcore.TokenCred // Get - Get a Capability Type resource for given Target Type and location. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2024-01-01 -// - locationName - String that represents a Location resource name. +// Generated from API version 2025-01-01 +// - location - The name of the Azure region. // - targetTypeName - String that represents a Target Type resource name. // - capabilityTypeName - String that represents a Capability Type resource name. // - options - CapabilityTypesClientGetOptions contains the optional parameters for the CapabilityTypesClient.Get method. -func (client *CapabilityTypesClient) Get(ctx context.Context, locationName string, targetTypeName string, capabilityTypeName string, options *CapabilityTypesClientGetOptions) (CapabilityTypesClientGetResponse, error) { +func (client *CapabilityTypesClient) Get(ctx context.Context, location string, targetTypeName string, capabilityTypeName string, options *CapabilityTypesClientGetOptions) (CapabilityTypesClientGetResponse, error) { var err error const operationName = "CapabilityTypesClient.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, locationName, targetTypeName, capabilityTypeName, options) + req, err := client.getCreateRequest(ctx, location, targetTypeName, capabilityTypeName, options) if err != nil { return CapabilityTypesClientGetResponse{}, err } @@ -74,16 +70,16 @@ func (client *CapabilityTypesClient) Get(ctx context.Context, locationName strin } // getCreateRequest creates the Get request. -func (client *CapabilityTypesClient) getCreateRequest(ctx context.Context, locationName string, targetTypeName string, capabilityTypeName string, options *CapabilityTypesClientGetOptions) (*policy.Request, error) { - urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Chaos/locations/{locationName}/targetTypes/{targetTypeName}/capabilityTypes/{capabilityTypeName}" +func (client *CapabilityTypesClient) getCreateRequest(ctx context.Context, location string, targetTypeName string, capabilityTypeName string, _ *CapabilityTypesClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Chaos/locations/{location}/targetTypes/{targetTypeName}/capabilityTypes/{capabilityTypeName}" if client.subscriptionID == "" { return nil, errors.New("parameter client.subscriptionID cannot be empty") } urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) - if locationName == "" { - return nil, errors.New("parameter locationName cannot be empty") + if location == "" { + return nil, errors.New("parameter location cannot be empty") } - urlPath = strings.ReplaceAll(urlPath, "{locationName}", url.PathEscape(locationName)) + urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location)) if targetTypeName == "" { return nil, errors.New("parameter targetTypeName cannot be empty") } @@ -97,7 +93,7 @@ func (client *CapabilityTypesClient) getCreateRequest(ctx context.Context, locat return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2024-01-01") + reqQP.Set("api-version", "2025-01-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -114,12 +110,12 @@ func (client *CapabilityTypesClient) getHandleResponse(resp *http.Response) (Cap // NewListPager - Get a list of Capability Type resources for given Target Type and location. // -// Generated from API version 2024-01-01 -// - locationName - String that represents a Location resource name. +// Generated from API version 2025-01-01 +// - location - The name of the Azure region. // - targetTypeName - String that represents a Target Type resource name. // - options - CapabilityTypesClientListOptions contains the optional parameters for the CapabilityTypesClient.NewListPager // method. -func (client *CapabilityTypesClient) NewListPager(locationName string, targetTypeName string, options *CapabilityTypesClientListOptions) *runtime.Pager[CapabilityTypesClientListResponse] { +func (client *CapabilityTypesClient) NewListPager(location string, targetTypeName string, options *CapabilityTypesClientListOptions) *runtime.Pager[CapabilityTypesClientListResponse] { return runtime.NewPager(runtime.PagingHandler[CapabilityTypesClientListResponse]{ More: func(page CapabilityTypesClientListResponse) bool { return page.NextLink != nil && len(*page.NextLink) > 0 @@ -131,7 +127,7 @@ func (client *CapabilityTypesClient) NewListPager(locationName string, targetTyp nextLink = *page.NextLink } resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { - return client.listCreateRequest(ctx, locationName, targetTypeName, options) + return client.listCreateRequest(ctx, location, targetTypeName, options) }, nil) if err != nil { return CapabilityTypesClientListResponse{}, err @@ -143,16 +139,16 @@ func (client *CapabilityTypesClient) NewListPager(locationName string, targetTyp } // listCreateRequest creates the List request. -func (client *CapabilityTypesClient) listCreateRequest(ctx context.Context, locationName string, targetTypeName string, options *CapabilityTypesClientListOptions) (*policy.Request, error) { - urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Chaos/locations/{locationName}/targetTypes/{targetTypeName}/capabilityTypes" +func (client *CapabilityTypesClient) listCreateRequest(ctx context.Context, location string, targetTypeName string, options *CapabilityTypesClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Chaos/locations/{location}/targetTypes/{targetTypeName}/capabilityTypes" if client.subscriptionID == "" { return nil, errors.New("parameter client.subscriptionID cannot be empty") } urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) - if locationName == "" { - return nil, errors.New("parameter locationName cannot be empty") + if location == "" { + return nil, errors.New("parameter location cannot be empty") } - urlPath = strings.ReplaceAll(urlPath, "{locationName}", url.PathEscape(locationName)) + urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location)) if targetTypeName == "" { return nil, errors.New("parameter targetTypeName cannot be empty") } @@ -162,7 +158,7 @@ func (client *CapabilityTypesClient) listCreateRequest(ctx context.Context, loca return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2024-01-01") + reqQP.Set("api-version", "2025-01-01") if options != nil && options.ContinuationToken != nil { reqQP.Set("continuationToken", *options.ContinuationToken) } diff --git a/sdk/resourcemanager/chaos/armchaos/capabilitytypes_client_example_test.go b/sdk/resourcemanager/chaos/armchaos/capabilitytypes_client_example_test.go index 8c3ecedd0c1a..5cb16e6a3081 100644 --- a/sdk/resourcemanager/chaos/armchaos/capabilitytypes_client_example_test.go +++ b/sdk/resourcemanager/chaos/armchaos/capabilitytypes_client_example_test.go @@ -1,34 +1,77 @@ -//go:build go1.18 -// +build go1.18 - // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. -// DO NOT EDIT. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. package armchaos_test import ( "context" - "log" - "github.com/Azure/azure-sdk-for-go/sdk/azidentity" - "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/chaos/armchaos" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/chaos/armchaos/v2" + "log" ) -// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/e4009d2f8d3bf0271757e522c7d1c1997e193d44/specification/chaos/resource-manager/Microsoft.Chaos/stable/2024-01-01/examples/ListCapabilityTypes.json +// Generated from example definition: 2025-01-01/CapabilityTypes_Get.json +func ExampleCapabilityTypesClient_Get() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armchaos.NewClientFactory("6b052e15-03d3-4f17-b2e1-be7f07588291", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + res, err := clientFactory.NewCapabilityTypesClient().Get(ctx, "westus2", "Microsoft-VirtualMachine", "Shutdown-1.0", nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + // You could use response here. We use blank identifier for just demo purposes. + _ = res + // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // res = armchaos.CapabilityTypesClientGetResponse{ + // CapabilityType: &armchaos.CapabilityType{ + // Name: to.Ptr("Shutdown-1.0"), + // Type: to.Ptr("Microsoft.Chaos/locations/targetTypes/capabilityTypes"), + // ID: to.Ptr("/subscriptions/6b052e15-03d3-4f17-b2e1-be7f07588291/providers/Microsoft.Chaos/locations/westus2/targetTypes/Microsoft-VirtualMachine/capabilityTypes/Shutdown-1.0"), + // Properties: &armchaos.CapabilityTypeProperties{ + // Description: to.Ptr("Shutdown an Azure Virtual Machine for a defined period of time."), + // DisplayName: to.Ptr("Shutdown VM"), + // Kind: to.Ptr("fault"), + // ParametersSchema: to.Ptr("https://schema.centralus.chaos-prod.azure.com/targets/Microsoft-VirtualMachine/capabilities/Shutdown-1.0.json"), + // Publisher: to.Ptr("Microsoft"), + // RuntimeProperties: &armchaos.CapabilityTypePropertiesRuntimeProperties{ + // Kind: to.Ptr("continuous"), + // }, + // TargetType: to.Ptr("VirtualMachine"), + // Urn: to.Ptr("urn:csci:microsoft:virtualMachine:shutdown/1.0"), + // AzureRbacActions: []*string{ + // to.Ptr("Microsoft.Compute/virtualMachines/poweroff/action"), + // to.Ptr("Microsoft.Compute/virtualMachines/start/action"), + // to.Ptr("Microsoft.Compute/virtualMachines/instanceView/read"), + // to.Ptr("Microsoft.Compute/virtualMachines/read"), + // to.Ptr("Microsoft.Compute/locations/operations/read"), + // }, + // RequiredAzureRoleDefinitionIDs: []*string{ + // to.Ptr("acdd72a7-3385-48ef-bd42-f606fba81ae0"), + // }, + // }, + // }, + // } +} + +// Generated from example definition: 2025-01-01/CapabilityTypes_List.json func ExampleCapabilityTypesClient_NewListPager() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() - clientFactory, err := armchaos.NewClientFactory("", cred, nil) + clientFactory, err := armchaos.NewClientFactory("6b052e15-03d3-4f17-b2e1-be7f07588291", cred, nil) if err != nil { log.Fatalf("failed to create client: %v", err) } - pager := clientFactory.NewCapabilityTypesClient().NewListPager("westus2", "Microsoft-VirtualMachine", &armchaos.CapabilityTypesClientListOptions{ContinuationToken: nil}) + pager := clientFactory.NewCapabilityTypesClient().NewListPager("westus2", "Microsoft-VirtualMachine", nil) for pager.More() { page, err := pager.NextPage(ctx) if err != nil { @@ -39,62 +82,39 @@ func ExampleCapabilityTypesClient_NewListPager() { _ = v } // If the HTTP response code is 200 as defined in example definition, your page structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. - // page.CapabilityTypeListResult = armchaos.CapabilityTypeListResult{ - // Value: []*armchaos.CapabilityType{ - // { - // Name: to.Ptr("Shutdown-1.0"), - // Type: to.Ptr("Microsoft.Chaos/locations/targetTypes/capabilityTypes"), - // ID: to.Ptr("/subscriptions/6b052e15-03d3-4f17-b2e1-be7f07588291/providers/Microsoft.Chaos/locations/westus2/targetTypes/Microsoft-VirtualMachine/capabilityTypes/Shutdown-1.0"), - // Properties: &armchaos.CapabilityTypeProperties{ - // Description: to.Ptr("Shutdown an Azure Virtual Machine for a defined period of time."), - // DisplayName: to.Ptr("Shutdown VM"), - // Kind: to.Ptr("fault"), - // ParametersSchema: to.Ptr("https://schema.centralus.chaos-prod.azure.com/targets/Microsoft-VirtualMachine/capabilities/Shutdown-1.0.json"), - // Publisher: to.Ptr("Microsoft"), - // RuntimeProperties: &armchaos.CapabilityTypePropertiesRuntimeProperties{ - // Kind: to.Ptr("continuous"), + // page = armchaos.CapabilityTypesClientListResponse{ + // CapabilityTypeListResult: armchaos.CapabilityTypeListResult{ + // NextLink: to.Ptr("https://management.azure.com/subscriptions/6b052e15-03d3-4f17-b2e1-be7f07588291/providers/Microsoft.Chaos/locations/westus2/targetTypes/Microsoft-VirtualMachine/capabilityTypes?continuationToken=&api-version=2024-11-01-preview"), + // Value: []*armchaos.CapabilityType{ + // { + // Name: to.Ptr("Shutdown-1.0"), + // Type: to.Ptr("Microsoft.Chaos/locations/targetTypes/capabilityTypes"), + // ID: to.Ptr("/subscriptions/6b052e15-03d3-4f17-b2e1-be7f07588291/providers/Microsoft.Chaos/locations/westus2/targetTypes/Microsoft-VirtualMachine/capabilityTypes/Shutdown-1.0"), + // Properties: &armchaos.CapabilityTypeProperties{ + // Description: to.Ptr("Shutdown an Azure Virtual Machine for a defined period of time."), + // DisplayName: to.Ptr("Shutdown VM"), + // Kind: to.Ptr("fault"), + // ParametersSchema: to.Ptr("https://schema.centralus.chaos-prod.azure.com/targets/Microsoft-VirtualMachine/capabilities/Shutdown-1.0.json"), + // Publisher: to.Ptr("Microsoft"), + // RuntimeProperties: &armchaos.CapabilityTypePropertiesRuntimeProperties{ + // Kind: to.Ptr("continuous"), + // }, + // TargetType: to.Ptr("VirtualMachine"), + // Urn: to.Ptr("urn:csci:microsoft:virtualMachine:shutdown/1.0"), + // AzureRbacActions: []*string{ + // to.Ptr("Microsoft.Compute/virtualMachines/poweroff/action"), + // to.Ptr("Microsoft.Compute/virtualMachines/start/action"), + // to.Ptr("Microsoft.Compute/virtualMachines/instanceView/read"), + // to.Ptr("Microsoft.Compute/virtualMachines/read"), + // to.Ptr("Microsoft.Compute/locations/operations/read"), + // }, + // RequiredAzureRoleDefinitionIDs: []*string{ + // to.Ptr("acdd72a7-3385-48ef-bd42-f606fba81ae0"), + // }, // }, - // TargetType: to.Ptr("VirtualMachine"), - // Urn: to.Ptr("urn:csci:microsoft:virtualMachine:shutdown/1.0"), // }, - // }}, + // }, + // }, // } } } - -// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/e4009d2f8d3bf0271757e522c7d1c1997e193d44/specification/chaos/resource-manager/Microsoft.Chaos/stable/2024-01-01/examples/GetCapabilityType.json -func ExampleCapabilityTypesClient_Get() { - cred, err := azidentity.NewDefaultAzureCredential(nil) - if err != nil { - log.Fatalf("failed to obtain a credential: %v", err) - } - ctx := context.Background() - clientFactory, err := armchaos.NewClientFactory("", cred, nil) - if err != nil { - log.Fatalf("failed to create client: %v", err) - } - res, err := clientFactory.NewCapabilityTypesClient().Get(ctx, "westus2", "Microsoft-VirtualMachine", "Shutdown-1.0", nil) - if err != nil { - log.Fatalf("failed to finish the request: %v", err) - } - // You could use response here. We use blank identifier for just demo purposes. - _ = res - // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. - // res.CapabilityType = armchaos.CapabilityType{ - // Name: to.Ptr("Shutdown-1.0"), - // Type: to.Ptr("Microsoft.Chaos/locations/targetTypes/capabilityTypes"), - // ID: to.Ptr("/subscriptions/6b052e15-03d3-4f17-b2e1-be7f07588291/Microsoft.Chaos/locations/westus2/targetTypes/Microsoft-VirtualMachine/capabilityTypes/Shutdown-1.0"), - // Properties: &armchaos.CapabilityTypeProperties{ - // Description: to.Ptr("Shutdown an Azure Virtual Machine for a defined period of time."), - // DisplayName: to.Ptr("Shutdown VM"), - // Kind: to.Ptr("fault"), - // ParametersSchema: to.Ptr("https://schema.centralus.chaos-prod.azure.com/targets/Microsoft-VirtualMachine/capabilities/Shutdown-1.0.json"), - // Publisher: to.Ptr("Microsoft"), - // RuntimeProperties: &armchaos.CapabilityTypePropertiesRuntimeProperties{ - // Kind: to.Ptr("continuous"), - // }, - // TargetType: to.Ptr("VirtualMachine"), - // Urn: to.Ptr("urn:csci:microsoft:virtualMachine:shutdown/1.0"), - // }, - // } -} diff --git a/sdk/resourcemanager/chaos/armchaos/capabilitytypes_live_test.go b/sdk/resourcemanager/chaos/armchaos/capabilitytypes_live_test.go index 645111fd6af6..8f9d703db531 100644 --- a/sdk/resourcemanager/chaos/armchaos/capabilitytypes_live_test.go +++ b/sdk/resourcemanager/chaos/armchaos/capabilitytypes_live_test.go @@ -14,7 +14,7 @@ import ( "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/internal/recording" - "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/chaos/armchaos" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/chaos/armchaos/v2" "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/internal/v3/testutil" "github.com/stretchr/testify/suite" ) diff --git a/sdk/resourcemanager/chaos/armchaos/client_factory.go b/sdk/resourcemanager/chaos/armchaos/client_factory.go index 6f27987f337c..7ed7c657b30d 100644 --- a/sdk/resourcemanager/chaos/armchaos/client_factory.go +++ b/sdk/resourcemanager/chaos/armchaos/client_factory.go @@ -1,10 +1,6 @@ -//go:build go1.18 -// +build go1.18 - // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. -// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. package armchaos @@ -22,7 +18,7 @@ type ClientFactory struct { // 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 - GUID that represents an Azure subscription ID. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. // - credential - used to authorize requests. Usually a credential from azidentity. // - options - pass nil to accept the default values. func NewClientFactory(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ClientFactory, error) { @@ -52,6 +48,14 @@ func (c *ClientFactory) NewCapabilityTypesClient() *CapabilityTypesClient { } } +// NewExperimentExecutionsClient creates a new instance of ExperimentExecutionsClient. +func (c *ClientFactory) NewExperimentExecutionsClient() *ExperimentExecutionsClient { + return &ExperimentExecutionsClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + // NewExperimentsClient creates a new instance of ExperimentsClient. func (c *ClientFactory) NewExperimentsClient() *ExperimentsClient { return &ExperimentsClient{ diff --git a/sdk/resourcemanager/chaos/armchaos/constants.go b/sdk/resourcemanager/chaos/armchaos/constants.go index c3bb6f1fd184..1d6bae485cc8 100644 --- a/sdk/resourcemanager/chaos/armchaos/constants.go +++ b/sdk/resourcemanager/chaos/armchaos/constants.go @@ -1,22 +1,19 @@ -//go:build go1.18 -// +build go1.18 - // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. -// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. package armchaos const ( moduleName = "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/chaos/armchaos" - moduleVersion = "v1.1.0" + moduleVersion = "v2.0.0" ) -// ActionType - Enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. +// ActionType - Extensible enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. type ActionType string const ( + // ActionTypeInternal - Actions are for internal-only APIs. ActionTypeInternal ActionType = "Internal" ) @@ -27,14 +24,18 @@ func PossibleActionTypeValues() []ActionType { } } -// CreatedByType - The type of identity that created the resource. +// CreatedByType - The kind of entity that created the resource. type CreatedByType string const ( - CreatedByTypeApplication CreatedByType = "Application" - CreatedByTypeKey CreatedByType = "Key" + // CreatedByTypeApplication - The entity was created by an application. + CreatedByTypeApplication CreatedByType = "Application" + // CreatedByTypeKey - The entity was created by a key. + CreatedByTypeKey CreatedByType = "Key" + // CreatedByTypeManagedIdentity - The entity was created by a managed identity. CreatedByTypeManagedIdentity CreatedByType = "ManagedIdentity" - CreatedByTypeUser CreatedByType = "User" + // CreatedByTypeUser - The entity was created by a user. + CreatedByTypeUser CreatedByType = "User" ) // PossibleCreatedByTypeValues returns the possible values for the CreatedByType const type. @@ -47,10 +48,29 @@ func PossibleCreatedByTypeValues() []CreatedByType { } } -// FilterType - Enum that discriminates between filter types. Currently only Simple type is supported. +// ExperimentActionType - Enum union of Chaos experiment action types. +type ExperimentActionType string + +const ( + ExperimentActionTypeContinuous ExperimentActionType = "continuous" + ExperimentActionTypeDelay ExperimentActionType = "delay" + ExperimentActionTypeDiscrete ExperimentActionType = "discrete" +) + +// PossibleExperimentActionTypeValues returns the possible values for the ExperimentActionType const type. +func PossibleExperimentActionTypeValues() []ExperimentActionType { + return []ExperimentActionType{ + ExperimentActionTypeContinuous, + ExperimentActionTypeDelay, + ExperimentActionTypeDiscrete, + } +} + +// FilterType - Enum that discriminates between filter types. Currently only `Simple` type is supported. type FilterType string const ( + // FilterTypeSimple - Simple filter type. FilterTypeSimple FilterType = "Simple" ) @@ -61,13 +81,40 @@ func PossibleFilterTypeValues() []FilterType { } } +// ManagedServiceIdentityType - Type of managed service identity (where both SystemAssigned and UserAssigned types are allowed). +type ManagedServiceIdentityType string + +const ( + // ManagedServiceIdentityTypeNone - No managed identity. + ManagedServiceIdentityTypeNone ManagedServiceIdentityType = "None" + // ManagedServiceIdentityTypeSystemAssigned - System assigned managed identity. + ManagedServiceIdentityTypeSystemAssigned ManagedServiceIdentityType = "SystemAssigned" + // ManagedServiceIdentityTypeSystemAssignedUserAssigned - System and user assigned managed identity. + ManagedServiceIdentityTypeSystemAssignedUserAssigned ManagedServiceIdentityType = "SystemAssigned,UserAssigned" + // ManagedServiceIdentityTypeUserAssigned - User assigned managed identity. + ManagedServiceIdentityTypeUserAssigned ManagedServiceIdentityType = "UserAssigned" +) + +// PossibleManagedServiceIdentityTypeValues returns the possible values for the ManagedServiceIdentityType const type. +func PossibleManagedServiceIdentityTypeValues() []ManagedServiceIdentityType { + return []ManagedServiceIdentityType{ + ManagedServiceIdentityTypeNone, + ManagedServiceIdentityTypeSystemAssigned, + ManagedServiceIdentityTypeSystemAssignedUserAssigned, + ManagedServiceIdentityTypeUserAssigned, + } +} + // 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" + // OriginSystem - Indicates the operation is initiated by a system. + OriginSystem Origin = "system" + // OriginUser - Indicates the operation is initiated by a user. + OriginUser Origin = "user" + // OriginUserSystem - Indicates the operation is initiated by a user or system. OriginUserSystem Origin = "user,system" ) @@ -84,12 +131,18 @@ func PossibleOriginValues() []Origin { type ProvisioningState string const ( - ProvisioningStateCanceled ProvisioningState = "Canceled" - ProvisioningStateCreating ProvisioningState = "Creating" - ProvisioningStateDeleting ProvisioningState = "Deleting" - ProvisioningStateFailed ProvisioningState = "Failed" + // ProvisioningStateCanceled - Resource creation was canceled. + ProvisioningStateCanceled ProvisioningState = "Canceled" + // ProvisioningStateCreating - Initial creation in progress. + ProvisioningStateCreating ProvisioningState = "Creating" + // ProvisioningStateDeleting - Deletion in progress. + ProvisioningStateDeleting ProvisioningState = "Deleting" + // ProvisioningStateFailed - Resource creation failed. + ProvisioningStateFailed ProvisioningState = "Failed" + // ProvisioningStateSucceeded - Resource has been created. ProvisioningStateSucceeded ProvisioningState = "Succeeded" - ProvisioningStateUpdating ProvisioningState = "Updating" + // ProvisioningStateUpdating - Update in progress. + ProvisioningStateUpdating ProvisioningState = "Updating" ) // PossibleProvisioningStateValues returns the possible values for the ProvisioningState const type. @@ -104,29 +157,13 @@ func PossibleProvisioningStateValues() []ProvisioningState { } } -// ResourceIdentityType - String of the resource identity type. -type ResourceIdentityType string - -const ( - ResourceIdentityTypeNone ResourceIdentityType = "None" - ResourceIdentityTypeSystemAssigned ResourceIdentityType = "SystemAssigned" - ResourceIdentityTypeUserAssigned ResourceIdentityType = "UserAssigned" -) - -// PossibleResourceIdentityTypeValues returns the possible values for the ResourceIdentityType const type. -func PossibleResourceIdentityTypeValues() []ResourceIdentityType { - return []ResourceIdentityType{ - ResourceIdentityTypeNone, - ResourceIdentityTypeSystemAssigned, - ResourceIdentityTypeUserAssigned, - } -} - // SelectorType - Enum of the selector type. type SelectorType string const ( - SelectorTypeList SelectorType = "List" + // SelectorTypeList - List selector type. + SelectorTypeList SelectorType = "List" + // SelectorTypeQuery - Query selector type. SelectorTypeQuery SelectorType = "Query" ) @@ -142,6 +179,7 @@ func PossibleSelectorTypeValues() []SelectorType { type TargetReferenceType string const ( + // TargetReferenceTypeChaosTarget - Chaos target reference type. TargetReferenceTypeChaosTarget TargetReferenceType = "ChaosTarget" ) diff --git a/sdk/resourcemanager/chaos/armchaos/experimentexecutions_client.go b/sdk/resourcemanager/chaos/armchaos/experimentexecutions_client.go new file mode 100644 index 000000000000..f8b9669c3fc7 --- /dev/null +++ b/sdk/resourcemanager/chaos/armchaos/experimentexecutions_client.go @@ -0,0 +1,245 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armchaos + +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" +) + +// ExperimentExecutionsClient contains the methods for the ExperimentExecutions group. +// Don't use this type directly, use NewExperimentExecutionsClient() instead. +type ExperimentExecutionsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewExperimentExecutionsClient creates a new instance of ExperimentExecutionsClient 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 NewExperimentExecutionsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ExperimentExecutionsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &ExperimentExecutionsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// GetExecution - Get an execution of an Experiment resource. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2025-01-01 +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - experimentName - String that represents a Experiment resource name. +// - executionID - GUID that represents a Experiment execution detail. +// - options - ExperimentExecutionsClientGetExecutionOptions contains the optional parameters for the ExperimentExecutionsClient.GetExecution +// method. +func (client *ExperimentExecutionsClient) GetExecution(ctx context.Context, resourceGroupName string, experimentName string, executionID string, options *ExperimentExecutionsClientGetExecutionOptions) (ExperimentExecutionsClientGetExecutionResponse, error) { + var err error + const operationName = "ExperimentExecutionsClient.GetExecution" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getExecutionCreateRequest(ctx, resourceGroupName, experimentName, executionID, options) + if err != nil { + return ExperimentExecutionsClientGetExecutionResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ExperimentExecutionsClientGetExecutionResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ExperimentExecutionsClientGetExecutionResponse{}, err + } + resp, err := client.getExecutionHandleResponse(httpResp) + return resp, err +} + +// getExecutionCreateRequest creates the GetExecution request. +func (client *ExperimentExecutionsClient) getExecutionCreateRequest(ctx context.Context, resourceGroupName string, experimentName string, executionID string, _ *ExperimentExecutionsClientGetExecutionOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Chaos/experiments/{experimentName}/executions/{executionId}" + 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 experimentName == "" { + return nil, errors.New("parameter experimentName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{experimentName}", url.PathEscape(experimentName)) + if executionID == "" { + return nil, errors.New("parameter executionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{executionId}", url.PathEscape(executionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2025-01-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getExecutionHandleResponse handles the GetExecution response. +func (client *ExperimentExecutionsClient) getExecutionHandleResponse(resp *http.Response) (ExperimentExecutionsClientGetExecutionResponse, error) { + result := ExperimentExecutionsClientGetExecutionResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ExperimentExecution); err != nil { + return ExperimentExecutionsClientGetExecutionResponse{}, err + } + return result, nil +} + +// GetExecutionDetails - Execution details of an experiment resource. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2025-01-01 +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - experimentName - String that represents a Experiment resource name. +// - executionID - GUID that represents a Experiment execution detail. +// - options - ExperimentExecutionsClientGetExecutionDetailsOptions contains the optional parameters for the ExperimentExecutionsClient.GetExecutionDetails +// method. +func (client *ExperimentExecutionsClient) GetExecutionDetails(ctx context.Context, resourceGroupName string, experimentName string, executionID string, options *ExperimentExecutionsClientGetExecutionDetailsOptions) (ExperimentExecutionsClientGetExecutionDetailsResponse, error) { + var err error + const operationName = "ExperimentExecutionsClient.GetExecutionDetails" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getExecutionDetailsCreateRequest(ctx, resourceGroupName, experimentName, executionID, options) + if err != nil { + return ExperimentExecutionsClientGetExecutionDetailsResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ExperimentExecutionsClientGetExecutionDetailsResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ExperimentExecutionsClientGetExecutionDetailsResponse{}, err + } + resp, err := client.getExecutionDetailsHandleResponse(httpResp) + return resp, err +} + +// getExecutionDetailsCreateRequest creates the GetExecutionDetails request. +func (client *ExperimentExecutionsClient) getExecutionDetailsCreateRequest(ctx context.Context, resourceGroupName string, experimentName string, executionID string, _ *ExperimentExecutionsClientGetExecutionDetailsOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Chaos/experiments/{experimentName}/executions/{executionId}/getExecutionDetails" + 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 experimentName == "" { + return nil, errors.New("parameter experimentName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{experimentName}", url.PathEscape(experimentName)) + if executionID == "" { + return nil, errors.New("parameter executionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{executionId}", url.PathEscape(executionID)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2025-01-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getExecutionDetailsHandleResponse handles the GetExecutionDetails response. +func (client *ExperimentExecutionsClient) getExecutionDetailsHandleResponse(resp *http.Response) (ExperimentExecutionsClientGetExecutionDetailsResponse, error) { + result := ExperimentExecutionsClientGetExecutionDetailsResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ExperimentExecutionDetails); err != nil { + return ExperimentExecutionsClientGetExecutionDetailsResponse{}, err + } + return result, nil +} + +// NewListAllExecutionsPager - Get a list of executions of an Experiment resource. +// +// Generated from API version 2025-01-01 +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - experimentName - String that represents a Experiment resource name. +// - options - ExperimentExecutionsClientListAllExecutionsOptions contains the optional parameters for the ExperimentExecutionsClient.NewListAllExecutionsPager +// method. +func (client *ExperimentExecutionsClient) NewListAllExecutionsPager(resourceGroupName string, experimentName string, options *ExperimentExecutionsClientListAllExecutionsOptions) *runtime.Pager[ExperimentExecutionsClientListAllExecutionsResponse] { + return runtime.NewPager(runtime.PagingHandler[ExperimentExecutionsClientListAllExecutionsResponse]{ + More: func(page ExperimentExecutionsClientListAllExecutionsResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ExperimentExecutionsClientListAllExecutionsResponse) (ExperimentExecutionsClientListAllExecutionsResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "ExperimentExecutionsClient.NewListAllExecutionsPager") + 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.listAllExecutionsCreateRequest(ctx, resourceGroupName, experimentName, options) + }, nil) + if err != nil { + return ExperimentExecutionsClientListAllExecutionsResponse{}, err + } + return client.listAllExecutionsHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listAllExecutionsCreateRequest creates the ListAllExecutions request. +func (client *ExperimentExecutionsClient) listAllExecutionsCreateRequest(ctx context.Context, resourceGroupName string, experimentName string, _ *ExperimentExecutionsClientListAllExecutionsOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Chaos/experiments/{experimentName}/executions" + 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 experimentName == "" { + return nil, errors.New("parameter experimentName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{experimentName}", url.PathEscape(experimentName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2025-01-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listAllExecutionsHandleResponse handles the ListAllExecutions response. +func (client *ExperimentExecutionsClient) listAllExecutionsHandleResponse(resp *http.Response) (ExperimentExecutionsClientListAllExecutionsResponse, error) { + result := ExperimentExecutionsClientListAllExecutionsResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ExperimentExecutionListResult); err != nil { + return ExperimentExecutionsClientListAllExecutionsResponse{}, err + } + return result, nil +} diff --git a/sdk/resourcemanager/chaos/armchaos/experimentexecutions_client_example_test.go b/sdk/resourcemanager/chaos/armchaos/experimentexecutions_client_example_test.go new file mode 100644 index 000000000000..e37b758d2baa --- /dev/null +++ b/sdk/resourcemanager/chaos/armchaos/experimentexecutions_client_example_test.go @@ -0,0 +1,169 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armchaos_test + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azidentity" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/chaos/armchaos/v2" + "log" +) + +// Generated from example definition: 2025-01-01/Experiments_GetExecution.json +func ExampleExperimentExecutionsClient_GetExecution() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armchaos.NewClientFactory("6b052e15-03d3-4f17-b2e1-be7f07588291", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + res, err := clientFactory.NewExperimentExecutionsClient().GetExecution(ctx, "exampleRG", "exampleExperiment", "f24500ad-744e-4a26-864b-b76199eac333", nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + // You could use response here. We use blank identifier for just demo purposes. + _ = res + // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // res = armchaos.ExperimentExecutionsClientGetExecutionResponse{ + // ExperimentExecution: &armchaos.ExperimentExecution{ + // Name: to.Ptr("f24500ad-744e-4a26-864b-b76199eac333"), + // Type: to.Ptr("Microsoft.Chaos/experiments/executions"), + // ID: to.Ptr("/subscriptions/6b052e15-03d3-4f17-b2e1-be7f07588291/resourceGroups/exampleRG/providers/Microsoft.Chaos/experiments/exampleExperiment/executions/f24500ad-744e-4a26-864b-b76199eac333"), + // Properties: &armchaos.ExperimentExecutionProperties{ + // StartedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2020-12-14T21:52:52.2552574Z"); return t}()), + // Status: to.Ptr("failed"), + // StoppedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2020-12-14T21:56:18.9281956Z"); return t}()), + // }, + // }, + // } +} + +// Generated from example definition: 2025-01-01/Experiments_ExecutionDetails.json +func ExampleExperimentExecutionsClient_GetExecutionDetails() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armchaos.NewClientFactory("6b052e15-03d3-4f17-b2e1-be7f07588291", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + res, err := clientFactory.NewExperimentExecutionsClient().GetExecutionDetails(ctx, "exampleRG", "exampleExperiment", "f24500ad-744e-4a26-864b-b76199eac333", nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + // You could use response here. We use blank identifier for just demo purposes. + _ = res + // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // res = armchaos.ExperimentExecutionsClientGetExecutionDetailsResponse{ + // ExperimentExecutionDetails: &armchaos.ExperimentExecutionDetails{ + // Name: to.Ptr("f24500ad-744e-4a26-864b-b76199eac333"), + // Type: to.Ptr("Microsoft.Chaos/experiments/executions/getExecutionDetails"), + // ID: to.Ptr("/subscriptions/6b052e15-03d3-4f17-b2e1-be7f07588291/resourceGroups/exampleRG/providers/Microsoft.Chaos/experiments/exampleExperiment/executions/f24500ad-744e-4a26-864b-b76199eac333/getExecutionDetails"), + // Properties: &armchaos.ExperimentExecutionDetailsProperties{ + // FailureReason: to.Ptr("Dependency failure"), + // LastActionAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2020-12-14T21:52:52.2552574Z"); return t}()), + // RunInformation: &armchaos.ExperimentExecutionDetailsPropertiesRunInformation{ + // Steps: []*armchaos.StepStatus{ + // { + // Branches: []*armchaos.BranchStatus{ + // { + // Actions: []*armchaos.ActionStatus{ + // { + // ActionID: to.Ptr("59499d33-6751-4b6e-a1f6-58f4d56a040a"), + // ActionName: to.Ptr("urn:provider:agent-v2:Microsoft.Azure.Chaos.Fault.CPUPressureAllProcessors"), + // EndTime: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2020-12-14T13:56:13.6270153-08:00"); return t}()), + // StartTime: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2020-12-14T13:56:13.6270153-08:00"); return t}()), + // Status: to.Ptr("failed"), + // Targets: []*armchaos.ExperimentExecutionActionTargetDetailsProperties{ + // { + // Status: to.Ptr("succeeded"), + // Target: to.Ptr("/subscriptions/6b052e15-03d3-4f17-b2e1-be7f07588291/resourceGroups/exampleRG/providers/Microsoft.Compute/virtualMachines/VM1"), + // TargetCompletedTime: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2021-04-02T17:30:55+00:00"); return t}()), + // TargetFailedTime: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2021-04-02T16:30:55+00:00"); return t}()), + // }, + // { + // Status: to.Ptr("failed"), + // Target: to.Ptr("/subscriptions/6b052e15-03d3-4f17-b2e1-be7f07588291/resourceGroups/exampleRG/providers/Microsoft.Compute/virtualMachines/VM1"), + // TargetCompletedTime: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2021-04-02T17:30:55+00:00"); return t}()), + // TargetFailedTime: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2021-04-02T16:30:55+00:00"); return t}()), + // }, + // }, + // }, + // }, + // BranchID: to.Ptr("FirstBranch"), + // BranchName: to.Ptr("FirstBranch"), + // Status: to.Ptr("failed"), + // }, + // }, + // Status: to.Ptr("failed"), + // StepID: to.Ptr("FirstStep"), + // StepName: to.Ptr("FirstStep"), + // }, + // }, + // }, + // StartedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2020-12-14T21:52:52.2552574Z"); return t}()), + // Status: to.Ptr("failed"), + // StoppedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2020-12-14T21:56:18.9281956Z"); return t}()), + // }, + // }, + // } +} + +// Generated from example definition: 2025-01-01/Experiments_ListAllExecutions.json +func ExampleExperimentExecutionsClient_NewListAllExecutionsPager() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armchaos.NewClientFactory("6b052e15-03d3-4f17-b2e1-be7f07588291", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + pager := clientFactory.NewExperimentExecutionsClient().NewListAllExecutionsPager("exampleRG", "exampleExperiment", nil) + for pager.More() { + page, err := pager.NextPage(ctx) + if err != nil { + log.Fatalf("failed to advance page: %v", err) + } + for _, v := range page.Value { + // You could use page here. We use blank identifier for just demo purposes. + _ = v + } + // If the HTTP response code is 200 as defined in example definition, your page structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // page = armchaos.ExperimentExecutionsClientListAllExecutionsResponse{ + // ExperimentExecutionListResult: armchaos.ExperimentExecutionListResult{ + // NextLink: to.Ptr("https://management.azure.com/subscriptions/6b052e15-03d3-4f17-b2e1-be7f07588291/resourceGroups/exampleRG/providers/Microsoft.Chaos/experiments/exampleExperiment/executionDetails?continuationToken=&api-version=2025-01-01"), + // Value: []*armchaos.ExperimentExecution{ + // { + // Name: to.Ptr("f24500ad-744e-4a26-864b-b76199eac333"), + // Type: to.Ptr("Microsoft.Chaos/experiments/executions"), + // ID: to.Ptr("/subscriptions/6b052e15-03d3-4f17-b2e1-be7f07588291/resourceGroups/exampleRG/providers/Microsoft.Chaos/experiments/exampleExperiment/executions/f24500ad-744e-4a26-864b-b76199eac333"), + // Properties: &armchaos.ExperimentExecutionProperties{ + // StartedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2020-12-14T21:52:52.2552574Z"); return t}()), + // Status: to.Ptr("failed"), + // StoppedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2020-12-14T21:56:18.9281956Z"); return t}()), + // }, + // }, + // { + // Name: to.Ptr("14d98367-52ef-4596-be4f-53fc81bbfc33"), + // Type: to.Ptr("Microsoft.Chaos/experiments/executions"), + // ID: to.Ptr("/subscriptions/6b052e15-03d3-4f17-b2e1-be7f07588291/resourceGroups/exampleRG/providers/Microsoft.Chaos/experiments/exampleExperiment/executions/14d98367-52ef-4596-be4f-53fc81bbfc33"), + // Properties: &armchaos.ExperimentExecutionProperties{ + // StartedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2020-12-14T21:52:52.2552574Z"); return t}()), + // Status: to.Ptr("success"), + // StoppedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2020-12-14T21:56:18.9281956Z"); return t}()), + // }, + // }, + // }, + // }, + // } + } +} diff --git a/sdk/resourcemanager/chaos/armchaos/experiments_client.go b/sdk/resourcemanager/chaos/armchaos/experiments_client.go index 404257553384..5a9f88ee4ca7 100644 --- a/sdk/resourcemanager/chaos/armchaos/experiments_client.go +++ b/sdk/resourcemanager/chaos/armchaos/experiments_client.go @@ -1,10 +1,6 @@ -//go:build go1.18 -// +build go1.18 - // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. -// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. package armchaos @@ -29,7 +25,7 @@ type ExperimentsClient struct { } // NewExperimentsClient creates a new instance of ExperimentsClient with the specified values. -// - subscriptionID - GUID that represents an Azure subscription ID. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. // - credential - used to authorize requests. Usually a credential from azidentity. // - options - pass nil to accept the default values. func NewExperimentsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ExperimentsClient, error) { @@ -47,8 +43,8 @@ func NewExperimentsClient(subscriptionID string, credential azcore.TokenCredenti // BeginCancel - Cancel a running Experiment resource. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2024-01-01 -// - resourceGroupName - String that represents an Azure resource group. +// Generated from API version 2025-01-01 +// - resourceGroupName - The name of the resource group. The name is case insensitive. // - experimentName - String that represents a Experiment resource name. // - options - ExperimentsClientBeginCancelOptions contains the optional parameters for the ExperimentsClient.BeginCancel method. func (client *ExperimentsClient) BeginCancel(ctx context.Context, resourceGroupName string, experimentName string, options *ExperimentsClientBeginCancelOptions) (*runtime.Poller[ExperimentsClientCancelResponse], error) { @@ -58,8 +54,7 @@ func (client *ExperimentsClient) BeginCancel(ctx context.Context, resourceGroupN return nil, err } poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[ExperimentsClientCancelResponse]{ - FinalStateVia: runtime.FinalStateViaLocation, - Tracer: client.internal.Tracer(), + Tracer: client.internal.Tracer(), }) return poller, err } else { @@ -72,7 +67,7 @@ func (client *ExperimentsClient) BeginCancel(ctx context.Context, resourceGroupN // Cancel - Cancel a running Experiment resource. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2024-01-01 +// Generated from API version 2025-01-01 func (client *ExperimentsClient) cancel(ctx context.Context, resourceGroupName string, experimentName string, options *ExperimentsClientBeginCancelOptions) (*http.Response, error) { var err error const operationName = "ExperimentsClient.BeginCancel" @@ -95,7 +90,7 @@ func (client *ExperimentsClient) cancel(ctx context.Context, resourceGroupName s } // cancelCreateRequest creates the Cancel request. -func (client *ExperimentsClient) cancelCreateRequest(ctx context.Context, resourceGroupName string, experimentName string, options *ExperimentsClientBeginCancelOptions) (*policy.Request, error) { +func (client *ExperimentsClient) cancelCreateRequest(ctx context.Context, resourceGroupName string, experimentName string, _ *ExperimentsClientBeginCancelOptions) (*policy.Request, error) { urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Chaos/experiments/{experimentName}/cancel" if client.subscriptionID == "" { return nil, errors.New("parameter client.subscriptionID cannot be empty") @@ -114,7 +109,7 @@ func (client *ExperimentsClient) cancelCreateRequest(ctx context.Context, resour return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2024-01-01") + reqQP.Set("api-version", "2025-01-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -123,21 +118,20 @@ func (client *ExperimentsClient) cancelCreateRequest(ctx context.Context, resour // BeginCreateOrUpdate - Create or update a Experiment resource. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2024-01-01 -// - resourceGroupName - String that represents an Azure resource group. +// Generated from API version 2025-01-01 +// - resourceGroupName - The name of the resource group. The name is case insensitive. // - experimentName - String that represents a Experiment resource name. -// - experiment - Experiment resource to be created or updated. +// - resource - Experiment resource to be created or updated. // - options - ExperimentsClientBeginCreateOrUpdateOptions contains the optional parameters for the ExperimentsClient.BeginCreateOrUpdate // method. -func (client *ExperimentsClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, experimentName string, experiment Experiment, options *ExperimentsClientBeginCreateOrUpdateOptions) (*runtime.Poller[ExperimentsClientCreateOrUpdateResponse], error) { +func (client *ExperimentsClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, experimentName string, resource Experiment, options *ExperimentsClientBeginCreateOrUpdateOptions) (*runtime.Poller[ExperimentsClientCreateOrUpdateResponse], error) { if options == nil || options.ResumeToken == "" { - resp, err := client.createOrUpdate(ctx, resourceGroupName, experimentName, experiment, options) + resp, err := client.createOrUpdate(ctx, resourceGroupName, experimentName, resource, options) if err != nil { return nil, err } poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[ExperimentsClientCreateOrUpdateResponse]{ - FinalStateVia: runtime.FinalStateViaAzureAsyncOp, - Tracer: client.internal.Tracer(), + Tracer: client.internal.Tracer(), }) return poller, err } else { @@ -150,14 +144,14 @@ func (client *ExperimentsClient) BeginCreateOrUpdate(ctx context.Context, resour // CreateOrUpdate - Create or update a Experiment resource. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2024-01-01 -func (client *ExperimentsClient) createOrUpdate(ctx context.Context, resourceGroupName string, experimentName string, experiment Experiment, options *ExperimentsClientBeginCreateOrUpdateOptions) (*http.Response, error) { +// Generated from API version 2025-01-01 +func (client *ExperimentsClient) createOrUpdate(ctx context.Context, resourceGroupName string, experimentName string, resource Experiment, options *ExperimentsClientBeginCreateOrUpdateOptions) (*http.Response, error) { var err error const operationName = "ExperimentsClient.BeginCreateOrUpdate" 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, experimentName, experiment, options) + req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, experimentName, resource, options) if err != nil { return nil, err } @@ -173,7 +167,7 @@ func (client *ExperimentsClient) createOrUpdate(ctx context.Context, resourceGro } // createOrUpdateCreateRequest creates the CreateOrUpdate request. -func (client *ExperimentsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, experimentName string, experiment Experiment, options *ExperimentsClientBeginCreateOrUpdateOptions) (*policy.Request, error) { +func (client *ExperimentsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, experimentName string, resource Experiment, _ *ExperimentsClientBeginCreateOrUpdateOptions) (*policy.Request, error) { urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Chaos/experiments/{experimentName}" if client.subscriptionID == "" { return nil, errors.New("parameter client.subscriptionID cannot be empty") @@ -192,10 +186,11 @@ func (client *ExperimentsClient) createOrUpdateCreateRequest(ctx context.Context return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2024-01-01") + reqQP.Set("api-version", "2025-01-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} - if err := runtime.MarshalAsJSON(req, experiment); err != nil { + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, resource); err != nil { return nil, err } return req, nil @@ -204,8 +199,8 @@ func (client *ExperimentsClient) createOrUpdateCreateRequest(ctx context.Context // BeginDelete - Delete a Experiment resource. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2024-01-01 -// - resourceGroupName - String that represents an Azure resource group. +// Generated from API version 2025-01-01 +// - resourceGroupName - The name of the resource group. The name is case insensitive. // - experimentName - String that represents a Experiment resource name. // - options - ExperimentsClientBeginDeleteOptions contains the optional parameters for the ExperimentsClient.BeginDelete method. func (client *ExperimentsClient) BeginDelete(ctx context.Context, resourceGroupName string, experimentName string, options *ExperimentsClientBeginDeleteOptions) (*runtime.Poller[ExperimentsClientDeleteResponse], error) { @@ -215,8 +210,7 @@ func (client *ExperimentsClient) BeginDelete(ctx context.Context, resourceGroupN return nil, err } poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[ExperimentsClientDeleteResponse]{ - FinalStateVia: runtime.FinalStateViaLocation, - Tracer: client.internal.Tracer(), + Tracer: client.internal.Tracer(), }) return poller, err } else { @@ -229,7 +223,7 @@ func (client *ExperimentsClient) BeginDelete(ctx context.Context, resourceGroupN // Delete - Delete a Experiment resource. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2024-01-01 +// Generated from API version 2025-01-01 func (client *ExperimentsClient) deleteOperation(ctx context.Context, resourceGroupName string, experimentName string, options *ExperimentsClientBeginDeleteOptions) (*http.Response, error) { var err error const operationName = "ExperimentsClient.BeginDelete" @@ -244,7 +238,7 @@ func (client *ExperimentsClient) deleteOperation(ctx context.Context, resourceGr if err != nil { return nil, err } - if !runtime.HasStatusCode(httpResp, http.StatusAccepted) { + if !runtime.HasStatusCode(httpResp, http.StatusAccepted, http.StatusNoContent) { err = runtime.NewResponseError(httpResp) return nil, err } @@ -252,7 +246,7 @@ func (client *ExperimentsClient) deleteOperation(ctx context.Context, resourceGr } // deleteCreateRequest creates the Delete request. -func (client *ExperimentsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, experimentName string, options *ExperimentsClientBeginDeleteOptions) (*policy.Request, error) { +func (client *ExperimentsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, experimentName string, _ *ExperimentsClientBeginDeleteOptions) (*policy.Request, error) { urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Chaos/experiments/{experimentName}" if client.subscriptionID == "" { return nil, errors.New("parameter client.subscriptionID cannot be empty") @@ -271,87 +265,17 @@ func (client *ExperimentsClient) deleteCreateRequest(ctx context.Context, resour return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2024-01-01") - req.Raw().URL.RawQuery = reqQP.Encode() - req.Raw().Header["Accept"] = []string{"application/json"} - return req, nil -} - -// ExecutionDetails - Execution details of an experiment resource. -// If the operation fails it returns an *azcore.ResponseError type. -// -// Generated from API version 2024-01-01 -// - resourceGroupName - String that represents an Azure resource group. -// - experimentName - String that represents a Experiment resource name. -// - executionID - GUID that represents a Experiment execution detail. -// - options - ExperimentsClientExecutionDetailsOptions contains the optional parameters for the ExperimentsClient.ExecutionDetails -// method. -func (client *ExperimentsClient) ExecutionDetails(ctx context.Context, resourceGroupName string, experimentName string, executionID string, options *ExperimentsClientExecutionDetailsOptions) (ExperimentsClientExecutionDetailsResponse, error) { - var err error - const operationName = "ExperimentsClient.ExecutionDetails" - ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) - ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) - defer func() { endSpan(err) }() - req, err := client.executionDetailsCreateRequest(ctx, resourceGroupName, experimentName, executionID, options) - if err != nil { - return ExperimentsClientExecutionDetailsResponse{}, err - } - httpResp, err := client.internal.Pipeline().Do(req) - if err != nil { - return ExperimentsClientExecutionDetailsResponse{}, err - } - if !runtime.HasStatusCode(httpResp, http.StatusOK) { - err = runtime.NewResponseError(httpResp) - return ExperimentsClientExecutionDetailsResponse{}, err - } - resp, err := client.executionDetailsHandleResponse(httpResp) - return resp, err -} - -// executionDetailsCreateRequest creates the ExecutionDetails request. -func (client *ExperimentsClient) executionDetailsCreateRequest(ctx context.Context, resourceGroupName string, experimentName string, executionID string, options *ExperimentsClientExecutionDetailsOptions) (*policy.Request, error) { - urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Chaos/experiments/{experimentName}/executions/{executionId}/getExecutionDetails" - 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 experimentName == "" { - return nil, errors.New("parameter experimentName cannot be empty") - } - urlPath = strings.ReplaceAll(urlPath, "{experimentName}", url.PathEscape(experimentName)) - if executionID == "" { - return nil, errors.New("parameter executionID cannot be empty") - } - urlPath = strings.ReplaceAll(urlPath, "{executionId}", url.PathEscape(executionID)) - req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) - if err != nil { - return nil, err - } - reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2024-01-01") + reqQP.Set("api-version", "2025-01-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil } -// executionDetailsHandleResponse handles the ExecutionDetails response. -func (client *ExperimentsClient) executionDetailsHandleResponse(resp *http.Response) (ExperimentsClientExecutionDetailsResponse, error) { - result := ExperimentsClientExecutionDetailsResponse{} - if err := runtime.UnmarshalAsJSON(resp, &result.ExperimentExecutionDetails); err != nil { - return ExperimentsClientExecutionDetailsResponse{}, err - } - return result, nil -} - // Get - Get a Experiment resource. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2024-01-01 -// - resourceGroupName - String that represents an Azure resource group. +// Generated from API version 2025-01-01 +// - resourceGroupName - The name of the resource group. The name is case insensitive. // - experimentName - String that represents a Experiment resource name. // - options - ExperimentsClientGetOptions contains the optional parameters for the ExperimentsClient.Get method. func (client *ExperimentsClient) Get(ctx context.Context, resourceGroupName string, experimentName string, options *ExperimentsClientGetOptions) (ExperimentsClientGetResponse, error) { @@ -377,7 +301,7 @@ func (client *ExperimentsClient) Get(ctx context.Context, resourceGroupName stri } // getCreateRequest creates the Get request. -func (client *ExperimentsClient) getCreateRequest(ctx context.Context, resourceGroupName string, experimentName string, options *ExperimentsClientGetOptions) (*policy.Request, error) { +func (client *ExperimentsClient) getCreateRequest(ctx context.Context, resourceGroupName string, experimentName string, _ *ExperimentsClientGetOptions) (*policy.Request, error) { urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Chaos/experiments/{experimentName}" if client.subscriptionID == "" { return nil, errors.New("parameter client.subscriptionID cannot be empty") @@ -396,7 +320,7 @@ func (client *ExperimentsClient) getCreateRequest(ctx context.Context, resourceG return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2024-01-01") + reqQP.Set("api-version", "2025-01-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -411,80 +335,10 @@ func (client *ExperimentsClient) getHandleResponse(resp *http.Response) (Experim return result, nil } -// GetExecution - Get an execution of an Experiment resource. -// If the operation fails it returns an *azcore.ResponseError type. -// -// Generated from API version 2024-01-01 -// - resourceGroupName - String that represents an Azure resource group. -// - experimentName - String that represents a Experiment resource name. -// - executionID - GUID that represents a Experiment execution detail. -// - options - ExperimentsClientGetExecutionOptions contains the optional parameters for the ExperimentsClient.GetExecution -// method. -func (client *ExperimentsClient) GetExecution(ctx context.Context, resourceGroupName string, experimentName string, executionID string, options *ExperimentsClientGetExecutionOptions) (ExperimentsClientGetExecutionResponse, error) { - var err error - const operationName = "ExperimentsClient.GetExecution" - ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) - ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) - defer func() { endSpan(err) }() - req, err := client.getExecutionCreateRequest(ctx, resourceGroupName, experimentName, executionID, options) - if err != nil { - return ExperimentsClientGetExecutionResponse{}, err - } - httpResp, err := client.internal.Pipeline().Do(req) - if err != nil { - return ExperimentsClientGetExecutionResponse{}, err - } - if !runtime.HasStatusCode(httpResp, http.StatusOK) { - err = runtime.NewResponseError(httpResp) - return ExperimentsClientGetExecutionResponse{}, err - } - resp, err := client.getExecutionHandleResponse(httpResp) - return resp, err -} - -// getExecutionCreateRequest creates the GetExecution request. -func (client *ExperimentsClient) getExecutionCreateRequest(ctx context.Context, resourceGroupName string, experimentName string, executionID string, options *ExperimentsClientGetExecutionOptions) (*policy.Request, error) { - urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Chaos/experiments/{experimentName}/executions/{executionId}" - 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 experimentName == "" { - return nil, errors.New("parameter experimentName cannot be empty") - } - urlPath = strings.ReplaceAll(urlPath, "{experimentName}", url.PathEscape(experimentName)) - if executionID == "" { - return nil, errors.New("parameter executionID cannot be empty") - } - urlPath = strings.ReplaceAll(urlPath, "{executionId}", url.PathEscape(executionID)) - req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) - if err != nil { - return nil, err - } - reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2024-01-01") - req.Raw().URL.RawQuery = reqQP.Encode() - req.Raw().Header["Accept"] = []string{"application/json"} - return req, nil -} - -// getExecutionHandleResponse handles the GetExecution response. -func (client *ExperimentsClient) getExecutionHandleResponse(resp *http.Response) (ExperimentsClientGetExecutionResponse, error) { - result := ExperimentsClientGetExecutionResponse{} - if err := runtime.UnmarshalAsJSON(resp, &result.ExperimentExecution); err != nil { - return ExperimentsClientGetExecutionResponse{}, err - } - return result, nil -} - // NewListPager - Get a list of Experiment resources in a resource group. // -// Generated from API version 2024-01-01 -// - resourceGroupName - String that represents an Azure resource group. +// Generated from API version 2025-01-01 +// - resourceGroupName - The name of the resource group. The name is case insensitive. // - options - ExperimentsClientListOptions contains the optional parameters for the ExperimentsClient.NewListPager method. func (client *ExperimentsClient) NewListPager(resourceGroupName string, options *ExperimentsClientListOptions) *runtime.Pager[ExperimentsClientListResponse] { return runtime.NewPager(runtime.PagingHandler[ExperimentsClientListResponse]{ @@ -525,7 +379,7 @@ func (client *ExperimentsClient) listCreateRequest(ctx context.Context, resource return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2024-01-01") + reqQP.Set("api-version", "2025-01-01") if options != nil && options.ContinuationToken != nil { reqQP.Set("continuationToken", *options.ContinuationToken) } @@ -548,7 +402,7 @@ func (client *ExperimentsClient) listHandleResponse(resp *http.Response) (Experi // NewListAllPager - Get a list of Experiment resources in a subscription. // -// Generated from API version 2024-01-01 +// Generated from API version 2025-01-01 // - options - ExperimentsClientListAllOptions contains the optional parameters for the ExperimentsClient.NewListAllPager method. func (client *ExperimentsClient) NewListAllPager(options *ExperimentsClientListAllOptions) *runtime.Pager[ExperimentsClientListAllResponse] { return runtime.NewPager(runtime.PagingHandler[ExperimentsClientListAllResponse]{ @@ -585,7 +439,7 @@ func (client *ExperimentsClient) listAllCreateRequest(ctx context.Context, optio return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2024-01-01") + reqQP.Set("api-version", "2025-01-01") if options != nil && options.ContinuationToken != nil { reqQP.Set("continuationToken", *options.ContinuationToken) } @@ -606,76 +460,11 @@ func (client *ExperimentsClient) listAllHandleResponse(resp *http.Response) (Exp return result, nil } -// NewListAllExecutionsPager - Get a list of executions of an Experiment resource. -// -// Generated from API version 2024-01-01 -// - resourceGroupName - String that represents an Azure resource group. -// - experimentName - String that represents a Experiment resource name. -// - options - ExperimentsClientListAllExecutionsOptions contains the optional parameters for the ExperimentsClient.NewListAllExecutionsPager -// method. -func (client *ExperimentsClient) NewListAllExecutionsPager(resourceGroupName string, experimentName string, options *ExperimentsClientListAllExecutionsOptions) *runtime.Pager[ExperimentsClientListAllExecutionsResponse] { - return runtime.NewPager(runtime.PagingHandler[ExperimentsClientListAllExecutionsResponse]{ - More: func(page ExperimentsClientListAllExecutionsResponse) bool { - return page.NextLink != nil && len(*page.NextLink) > 0 - }, - Fetcher: func(ctx context.Context, page *ExperimentsClientListAllExecutionsResponse) (ExperimentsClientListAllExecutionsResponse, error) { - ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "ExperimentsClient.NewListAllExecutionsPager") - 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.listAllExecutionsCreateRequest(ctx, resourceGroupName, experimentName, options) - }, nil) - if err != nil { - return ExperimentsClientListAllExecutionsResponse{}, err - } - return client.listAllExecutionsHandleResponse(resp) - }, - Tracer: client.internal.Tracer(), - }) -} - -// listAllExecutionsCreateRequest creates the ListAllExecutions request. -func (client *ExperimentsClient) listAllExecutionsCreateRequest(ctx context.Context, resourceGroupName string, experimentName string, options *ExperimentsClientListAllExecutionsOptions) (*policy.Request, error) { - urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Chaos/experiments/{experimentName}/executions" - 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 experimentName == "" { - return nil, errors.New("parameter experimentName cannot be empty") - } - urlPath = strings.ReplaceAll(urlPath, "{experimentName}", url.PathEscape(experimentName)) - req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) - if err != nil { - return nil, err - } - reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2024-01-01") - req.Raw().URL.RawQuery = reqQP.Encode() - req.Raw().Header["Accept"] = []string{"application/json"} - return req, nil -} - -// listAllExecutionsHandleResponse handles the ListAllExecutions response. -func (client *ExperimentsClient) listAllExecutionsHandleResponse(resp *http.Response) (ExperimentsClientListAllExecutionsResponse, error) { - result := ExperimentsClientListAllExecutionsResponse{} - if err := runtime.UnmarshalAsJSON(resp, &result.ExperimentExecutionListResult); err != nil { - return ExperimentsClientListAllExecutionsResponse{}, err - } - return result, nil -} - // BeginStart - Start a Experiment resource. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2024-01-01 -// - resourceGroupName - String that represents an Azure resource group. +// Generated from API version 2025-01-01 +// - resourceGroupName - The name of the resource group. The name is case insensitive. // - experimentName - String that represents a Experiment resource name. // - options - ExperimentsClientBeginStartOptions contains the optional parameters for the ExperimentsClient.BeginStart method. func (client *ExperimentsClient) BeginStart(ctx context.Context, resourceGroupName string, experimentName string, options *ExperimentsClientBeginStartOptions) (*runtime.Poller[ExperimentsClientStartResponse], error) { @@ -685,8 +474,7 @@ func (client *ExperimentsClient) BeginStart(ctx context.Context, resourceGroupNa return nil, err } poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[ExperimentsClientStartResponse]{ - FinalStateVia: runtime.FinalStateViaLocation, - Tracer: client.internal.Tracer(), + Tracer: client.internal.Tracer(), }) return poller, err } else { @@ -699,7 +487,7 @@ func (client *ExperimentsClient) BeginStart(ctx context.Context, resourceGroupNa // Start - Start a Experiment resource. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2024-01-01 +// Generated from API version 2025-01-01 func (client *ExperimentsClient) start(ctx context.Context, resourceGroupName string, experimentName string, options *ExperimentsClientBeginStartOptions) (*http.Response, error) { var err error const operationName = "ExperimentsClient.BeginStart" @@ -722,7 +510,7 @@ func (client *ExperimentsClient) start(ctx context.Context, resourceGroupName st } // startCreateRequest creates the Start request. -func (client *ExperimentsClient) startCreateRequest(ctx context.Context, resourceGroupName string, experimentName string, options *ExperimentsClientBeginStartOptions) (*policy.Request, error) { +func (client *ExperimentsClient) startCreateRequest(ctx context.Context, resourceGroupName string, experimentName string, _ *ExperimentsClientBeginStartOptions) (*policy.Request, error) { urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Chaos/experiments/{experimentName}/start" if client.subscriptionID == "" { return nil, errors.New("parameter client.subscriptionID cannot be empty") @@ -741,7 +529,7 @@ func (client *ExperimentsClient) startCreateRequest(ctx context.Context, resourc return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2024-01-01") + reqQP.Set("api-version", "2025-01-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -750,20 +538,19 @@ func (client *ExperimentsClient) startCreateRequest(ctx context.Context, resourc // BeginUpdate - The operation to update an experiment. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2024-01-01 -// - resourceGroupName - String that represents an Azure resource group. +// Generated from API version 2025-01-01 +// - resourceGroupName - The name of the resource group. The name is case insensitive. // - experimentName - String that represents a Experiment resource name. -// - experiment - Parameters supplied to the Update experiment operation. +// - properties - Parameters supplied to the Update experiment operation. // - options - ExperimentsClientBeginUpdateOptions contains the optional parameters for the ExperimentsClient.BeginUpdate method. -func (client *ExperimentsClient) BeginUpdate(ctx context.Context, resourceGroupName string, experimentName string, experiment ExperimentUpdate, options *ExperimentsClientBeginUpdateOptions) (*runtime.Poller[ExperimentsClientUpdateResponse], error) { +func (client *ExperimentsClient) BeginUpdate(ctx context.Context, resourceGroupName string, experimentName string, properties ExperimentUpdate, options *ExperimentsClientBeginUpdateOptions) (*runtime.Poller[ExperimentsClientUpdateResponse], error) { if options == nil || options.ResumeToken == "" { - resp, err := client.update(ctx, resourceGroupName, experimentName, experiment, options) + resp, err := client.update(ctx, resourceGroupName, experimentName, properties, options) if err != nil { return nil, err } poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[ExperimentsClientUpdateResponse]{ - FinalStateVia: runtime.FinalStateViaLocation, - Tracer: client.internal.Tracer(), + Tracer: client.internal.Tracer(), }) return poller, err } else { @@ -776,14 +563,14 @@ func (client *ExperimentsClient) BeginUpdate(ctx context.Context, resourceGroupN // Update - The operation to update an experiment. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2024-01-01 -func (client *ExperimentsClient) update(ctx context.Context, resourceGroupName string, experimentName string, experiment ExperimentUpdate, options *ExperimentsClientBeginUpdateOptions) (*http.Response, error) { +// Generated from API version 2025-01-01 +func (client *ExperimentsClient) update(ctx context.Context, resourceGroupName string, experimentName string, properties ExperimentUpdate, options *ExperimentsClientBeginUpdateOptions) (*http.Response, error) { var err error const operationName = "ExperimentsClient.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, experimentName, experiment, options) + req, err := client.updateCreateRequest(ctx, resourceGroupName, experimentName, properties, options) if err != nil { return nil, err } @@ -791,7 +578,7 @@ func (client *ExperimentsClient) update(ctx context.Context, resourceGroupName s if err != nil { return nil, err } - if !runtime.HasStatusCode(httpResp, http.StatusAccepted) { + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) { err = runtime.NewResponseError(httpResp) return nil, err } @@ -799,7 +586,7 @@ func (client *ExperimentsClient) update(ctx context.Context, resourceGroupName s } // updateCreateRequest creates the Update request. -func (client *ExperimentsClient) updateCreateRequest(ctx context.Context, resourceGroupName string, experimentName string, experiment ExperimentUpdate, options *ExperimentsClientBeginUpdateOptions) (*policy.Request, error) { +func (client *ExperimentsClient) updateCreateRequest(ctx context.Context, resourceGroupName string, experimentName string, properties ExperimentUpdate, _ *ExperimentsClientBeginUpdateOptions) (*policy.Request, error) { urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Chaos/experiments/{experimentName}" if client.subscriptionID == "" { return nil, errors.New("parameter client.subscriptionID cannot be empty") @@ -818,10 +605,11 @@ func (client *ExperimentsClient) updateCreateRequest(ctx context.Context, resour return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2024-01-01") + reqQP.Set("api-version", "2025-01-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} - if err := runtime.MarshalAsJSON(req, experiment); err != nil { + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, properties); err != nil { return nil, err } return req, nil diff --git a/sdk/resourcemanager/chaos/armchaos/experiments_client_example_test.go b/sdk/resourcemanager/chaos/armchaos/experiments_client_example_test.go index fb537dbc74ef..7737c506aa3a 100644 --- a/sdk/resourcemanager/chaos/armchaos/experiments_client_example_test.go +++ b/sdk/resourcemanager/chaos/armchaos/experiments_client_example_test.go @@ -1,197 +1,29 @@ -//go:build go1.18 -// +build go1.18 - // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. -// DO NOT EDIT. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. package armchaos_test import ( "context" - "log" - "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" "github.com/Azure/azure-sdk-for-go/sdk/azidentity" - "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/chaos/armchaos" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/chaos/armchaos/v2" + "log" ) -// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/e4009d2f8d3bf0271757e522c7d1c1997e193d44/specification/chaos/resource-manager/Microsoft.Chaos/stable/2024-01-01/examples/ListExperimentsInASubscription.json -func ExampleExperimentsClient_NewListAllPager() { - cred, err := azidentity.NewDefaultAzureCredential(nil) - if err != nil { - log.Fatalf("failed to obtain a credential: %v", err) - } - ctx := context.Background() - clientFactory, err := armchaos.NewClientFactory("", cred, nil) - if err != nil { - log.Fatalf("failed to create client: %v", err) - } - pager := clientFactory.NewExperimentsClient().NewListAllPager(&armchaos.ExperimentsClientListAllOptions{Running: nil, - ContinuationToken: nil, - }) - for pager.More() { - page, err := pager.NextPage(ctx) - if err != nil { - log.Fatalf("failed to advance page: %v", err) - } - for _, v := range page.Value { - // You could use page here. We use blank identifier for just demo purposes. - _ = v - } - // If the HTTP response code is 200 as defined in example definition, your page structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. - // page.ExperimentListResult = armchaos.ExperimentListResult{ - // Value: []*armchaos.Experiment{ - // { - // Name: to.Ptr("exampleExperiment"), - // Type: to.Ptr("Microsoft.Chaos/experiments"), - // ID: to.Ptr("/subscriptions/6b052e15-03d3-4f17-b2e1-be7f07588291/resourceGroups/exampleRG/providers/Microsoft.Chaos/experiments/exampleExperiment"), - // Location: to.Ptr("centraluseuap"), - // Identity: &armchaos.ResourceIdentity{ - // Type: to.Ptr(armchaos.ResourceIdentityTypeSystemAssigned), - // PrincipalID: to.Ptr("d04ab567-2c07-43ef-a7f4-4527626b7f56"), - // TenantID: to.Ptr("8c3e2fb2-fe7a-4bf1-b779-d73990782fe6"), - // }, - // Properties: &armchaos.ExperimentProperties{ - // Selectors: []armchaos.TargetSelectorClassification{ - // &armchaos.TargetListSelector{ - // Type: to.Ptr(armchaos.SelectorTypeList), - // ID: to.Ptr("selector1"), - // Targets: []*armchaos.TargetReference{ - // { - // Type: to.Ptr(armchaos.TargetReferenceTypeChaosTarget), - // ID: to.Ptr("/subscriptions/6b052e15-03d3-4f17-b2e1-be7f07588291/resourceGroups/exampleRG/providers/Microsoft.Compute/virtualMachines/exampleVM/providers/Microsoft.Chaos/targets/Microsoft-VirtualMachine"), - // }}, - // }}, - // Steps: []*armchaos.ExperimentStep{ - // { - // Name: to.Ptr("step1"), - // Branches: []*armchaos.ExperimentBranch{ - // { - // Name: to.Ptr("branch1"), - // Actions: []armchaos.ExperimentActionClassification{ - // &armchaos.ContinuousAction{ - // Name: to.Ptr("urn:csci:provider:providername:Shutdown/1.0"), - // Type: to.Ptr("continuous"), - // Duration: to.Ptr("PT10M"), - // Parameters: []*armchaos.KeyValuePair{ - // { - // Key: to.Ptr("abruptShutdown"), - // Value: to.Ptr("false"), - // }}, - // SelectorID: to.Ptr("selector1"), - // }}, - // }}, - // }}, - // }, - // SystemData: &armchaos.SystemData{ - // CreatedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2021-07-01T00:00:00.000Z"); return t}()), - // CreatedBy: to.Ptr("User"), - // CreatedByType: to.Ptr(armchaos.CreatedByType("b3a41dba-4415-4d36-9ee8-e5eaa86db976")), - // LastModifiedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2021-07-01T00:00:00.000Z"); return t}()), - // LastModifiedBy: to.Ptr("User"), - // LastModifiedByType: to.Ptr(armchaos.CreatedByType("b3a41dba-4415-4d36-9ee8-e5eaa86db976")), - // }, - // }}, - // } - } -} - -// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/e4009d2f8d3bf0271757e522c7d1c1997e193d44/specification/chaos/resource-manager/Microsoft.Chaos/stable/2024-01-01/examples/ListExperimentsInAResourceGroup.json -func ExampleExperimentsClient_NewListPager() { - cred, err := azidentity.NewDefaultAzureCredential(nil) - if err != nil { - log.Fatalf("failed to obtain a credential: %v", err) - } - ctx := context.Background() - clientFactory, err := armchaos.NewClientFactory("", cred, nil) - if err != nil { - log.Fatalf("failed to create client: %v", err) - } - pager := clientFactory.NewExperimentsClient().NewListPager("exampleRG", &armchaos.ExperimentsClientListOptions{Running: nil, - ContinuationToken: nil, - }) - for pager.More() { - page, err := pager.NextPage(ctx) - if err != nil { - log.Fatalf("failed to advance page: %v", err) - } - for _, v := range page.Value { - // You could use page here. We use blank identifier for just demo purposes. - _ = v - } - // If the HTTP response code is 200 as defined in example definition, your page structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. - // page.ExperimentListResult = armchaos.ExperimentListResult{ - // Value: []*armchaos.Experiment{ - // { - // Name: to.Ptr("exampleExperiment"), - // Type: to.Ptr("Microsoft.Chaos/experiments"), - // ID: to.Ptr("/subscriptions/6b052e15-03d3-4f17-b2e1-be7f07588291/resourceGroups/exampleRG/providers/Microsoft.Chaos/experiments/exampleExperiment"), - // Location: to.Ptr("centraluseuap"), - // Identity: &armchaos.ResourceIdentity{ - // Type: to.Ptr(armchaos.ResourceIdentityTypeSystemAssigned), - // PrincipalID: to.Ptr("d04ab567-2c07-43ef-a7f4-4527626b7f56"), - // TenantID: to.Ptr("8c3e2fb2-fe7a-4bf1-b779-d73990782fe6"), - // }, - // Properties: &armchaos.ExperimentProperties{ - // Selectors: []armchaos.TargetSelectorClassification{ - // &armchaos.TargetListSelector{ - // Type: to.Ptr(armchaos.SelectorTypeList), - // ID: to.Ptr("selector1"), - // Targets: []*armchaos.TargetReference{ - // { - // Type: to.Ptr(armchaos.TargetReferenceTypeChaosTarget), - // ID: to.Ptr("/subscriptions/6b052e15-03d3-4f17-b2e1-be7f07588291/resourceGroups/exampleRG/providers/Microsoft.Compute/virtualMachines/exampleVM/providers/Microsoft.Chaos/targets/Microsoft-VirtualMachine"), - // }}, - // }}, - // Steps: []*armchaos.ExperimentStep{ - // { - // Name: to.Ptr("step1"), - // Branches: []*armchaos.ExperimentBranch{ - // { - // Name: to.Ptr("branch1"), - // Actions: []armchaos.ExperimentActionClassification{ - // &armchaos.ContinuousAction{ - // Name: to.Ptr("urn:csci:provider:providername:Shutdown/1.0"), - // Type: to.Ptr("continuous"), - // Duration: to.Ptr("PT10M"), - // Parameters: []*armchaos.KeyValuePair{ - // { - // Key: to.Ptr("abruptShutdown"), - // Value: to.Ptr("false"), - // }}, - // SelectorID: to.Ptr("selector1"), - // }}, - // }}, - // }}, - // }, - // SystemData: &armchaos.SystemData{ - // CreatedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2021-07-01T00:00:00.000Z"); return t}()), - // CreatedBy: to.Ptr("User"), - // CreatedByType: to.Ptr(armchaos.CreatedByType("b3a41dba-4415-4d36-9ee8-e5eaa86db976")), - // LastModifiedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2021-07-01T00:00:00.000Z"); return t}()), - // LastModifiedBy: to.Ptr("User"), - // LastModifiedByType: to.Ptr(armchaos.CreatedByType("b3a41dba-4415-4d36-9ee8-e5eaa86db976")), - // }, - // }}, - // } - } -} - -// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/e4009d2f8d3bf0271757e522c7d1c1997e193d44/specification/chaos/resource-manager/Microsoft.Chaos/stable/2024-01-01/examples/DeleteExperiment.json -func ExampleExperimentsClient_BeginDelete() { +// Generated from example definition: 2025-01-01/Experiments_Cancel.json +func ExampleExperimentsClient_BeginCancel() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() - clientFactory, err := armchaos.NewClientFactory("", cred, nil) + clientFactory, err := armchaos.NewClientFactory("6b052e15-03d3-4f17-b2e1-be7f07588291", cred, nil) if err != nil { log.Fatalf("failed to create client: %v", err) } - poller, err := clientFactory.NewExperimentsClient().BeginDelete(ctx, "exampleRG", "exampleExperiment", nil) + poller, err := clientFactory.NewExperimentsClient().BeginCancel(ctx, "exampleRG", "exampleExperiment", nil) if err != nil { log.Fatalf("failed to finish the request: %v", err) } @@ -201,93 +33,26 @@ func ExampleExperimentsClient_BeginDelete() { } } -// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/e4009d2f8d3bf0271757e522c7d1c1997e193d44/specification/chaos/resource-manager/Microsoft.Chaos/stable/2024-01-01/examples/GetExperiment.json -func ExampleExperimentsClient_Get() { - cred, err := azidentity.NewDefaultAzureCredential(nil) - if err != nil { - log.Fatalf("failed to obtain a credential: %v", err) - } - ctx := context.Background() - clientFactory, err := armchaos.NewClientFactory("", cred, nil) - if err != nil { - log.Fatalf("failed to create client: %v", err) - } - res, err := clientFactory.NewExperimentsClient().Get(ctx, "exampleRG", "exampleExperiment", nil) - if err != nil { - log.Fatalf("failed to finish the request: %v", err) - } - // You could use response here. We use blank identifier for just demo purposes. - _ = res - // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. - // res.Experiment = armchaos.Experiment{ - // Name: to.Ptr("exampleExperiment"), - // Type: to.Ptr("Microsoft.Chaos/experiments"), - // ID: to.Ptr("/subscriptions/6b052e15-03d3-4f17-b2e1-be7f07588291/resourceGroups/exampleRG/providers/Microsoft.Chaos/experiments/exampleExperiment"), - // Location: to.Ptr("centraluseuap"), - // Identity: &armchaos.ResourceIdentity{ - // Type: to.Ptr(armchaos.ResourceIdentityTypeSystemAssigned), - // PrincipalID: to.Ptr("d04ab567-2c07-43ef-a7f4-4527626b7f56"), - // TenantID: to.Ptr("8c3e2fb2-fe7a-4bf1-b779-d73990782fe6"), - // }, - // Properties: &armchaos.ExperimentProperties{ - // Selectors: []armchaos.TargetSelectorClassification{ - // &armchaos.TargetListSelector{ - // Type: to.Ptr(armchaos.SelectorTypeList), - // ID: to.Ptr("selector1"), - // Targets: []*armchaos.TargetReference{ - // { - // Type: to.Ptr(armchaos.TargetReferenceTypeChaosTarget), - // ID: to.Ptr("/subscriptions/6b052e15-03d3-4f17-b2e1-be7f07588291/resourceGroups/exampleRG/providers/Microsoft.Compute/virtualMachines/exampleVM/providers/Microsoft.Chaos/targets/Microsoft-VirtualMachine"), - // }}, - // }}, - // Steps: []*armchaos.ExperimentStep{ - // { - // Name: to.Ptr("step1"), - // Branches: []*armchaos.ExperimentBranch{ - // { - // Name: to.Ptr("branch1"), - // Actions: []armchaos.ExperimentActionClassification{ - // &armchaos.ContinuousAction{ - // Name: to.Ptr("urn:csci:provider:providername:Shutdown/1.0"), - // Type: to.Ptr("continuous"), - // Duration: to.Ptr("PT10M"), - // Parameters: []*armchaos.KeyValuePair{ - // { - // Key: to.Ptr("abruptShutdown"), - // Value: to.Ptr("false"), - // }}, - // SelectorID: to.Ptr("selector1"), - // }}, - // }}, - // }}, - // }, - // SystemData: &armchaos.SystemData{ - // CreatedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2021-07-01T00:00:00.000Z"); return t}()), - // CreatedBy: to.Ptr("User"), - // CreatedByType: to.Ptr(armchaos.CreatedByType("b3a41dba-4415-4d36-9ee8-e5eaa86db976")), - // LastModifiedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2021-07-01T00:00:00.000Z"); return t}()), - // LastModifiedBy: to.Ptr("User"), - // LastModifiedByType: to.Ptr(armchaos.CreatedByType("b3a41dba-4415-4d36-9ee8-e5eaa86db976")), - // }, - // } -} - -// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/e4009d2f8d3bf0271757e522c7d1c1997e193d44/specification/chaos/resource-manager/Microsoft.Chaos/stable/2024-01-01/examples/CreateUpdateExperiment.json +// Generated from example definition: 2025-01-01/Experiments_CreateOrUpdate.json func ExampleExperimentsClient_BeginCreateOrUpdate() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() - clientFactory, err := armchaos.NewClientFactory("", cred, nil) + clientFactory, err := armchaos.NewClientFactory("6b052e15-03d3-4f17-b2e1-be7f07588291", cred, nil) if err != nil { log.Fatalf("failed to create client: %v", err) } poller, err := clientFactory.NewExperimentsClient().BeginCreateOrUpdate(ctx, "exampleRG", "exampleExperiment", armchaos.Experiment{ - Location: to.Ptr("eastus2euap"), - Identity: &armchaos.ResourceIdentity{ - Type: to.Ptr(armchaos.ResourceIdentityTypeSystemAssigned), + Identity: &armchaos.ManagedServiceIdentity{ + Type: to.Ptr(armchaos.ManagedServiceIdentityTypeSystemAssigned), }, + Tags: map[string]*string{ + "key7131": to.Ptr("ryohwcoiccwsnewjigfmijz"), + "key2138": to.Ptr("fjaeecgnvqd"), + }, + Location: to.Ptr("eastus2euap"), Properties: &armchaos.ExperimentProperties{ Selectors: []armchaos.TargetSelectorClassification{ &armchaos.TargetListSelector{ @@ -297,8 +62,10 @@ func ExampleExperimentsClient_BeginCreateOrUpdate() { { Type: to.Ptr(armchaos.TargetReferenceTypeChaosTarget), ID: to.Ptr("/subscriptions/6b052e15-03d3-4f17-b2e1-be7f07588291/resourceGroups/exampleRG/providers/Microsoft.Compute/virtualMachines/exampleVM/providers/Microsoft.Chaos/targets/Microsoft-VirtualMachine"), - }}, - }}, + }, + }, + }, + }, Steps: []*armchaos.ExperimentStep{ { Name: to.Ptr("step1"), @@ -308,17 +75,21 @@ func ExampleExperimentsClient_BeginCreateOrUpdate() { Actions: []armchaos.ExperimentActionClassification{ &armchaos.ContinuousAction{ Name: to.Ptr("urn:csci:microsoft:virtualMachine:shutdown/1.0"), - Type: to.Ptr("continuous"), + Type: to.Ptr(armchaos.ExperimentActionTypeContinuous), Duration: to.Ptr("PT10M"), Parameters: []*armchaos.KeyValuePair{ { Key: to.Ptr("abruptShutdown"), Value: to.Ptr("false"), - }}, + }, + }, SelectorID: to.Ptr("selector1"), - }}, - }}, - }}, + }, + }, + }, + }, + }, + }, }, }, nil) if err != nil { @@ -331,83 +102,84 @@ func ExampleExperimentsClient_BeginCreateOrUpdate() { // You could use response here. We use blank identifier for just demo purposes. _ = res // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. - // res.Experiment = armchaos.Experiment{ - // Name: to.Ptr("exampleExperiment"), - // Type: to.Ptr("Microsoft.Chaos/experiments"), - // ID: to.Ptr("/subscriptions/6b052e15-03d3-4f17-b2e1-be7f07588291/resourceGroups/exampleRG/providers/Microsoft.Chaos/experiments/exampleExperiment"), - // Location: to.Ptr("eastus2euap"), - // Identity: &armchaos.ResourceIdentity{ - // Type: to.Ptr(armchaos.ResourceIdentityTypeSystemAssigned), - // PrincipalID: to.Ptr("d04ab567-2c07-43ef-a7f4-4527626b7f56"), - // TenantID: to.Ptr("8c3e2fb2-fe7a-4bf1-b779-d73990782fe6"), - // }, - // Properties: &armchaos.ExperimentProperties{ - // ProvisioningState: to.Ptr(armchaos.ProvisioningStateSucceeded), - // Selectors: []armchaos.TargetSelectorClassification{ - // &armchaos.TargetListSelector{ - // Type: to.Ptr(armchaos.SelectorTypeList), - // ID: to.Ptr("selector1"), - // Targets: []*armchaos.TargetReference{ - // { - // Type: to.Ptr(armchaos.TargetReferenceTypeChaosTarget), - // ID: to.Ptr("/subscriptions/6b052e15-03d3-4f17-b2e1-be7f07588291/resourceGroups/exampleRG/providers/Microsoft.Compute/virtualMachines/exampleVM/providers/Microsoft.Chaos/targets/Microsoft-VirtualMachine"), - // }}, - // }}, - // Steps: []*armchaos.ExperimentStep{ - // { - // Name: to.Ptr("step1"), - // Branches: []*armchaos.ExperimentBranch{ - // { - // Name: to.Ptr("branch1"), - // Actions: []armchaos.ExperimentActionClassification{ - // &armchaos.ContinuousAction{ - // Name: to.Ptr("urn:csci:microsoft:virtualMachine:shutdown/1.0"), - // Type: to.Ptr("continuous"), - // Duration: to.Ptr("PT10M"), - // Parameters: []*armchaos.KeyValuePair{ - // { - // Key: to.Ptr("abruptShutdown"), - // Value: to.Ptr("false"), - // }}, - // SelectorID: to.Ptr("selector1"), - // }}, - // }}, - // }}, - // }, - // SystemData: &armchaos.SystemData{ - // CreatedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2021-07-01T00:00:00.000Z"); return t}()), - // CreatedBy: to.Ptr("User"), - // CreatedByType: to.Ptr(armchaos.CreatedByType("b3a41dba-4415-4d36-9ee8-e5eaa86db976")), - // LastModifiedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2021-07-01T00:00:00.000Z"); return t}()), - // LastModifiedBy: to.Ptr("User"), - // LastModifiedByType: to.Ptr(armchaos.CreatedByType("b3a41dba-4415-4d36-9ee8-e5eaa86db976")), + // res = armchaos.ExperimentsClientCreateOrUpdateResponse{ + // Experiment: &armchaos.Experiment{ + // Name: to.Ptr("exampleExperiment"), + // Type: to.Ptr("Microsoft.Chaos/experiments"), + // ID: to.Ptr("/subscriptions/6b052e15-03d3-4f17-b2e1-be7f07588291/resourceGroups/exampleRG/providers/Microsoft.Chaos/experiments/exampleExperiment"), + // Identity: &armchaos.ManagedServiceIdentity{ + // Type: to.Ptr(armchaos.ManagedServiceIdentityTypeSystemAssigned), + // PrincipalID: to.Ptr("d04ab567-2c07-43ef-a7f4-4527626b7f56"), + // TenantID: to.Ptr("8c3e2fb2-fe7a-4bf1-b779-d73990782fe6"), + // }, + // Tags: map[string]*string{ + // "key7131": to.Ptr("ryohwcoiccwsnewjigfmijz"), + // "key2138": to.Ptr("fjaeecgnvqd"), + // }, + // Location: to.Ptr("eastus2euap"), + // Properties: &armchaos.ExperimentProperties{ + // ProvisioningState: to.Ptr(armchaos.ProvisioningStateUpdating), + // Selectors: []armchaos.TargetSelectorClassification{ + // &armchaos.TargetListSelector{ + // Type: to.Ptr(armchaos.SelectorTypeList), + // ID: to.Ptr("selector1"), + // Targets: []*armchaos.TargetReference{ + // { + // Type: to.Ptr(armchaos.TargetReferenceTypeChaosTarget), + // ID: to.Ptr("/subscriptions/6b052e15-03d3-4f17-b2e1-be7f07588291/resourceGroups/exampleRG/providers/Microsoft.Compute/virtualMachines/exampleVM/providers/Microsoft.Chaos/targets/Microsoft-VirtualMachine"), + // }, + // }, + // }, + // }, + // Steps: []*armchaos.ExperimentStep{ + // { + // Name: to.Ptr("step1"), + // Branches: []*armchaos.ExperimentBranch{ + // { + // Name: to.Ptr("branch1"), + // Actions: []armchaos.ExperimentActionClassification{ + // &armchaos.ContinuousAction{ + // Name: to.Ptr("urn:csci:microsoft:virtualMachine:shutdown/1.0"), + // Type: to.Ptr(armchaos.ExperimentActionTypeContinuous), + // Duration: to.Ptr("PT10M"), + // Parameters: []*armchaos.KeyValuePair{ + // { + // Key: to.Ptr("abruptShutdown"), + // Value: to.Ptr("false"), + // }, + // }, + // SelectorID: to.Ptr("selector1"), + // }, + // }, + // }, + // }, + // }, + // }, + // }, + // SystemData: &armchaos.SystemData{ + // CreatedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2021-07-01T00:00:00.0Z"); return t}()), + // CreatedBy: to.Ptr("User"), + // CreatedByType: to.Ptr(armchaos.CreatedByType("b3a41dba-4415-4d36-9ee8-e5eaa86db976")), + // LastModifiedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2021-07-01T00:00:00.0Z"); return t}()), + // LastModifiedBy: to.Ptr("User"), + // LastModifiedByType: to.Ptr(armchaos.CreatedByType("b3a41dba-4415-4d36-9ee8-e5eaa86db976")), + // }, // }, // } } -// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/e4009d2f8d3bf0271757e522c7d1c1997e193d44/specification/chaos/resource-manager/Microsoft.Chaos/stable/2024-01-01/examples/UpdateExperiment.json -func ExampleExperimentsClient_BeginUpdate() { +// Generated from example definition: 2025-01-01/Experiments_Delete.json +func ExampleExperimentsClient_BeginDelete() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() - clientFactory, err := armchaos.NewClientFactory("", cred, nil) + clientFactory, err := armchaos.NewClientFactory("6b052e15-03d3-4f17-b2e1-be7f07588291", cred, nil) if err != nil { log.Fatalf("failed to create client: %v", err) } - poller, err := clientFactory.NewExperimentsClient().BeginUpdate(ctx, "exampleRG", "exampleExperiment", armchaos.ExperimentUpdate{ - Identity: &armchaos.ResourceIdentity{ - Type: to.Ptr(armchaos.ResourceIdentityTypeUserAssigned), - UserAssignedIdentities: map[string]*armchaos.UserAssignedIdentity{ - "/subscriptions/6b052e15-03d3-4f17-b2e1-be7f07588291/resourceGroups/exampleRG/providers/Microsoft.ManagedIdentity/userAssignedIdentity/exampleUMI": {}, - }, - }, - Tags: map[string]*string{ - "key1": to.Ptr("value1"), - "key2": to.Ptr("value2"), - }, - }, nil) + poller, err := clientFactory.NewExperimentsClient().BeginDelete(ctx, "exampleRG", "exampleExperiment", nil) if err != nil { log.Fatalf("failed to finish the request: %v", err) } @@ -417,60 +189,186 @@ func ExampleExperimentsClient_BeginUpdate() { } } -// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/e4009d2f8d3bf0271757e522c7d1c1997e193d44/specification/chaos/resource-manager/Microsoft.Chaos/stable/2024-01-01/examples/CancelExperiment.json -func ExampleExperimentsClient_BeginCancel() { +// Generated from example definition: 2025-01-01/Experiments_Get.json +func ExampleExperimentsClient_Get() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() - clientFactory, err := armchaos.NewClientFactory("", cred, nil) + clientFactory, err := armchaos.NewClientFactory("6b052e15-03d3-4f17-b2e1-be7f07588291", cred, nil) if err != nil { log.Fatalf("failed to create client: %v", err) } - poller, err := clientFactory.NewExperimentsClient().BeginCancel(ctx, "exampleRG", "exampleExperiment", nil) + res, err := clientFactory.NewExperimentsClient().Get(ctx, "exampleRG", "exampleExperiment", nil) if err != nil { log.Fatalf("failed to finish the request: %v", err) } - _, err = poller.PollUntilDone(ctx, nil) - if err != nil { - log.Fatalf("failed to pull the result: %v", err) - } + // You could use response here. We use blank identifier for just demo purposes. + _ = res + // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // res = armchaos.ExperimentsClientGetResponse{ + // Experiment: &armchaos.Experiment{ + // Name: to.Ptr("exampleExperiment"), + // Type: to.Ptr("Microsoft.Chaos/experiments"), + // ID: to.Ptr("/subscriptions/6b052e15-03d3-4f17-b2e1-be7f07588291/resourceGroups/exampleRG/providers/Microsoft.Chaos/experiments/exampleExperiment"), + // Identity: &armchaos.ManagedServiceIdentity{ + // Type: to.Ptr(armchaos.ManagedServiceIdentityTypeSystemAssigned), + // PrincipalID: to.Ptr("d04ab567-2c07-43ef-a7f4-4527626b7f56"), + // TenantID: to.Ptr("8c3e2fb2-fe7a-4bf1-b779-d73990782fe6"), + // }, + // Location: to.Ptr("centraluseuap"), + // Properties: &armchaos.ExperimentProperties{ + // Selectors: []armchaos.TargetSelectorClassification{ + // &armchaos.TargetListSelector{ + // Type: to.Ptr(armchaos.SelectorTypeList), + // ID: to.Ptr("selector1"), + // Targets: []*armchaos.TargetReference{ + // { + // Type: to.Ptr(armchaos.TargetReferenceTypeChaosTarget), + // ID: to.Ptr("/subscriptions/6b052e15-03d3-4f17-b2e1-be7f07588291/resourceGroups/exampleRG/providers/Microsoft.Compute/virtualMachines/exampleVM/providers/Microsoft.Chaos/targets/Microsoft-VirtualMachine"), + // }, + // }, + // }, + // }, + // Steps: []*armchaos.ExperimentStep{ + // { + // Name: to.Ptr("step1"), + // Branches: []*armchaos.ExperimentBranch{ + // { + // Name: to.Ptr("branch1"), + // Actions: []armchaos.ExperimentActionClassification{ + // &armchaos.ContinuousAction{ + // Name: to.Ptr("urn:csci:provider:providername:Shutdown/1.0"), + // Type: to.Ptr(armchaos.ExperimentActionTypeContinuous), + // Duration: to.Ptr("PT10M"), + // Parameters: []*armchaos.KeyValuePair{ + // { + // Key: to.Ptr("abruptShutdown"), + // Value: to.Ptr("false"), + // }, + // }, + // SelectorID: to.Ptr("selector1"), + // }, + // }, + // }, + // }, + // }, + // }, + // }, + // SystemData: &armchaos.SystemData{ + // CreatedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2021-07-01T00:00:00.0Z"); return t}()), + // CreatedBy: to.Ptr("User"), + // CreatedByType: to.Ptr(armchaos.CreatedByType("b3a41dba-4415-4d36-9ee8-e5eaa86db976")), + // LastModifiedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2021-07-01T00:00:00.0Z"); return t}()), + // LastModifiedBy: to.Ptr("User"), + // LastModifiedByType: to.Ptr(armchaos.CreatedByType("b3a41dba-4415-4d36-9ee8-e5eaa86db976")), + // }, + // }, + // } } -// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/e4009d2f8d3bf0271757e522c7d1c1997e193d44/specification/chaos/resource-manager/Microsoft.Chaos/stable/2024-01-01/examples/StartExperiment.json -func ExampleExperimentsClient_BeginStart() { +// Generated from example definition: 2025-01-01/Experiments_List.json +func ExampleExperimentsClient_NewListPager() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() - clientFactory, err := armchaos.NewClientFactory("", cred, nil) + clientFactory, err := armchaos.NewClientFactory("6b052e15-03d3-4f17-b2e1-be7f07588291", cred, nil) if err != nil { log.Fatalf("failed to create client: %v", err) } - poller, err := clientFactory.NewExperimentsClient().BeginStart(ctx, "exampleRG", "exampleExperiment", nil) - if err != nil { - log.Fatalf("failed to finish the request: %v", err) - } - _, err = poller.PollUntilDone(ctx, nil) - if err != nil { - log.Fatalf("failed to pull the result: %v", err) + pager := clientFactory.NewExperimentsClient().NewListPager("exampleRG", nil) + for pager.More() { + page, err := pager.NextPage(ctx) + if err != nil { + log.Fatalf("failed to advance page: %v", err) + } + for _, v := range page.Value { + // You could use page here. We use blank identifier for just demo purposes. + _ = v + } + // If the HTTP response code is 200 as defined in example definition, your page structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // page = armchaos.ExperimentsClientListResponse{ + // ExperimentListResult: armchaos.ExperimentListResult{ + // NextLink: to.Ptr("https://management.azure.com/subscriptions/6b052e15-03d3-4f17-b2e1-be7f07588291/resourceGroups/exampleRG/providers/Microsoft.Chaos/experiments?continuationToken=&api-version=2024-11-01-preview"), + // Value: []*armchaos.Experiment{ + // { + // Name: to.Ptr("exampleExperiment"), + // Type: to.Ptr("Microsoft.Chaos/experiments"), + // ID: to.Ptr("/subscriptions/6b052e15-03d3-4f17-b2e1-be7f07588291/resourceGroups/exampleRG/providers/Microsoft.Chaos/experiments/exampleExperiment"), + // Identity: &armchaos.ManagedServiceIdentity{ + // Type: to.Ptr(armchaos.ManagedServiceIdentityTypeSystemAssigned), + // PrincipalID: to.Ptr("d04ab567-2c07-43ef-a7f4-4527626b7f56"), + // TenantID: to.Ptr("8c3e2fb2-fe7a-4bf1-b779-d73990782fe6"), + // }, + // Location: to.Ptr("centraluseuap"), + // Properties: &armchaos.ExperimentProperties{ + // Selectors: []armchaos.TargetSelectorClassification{ + // &armchaos.TargetListSelector{ + // Type: to.Ptr(armchaos.SelectorTypeList), + // ID: to.Ptr("selector1"), + // Targets: []*armchaos.TargetReference{ + // { + // Type: to.Ptr(armchaos.TargetReferenceTypeChaosTarget), + // ID: to.Ptr("/subscriptions/6b052e15-03d3-4f17-b2e1-be7f07588291/resourceGroups/exampleRG/providers/Microsoft.Compute/virtualMachines/exampleVM/providers/Microsoft.Chaos/targets/Microsoft-VirtualMachine"), + // }, + // }, + // }, + // }, + // Steps: []*armchaos.ExperimentStep{ + // { + // Name: to.Ptr("step1"), + // Branches: []*armchaos.ExperimentBranch{ + // { + // Name: to.Ptr("branch1"), + // Actions: []armchaos.ExperimentActionClassification{ + // &armchaos.ContinuousAction{ + // Name: to.Ptr("urn:csci:provider:providername:Shutdown/1.0"), + // Type: to.Ptr(armchaos.ExperimentActionTypeContinuous), + // Duration: to.Ptr("PT10M"), + // Parameters: []*armchaos.KeyValuePair{ + // { + // Key: to.Ptr("abruptShutdown"), + // Value: to.Ptr("false"), + // }, + // }, + // SelectorID: to.Ptr("selector1"), + // }, + // }, + // }, + // }, + // }, + // }, + // }, + // SystemData: &armchaos.SystemData{ + // CreatedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2021-07-01T00:00:00.0Z"); return t}()), + // CreatedBy: to.Ptr("User"), + // CreatedByType: to.Ptr(armchaos.CreatedByType("b3a41dba-4415-4d36-9ee8-e5eaa86db976")), + // LastModifiedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2021-07-01T00:00:00.0Z"); return t}()), + // LastModifiedBy: to.Ptr("User"), + // LastModifiedByType: to.Ptr(armchaos.CreatedByType("b3a41dba-4415-4d36-9ee8-e5eaa86db976")), + // }, + // }, + // }, + // }, + // } } } -// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/e4009d2f8d3bf0271757e522c7d1c1997e193d44/specification/chaos/resource-manager/Microsoft.Chaos/stable/2024-01-01/examples/ListExperimentExecutions.json -func ExampleExperimentsClient_NewListAllExecutionsPager() { +// Generated from example definition: 2025-01-01/Experiments_ListAll.json +func ExampleExperimentsClient_NewListAllPager() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() - clientFactory, err := armchaos.NewClientFactory("", cred, nil) + clientFactory, err := armchaos.NewClientFactory("6b052e15-03d3-4f17-b2e1-be7f07588291", cred, nil) if err != nil { log.Fatalf("failed to create client: %v", err) } - pager := clientFactory.NewExperimentsClient().NewListAllExecutionsPager("exampleRG", "exampleExperiment", nil) + pager := clientFactory.NewExperimentsClient().NewListAllPager(nil) for pager.More() { page, err := pager.NextPage(ctx) if err != nil { @@ -481,124 +379,191 @@ func ExampleExperimentsClient_NewListAllExecutionsPager() { _ = v } // If the HTTP response code is 200 as defined in example definition, your page structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. - // page.ExperimentExecutionListResult = armchaos.ExperimentExecutionListResult{ - // Value: []*armchaos.ExperimentExecution{ - // { - // Name: to.Ptr("f24500ad-744e-4a26-864b-b76199eac333"), - // Type: to.Ptr("Microsoft.Chaos/experiments/executions"), - // ID: to.Ptr("/subscriptions/6b052e15-03d3-4f17-b2e1-be7f07588291/resourceGroups/exampleRG/providers/Microsoft.Chaos/experiments/exampleExperiment/executions/"), - // Properties: &armchaos.ExperimentExecutionProperties{ - // StartedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2020-12-14T21:52:52.255Z"); return t}()), - // Status: to.Ptr("failed"), - // StoppedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2020-12-14T21:56:18.928Z"); return t}()), + // page = armchaos.ExperimentsClientListAllResponse{ + // ExperimentListResult: armchaos.ExperimentListResult{ + // NextLink: to.Ptr("https://management.azure.com/subscriptions/6b052e15-03d3-4f17-b2e1-be7f07588291/providers/Microsoft.Chaos/experiments?continuationToken=&api-version=2024-11-01-preview"), + // Value: []*armchaos.Experiment{ + // { + // Name: to.Ptr("exampleExperiment"), + // Type: to.Ptr("Microsoft.Chaos/experiments"), + // ID: to.Ptr("/subscriptions/6b052e15-03d3-4f17-b2e1-be7f07588291/resourceGroups/exampleRG/providers/Microsoft.Chaos/experiments/exampleExperiment"), + // Identity: &armchaos.ManagedServiceIdentity{ + // Type: to.Ptr(armchaos.ManagedServiceIdentityTypeSystemAssigned), + // PrincipalID: to.Ptr("d04ab567-2c07-43ef-a7f4-4527626b7f56"), + // TenantID: to.Ptr("8c3e2fb2-fe7a-4bf1-b779-d73990782fe6"), + // }, + // Location: to.Ptr("centraluseuap"), + // Properties: &armchaos.ExperimentProperties{ + // Selectors: []armchaos.TargetSelectorClassification{ + // &armchaos.TargetListSelector{ + // Type: to.Ptr(armchaos.SelectorTypeList), + // ID: to.Ptr("selector1"), + // Targets: []*armchaos.TargetReference{ + // { + // Type: to.Ptr(armchaos.TargetReferenceTypeChaosTarget), + // ID: to.Ptr("/subscriptions/6b052e15-03d3-4f17-b2e1-be7f07588291/resourceGroups/exampleRG/providers/Microsoft.Compute/virtualMachines/exampleVM/providers/Microsoft.Chaos/targets/Microsoft-VirtualMachine"), + // }, + // }, + // }, + // }, + // Steps: []*armchaos.ExperimentStep{ + // { + // Name: to.Ptr("step1"), + // Branches: []*armchaos.ExperimentBranch{ + // { + // Name: to.Ptr("branch1"), + // Actions: []armchaos.ExperimentActionClassification{ + // &armchaos.ContinuousAction{ + // Name: to.Ptr("urn:csci:provider:providername:Shutdown/1.0"), + // Type: to.Ptr(armchaos.ExperimentActionTypeContinuous), + // Duration: to.Ptr("PT10M"), + // Parameters: []*armchaos.KeyValuePair{ + // { + // Key: to.Ptr("abruptShutdown"), + // Value: to.Ptr("false"), + // }, + // }, + // SelectorID: to.Ptr("selector1"), + // }, + // }, + // }, + // }, + // }, + // }, + // }, + // SystemData: &armchaos.SystemData{ + // CreatedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2021-07-01T00:00:00.0Z"); return t}()), + // CreatedBy: to.Ptr("User"), + // CreatedByType: to.Ptr(armchaos.CreatedByType("b3a41dba-4415-4d36-9ee8-e5eaa86db976")), + // LastModifiedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2021-07-01T00:00:00.0Z"); return t}()), + // LastModifiedBy: to.Ptr("User"), + // LastModifiedByType: to.Ptr(armchaos.CreatedByType("b3a41dba-4415-4d36-9ee8-e5eaa86db976")), + // }, // }, // }, - // { - // Name: to.Ptr("14d98367-52ef-4596-be4f-53fc81bbfc33"), - // Type: to.Ptr("Microsoft.Chaos/experiments/executions"), - // ID: to.Ptr("/subscriptions/6b052e15-03d3-4f17-b2e1-be7f07588291/resourceGroups/exampleRG/providers/Microsoft.Chaos/experiments/exampleExperiment/executionDetails/14d98367-52ef-4596-be4f-53fc81bbfc33"), - // Properties: &armchaos.ExperimentExecutionProperties{ - // StartedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2020-12-14T21:52:52.255Z"); return t}()), - // Status: to.Ptr("success"), - // StoppedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2020-12-14T21:56:18.928Z"); return t}()), - // }, - // }}, + // }, // } } } -// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/e4009d2f8d3bf0271757e522c7d1c1997e193d44/specification/chaos/resource-manager/Microsoft.Chaos/stable/2024-01-01/examples/GetExperimentExecution.json -func ExampleExperimentsClient_GetExecution() { +// Generated from example definition: 2025-01-01/Experiments_Start.json +func ExampleExperimentsClient_BeginStart() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() - clientFactory, err := armchaos.NewClientFactory("", cred, nil) + clientFactory, err := armchaos.NewClientFactory("6b052e15-03d3-4f17-b2e1-be7f07588291", cred, nil) if err != nil { log.Fatalf("failed to create client: %v", err) } - res, err := clientFactory.NewExperimentsClient().GetExecution(ctx, "exampleRG", "exampleExperiment", "f24500ad-744e-4a26-864b-b76199eac333", nil) + poller, err := clientFactory.NewExperimentsClient().BeginStart(ctx, "exampleRG", "exampleExperiment", nil) if err != nil { log.Fatalf("failed to finish the request: %v", err) } - // You could use response here. We use blank identifier for just demo purposes. - _ = res - // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. - // res.ExperimentExecution = armchaos.ExperimentExecution{ - // Name: to.Ptr("f24500ad-744e-4a26-864b-b76199eac333"), - // Type: to.Ptr("Microsoft.Chaos/experiments/executions"), - // ID: to.Ptr("/subscriptions/6b052e15-03d3-4f17-b2e1-be7f07588291/resourceGroups/exampleRG/providers/Microsoft.Chaos/experiments/exampleExperiment/executions/f24500ad-744e-4a26-864b-b76199eac333"), - // Properties: &armchaos.ExperimentExecutionProperties{ - // StartedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2020-12-14T21:52:52.255Z"); return t}()), - // Status: to.Ptr("failed"), - // StoppedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2020-12-14T21:56:18.928Z"); return t}()), - // }, - // } + _, err = poller.PollUntilDone(ctx, nil) + if err != nil { + log.Fatalf("failed to pull the result: %v", err) + } } -// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/e4009d2f8d3bf0271757e522c7d1c1997e193d44/specification/chaos/resource-manager/Microsoft.Chaos/stable/2024-01-01/examples/DetailsExperiment.json -func ExampleExperimentsClient_ExecutionDetails() { +// Generated from example definition: 2025-01-01/Experiments_Update.json +func ExampleExperimentsClient_BeginUpdate() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() - clientFactory, err := armchaos.NewClientFactory("", cred, nil) + clientFactory, err := armchaos.NewClientFactory("6b052e15-03d3-4f17-b2e1-be7f07588291", cred, nil) if err != nil { log.Fatalf("failed to create client: %v", err) } - res, err := clientFactory.NewExperimentsClient().ExecutionDetails(ctx, "exampleRG", "exampleExperiment", "f24500ad-744e-4a26-864b-b76199eac333", nil) + poller, err := clientFactory.NewExperimentsClient().BeginUpdate(ctx, "exampleRG", "exampleExperiment", armchaos.ExperimentUpdate{ + Identity: &armchaos.ManagedServiceIdentity{ + Type: to.Ptr(armchaos.ManagedServiceIdentityTypeUserAssigned), + UserAssignedIdentities: map[string]*armchaos.UserAssignedIdentity{ + "/subscriptions/6b052e15-03d3-4f17-b2e1-be7f07588291/resourceGroups/exampleRG/providers/Microsoft.ManagedIdentity/userAssignedIdentity/exampleUMI": {}, + }, + }, + Tags: map[string]*string{ + "key1": to.Ptr("value1"), + "key2": to.Ptr("value2"), + }, + }, nil) if err != nil { log.Fatalf("failed to finish the request: %v", err) } + res, err := poller.PollUntilDone(ctx, nil) + if err != nil { + log.Fatalf("failed to pull the result: %v", err) + } // You could use response here. We use blank identifier for just demo purposes. _ = res // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. - // res.ExperimentExecutionDetails = armchaos.ExperimentExecutionDetails{ - // Name: to.Ptr("f24500ad-744e-4a26-864b-b76199eac333"), - // Type: to.Ptr("Microsoft.Chaos/experiments/executions/getExecutionDetails"), - // ID: to.Ptr("/subscriptions/6b052e15-03d3-4f17-b2e1-be7f07588291/resourceGroups/exampleRG/providers/Microsoft.Chaos/experiments/exampleExperiment/executions/f24500ad-744e-4a26-864b-b76199eac333/getExecutionDetails"), - // Properties: &armchaos.ExperimentExecutionDetailsProperties{ - // StartedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2020-12-14T21:52:52.255Z"); return t}()), - // Status: to.Ptr("failed"), - // StoppedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2020-12-14T21:56:18.928Z"); return t}()), - // FailureReason: to.Ptr("Dependency failure"), - // LastActionAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2020-12-14T21:52:52.255Z"); return t}()), - // RunInformation: &armchaos.ExperimentExecutionDetailsPropertiesRunInformation{ - // Steps: []*armchaos.StepStatus{ + // res = armchaos.ExperimentsClientUpdateResponse{ + // Experiment: &armchaos.Experiment{ + // Name: to.Ptr("exampleExperiment"), + // Type: to.Ptr("Microsoft.Chaos/experiments"), + // ID: to.Ptr("/subscriptions/6b052e15-03d3-4f17-b2e1-be7f07588291/resourceGroups/exampleRG/providers/Microsoft.Chaos/experiments/exampleExperiment"), + // Identity: &armchaos.ManagedServiceIdentity{ + // Type: to.Ptr(armchaos.ManagedServiceIdentityTypeUserAssigned), + // PrincipalID: to.Ptr("d04ab567-2c07-43ef-a7f4-4527626b7f56"), + // TenantID: to.Ptr("8c3e2fb2-fe7a-4bf1-b779-d73990782fe6"), + // UserAssignedIdentities: map[string]*armchaos.UserAssignedIdentity{ + // "/subscriptions/6b052e15-03d3-4f17-b2e1-be7f07588291/resourceGroups/exampleRG/providers/Microsoft.ManagedIdentity/userAssignedIdentity/exampleUMI": &armchaos.UserAssignedIdentity{ + // }, + // }, + // }, + // Location: to.Ptr("centraluseuap"), + // Properties: &armchaos.ExperimentProperties{ + // Selectors: []armchaos.TargetSelectorClassification{ + // &armchaos.TargetListSelector{ + // Type: to.Ptr(armchaos.SelectorTypeList), + // ID: to.Ptr("selector1"), + // Targets: []*armchaos.TargetReference{ + // { + // Type: to.Ptr(armchaos.TargetReferenceTypeChaosTarget), + // ID: to.Ptr("/subscriptions/6b052e15-03d3-4f17-b2e1-be7f07588291/resourceGroups/exampleRG/providers/Microsoft.Compute/virtualMachines/exampleVM/providers/Microsoft.Chaos/targets/Microsoft-VirtualMachine"), + // }, + // }, + // }, + // }, + // Steps: []*armchaos.ExperimentStep{ // { - // Branches: []*armchaos.BranchStatus{ + // Name: to.Ptr("step1"), + // Branches: []*armchaos.ExperimentBranch{ // { - // Actions: []*armchaos.ActionStatus{ - // { - // ActionID: to.Ptr("59499d33-6751-4b6e-a1f6-58f4d56a040a"), - // ActionName: to.Ptr("urn:provider:agent-v2:Microsoft.Azure.Chaos.Fault.CPUPressureAllProcessors"), - // EndTime: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2020-12-14T21:56:13.627Z"); return t}()), - // StartTime: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2020-12-14T21:56:13.627Z"); return t}()), - // Status: to.Ptr("failed"), - // Targets: []*armchaos.ExperimentExecutionActionTargetDetailsProperties{ + // Name: to.Ptr("branch1"), + // Actions: []armchaos.ExperimentActionClassification{ + // &armchaos.ContinuousAction{ + // Name: to.Ptr("urn:csci:provider:providername:Shutdown/1.0"), + // Type: to.Ptr(armchaos.ExperimentActionTypeContinuous), + // Duration: to.Ptr("PT10M"), + // Parameters: []*armchaos.KeyValuePair{ // { - // Status: to.Ptr("succeeded"), - // Target: to.Ptr("/subscriptions/6b052e15-03d3-4f17-b2e1-be7f07588291/resourceGroups/exampleRG/providers/Microsoft.Compute/virtualMachines/VM1"), - // TargetCompletedTime: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2021-04-02T17:30:55.000Z"); return t}()), - // TargetFailedTime: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2021-04-02T16:30:55.000Z"); return t}()), + // Key: to.Ptr("abruptShutdown"), + // Value: to.Ptr("false"), // }, - // { - // Status: to.Ptr("failed"), - // Target: to.Ptr("/subscriptions/6b052e15-03d3-4f17-b2e1-be7f07588291/resourceGroups/exampleRG/providers/Microsoft.Compute/virtualMachines/VM1"), - // TargetCompletedTime: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2021-04-02T17:30:55.000Z"); return t}()), - // TargetFailedTime: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2021-04-02T16:30:55.000Z"); return t}()), - // }}, - // }}, - // BranchID: to.Ptr("FirstBranch"), - // BranchName: to.Ptr("FirstBranch"), - // Status: to.Ptr("failed"), - // }}, - // Status: to.Ptr("failed"), - // StepID: to.Ptr("FirstStep"), - // StepName: to.Ptr("FirstStep"), - // }}, + // }, + // SelectorID: to.Ptr("selector1"), + // }, + // }, + // }, + // }, + // }, + // }, + // }, + // SystemData: &armchaos.SystemData{ + // CreatedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2021-07-01T00:00:00.0Z"); return t}()), + // CreatedBy: to.Ptr("User"), + // CreatedByType: to.Ptr(armchaos.CreatedByType("b3a41dba-4415-4d36-9ee8-e5eaa86db976")), + // LastModifiedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2021-07-01T00:00:00.0Z"); return t}()), + // LastModifiedBy: to.Ptr("User"), + // LastModifiedByType: to.Ptr(armchaos.CreatedByType("b3a41dba-4415-4d36-9ee8-e5eaa86db976")), + // }, + // Tags: map[string]*string{ + // "key1": to.Ptr("value1"), + // "key2": to.Ptr("value2"), // }, // }, // } diff --git a/sdk/resourcemanager/chaos/armchaos/experiments_live_test.go b/sdk/resourcemanager/chaos/armchaos/experiments_live_test.go index 8d7d1dd2ff2c..365482e238c0 100644 --- a/sdk/resourcemanager/chaos/armchaos/experiments_live_test.go +++ b/sdk/resourcemanager/chaos/armchaos/experiments_live_test.go @@ -15,7 +15,7 @@ import ( "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" "github.com/Azure/azure-sdk-for-go/sdk/internal/recording" - "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/chaos/armchaos" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/chaos/armchaos/v2" "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/internal/v3/testutil" "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/resources/armresources" "github.com/stretchr/testify/suite" diff --git a/sdk/resourcemanager/chaos/armchaos/fake/capabilities_server.go b/sdk/resourcemanager/chaos/armchaos/fake/capabilities_server.go index 859cfec668df..aeb4596566c8 100644 --- a/sdk/resourcemanager/chaos/armchaos/fake/capabilities_server.go +++ b/sdk/resourcemanager/chaos/armchaos/fake/capabilities_server.go @@ -1,10 +1,6 @@ -//go:build go1.18 -// +build go1.18 - // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. -// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. package fake @@ -16,7 +12,7 @@ import ( "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" - "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/chaos/armchaos" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/chaos/armchaos/v2" "net/http" "net/url" "regexp" @@ -25,8 +21,8 @@ import ( // CapabilitiesServer is a fake server for instances of the armchaos.CapabilitiesClient type. type CapabilitiesServer struct { // CreateOrUpdate is the fake for method CapabilitiesClient.CreateOrUpdate - // HTTP status codes to indicate success: http.StatusOK - CreateOrUpdate func(ctx context.Context, resourceGroupName string, parentProviderNamespace string, parentResourceType string, parentResourceName string, targetName string, capabilityName string, capability armchaos.Capability, options *armchaos.CapabilitiesClientCreateOrUpdateOptions) (resp azfake.Responder[armchaos.CapabilitiesClientCreateOrUpdateResponse], errResp azfake.ErrorResponder) + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + CreateOrUpdate func(ctx context.Context, resourceGroupName string, parentProviderNamespace string, parentResourceType string, parentResourceName string, targetName string, capabilityName string, resource armchaos.Capability, options *armchaos.CapabilitiesClientCreateOrUpdateOptions) (resp azfake.Responder[armchaos.CapabilitiesClientCreateOrUpdateResponse], errResp azfake.ErrorResponder) // Delete is the fake for method CapabilitiesClient.Delete // HTTP status codes to indicate success: http.StatusOK, http.StatusNoContent @@ -66,27 +62,46 @@ func (c *CapabilitiesServerTransport) Do(req *http.Request) (*http.Response, err return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} } - var resp *http.Response - var err error + return c.dispatchToMethodFake(req, method) +} - switch method { - case "CapabilitiesClient.CreateOrUpdate": - resp, err = c.dispatchCreateOrUpdate(req) - case "CapabilitiesClient.Delete": - resp, err = c.dispatchDelete(req) - case "CapabilitiesClient.Get": - resp, err = c.dispatchGet(req) - case "CapabilitiesClient.NewListPager": - resp, err = c.dispatchNewListPager(req) - default: - err = fmt.Errorf("unhandled API %s", method) - } +func (c *CapabilitiesServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result) + defer close(resultChan) - if err != nil { - return nil, err - } + go func() { + var intercepted bool + var res result + if capabilitiesServerTransportInterceptor != nil { + res.resp, res.err, intercepted = capabilitiesServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "CapabilitiesClient.CreateOrUpdate": + res.resp, res.err = c.dispatchCreateOrUpdate(req) + case "CapabilitiesClient.Delete": + res.resp, res.err = c.dispatchDelete(req) + case "CapabilitiesClient.Get": + res.resp, res.err = c.dispatchGet(req) + case "CapabilitiesClient.NewListPager": + res.resp, res.err = c.dispatchNewListPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } - return resp, nil + } + select { + case resultChan <- res: + case <-req.Context().Done(): + } + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } } func (c *CapabilitiesServerTransport) dispatchCreateOrUpdate(req *http.Request) (*http.Response, error) { @@ -132,8 +147,8 @@ func (c *CapabilitiesServerTransport) dispatchCreateOrUpdate(req *http.Request) 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)} + 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).Capability, req) if err != nil { @@ -269,15 +284,15 @@ func (c *CapabilitiesServerTransport) dispatchNewListPager(req *http.Request) (* if err != nil { return nil, err } - targetNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("targetName")]) + continuationTokenUnescaped, err := url.QueryUnescape(qp.Get("continuationToken")) if err != nil { return nil, err } - continuationTokenUnescaped, err := url.QueryUnescape(qp.Get("continuationToken")) + continuationTokenParam := getOptional(continuationTokenUnescaped) + targetNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("targetName")]) if err != nil { return nil, err } - continuationTokenParam := getOptional(continuationTokenUnescaped) var options *armchaos.CapabilitiesClientListOptions if continuationTokenParam != nil { options = &armchaos.CapabilitiesClientListOptions{ @@ -304,3 +319,9 @@ func (c *CapabilitiesServerTransport) dispatchNewListPager(req *http.Request) (* } return resp, nil } + +// set this to conditionally intercept incoming requests to CapabilitiesServerTransport +var capabilitiesServerTransportInterceptor 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/chaos/armchaos/fake/capabilitytypes_server.go b/sdk/resourcemanager/chaos/armchaos/fake/capabilitytypes_server.go index 4ab582c9e43f..eea287e2d4a4 100644 --- a/sdk/resourcemanager/chaos/armchaos/fake/capabilitytypes_server.go +++ b/sdk/resourcemanager/chaos/armchaos/fake/capabilitytypes_server.go @@ -1,10 +1,6 @@ -//go:build go1.18 -// +build go1.18 - // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. -// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. package fake @@ -16,7 +12,7 @@ import ( "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" - "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/chaos/armchaos" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/chaos/armchaos/v2" "net/http" "net/url" "regexp" @@ -26,11 +22,11 @@ import ( type CapabilityTypesServer struct { // Get is the fake for method CapabilityTypesClient.Get // HTTP status codes to indicate success: http.StatusOK - Get func(ctx context.Context, locationName string, targetTypeName string, capabilityTypeName string, options *armchaos.CapabilityTypesClientGetOptions) (resp azfake.Responder[armchaos.CapabilityTypesClientGetResponse], errResp azfake.ErrorResponder) + Get func(ctx context.Context, location string, targetTypeName string, capabilityTypeName string, options *armchaos.CapabilityTypesClientGetOptions) (resp azfake.Responder[armchaos.CapabilityTypesClientGetResponse], errResp azfake.ErrorResponder) // NewListPager is the fake for method CapabilityTypesClient.NewListPager // HTTP status codes to indicate success: http.StatusOK - NewListPager func(locationName string, targetTypeName string, options *armchaos.CapabilityTypesClientListOptions) (resp azfake.PagerResponder[armchaos.CapabilityTypesClientListResponse]) + NewListPager func(location string, targetTypeName string, options *armchaos.CapabilityTypesClientListOptions) (resp azfake.PagerResponder[armchaos.CapabilityTypesClientListResponse]) } // NewCapabilityTypesServerTransport creates a new instance of CapabilityTypesServerTransport with the provided implementation. @@ -58,36 +54,55 @@ func (c *CapabilityTypesServerTransport) Do(req *http.Request) (*http.Response, return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} } - var resp *http.Response - var err error + return c.dispatchToMethodFake(req, method) +} - switch method { - case "CapabilityTypesClient.Get": - resp, err = c.dispatchGet(req) - case "CapabilityTypesClient.NewListPager": - resp, err = c.dispatchNewListPager(req) - default: - err = fmt.Errorf("unhandled API %s", method) - } +func (c *CapabilityTypesServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result) + defer close(resultChan) - if err != nil { - return nil, err - } + go func() { + var intercepted bool + var res result + if capabilityTypesServerTransportInterceptor != nil { + res.resp, res.err, intercepted = capabilityTypesServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "CapabilityTypesClient.Get": + res.resp, res.err = c.dispatchGet(req) + case "CapabilityTypesClient.NewListPager": + res.resp, res.err = c.dispatchNewListPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } - return resp, nil + } + select { + case resultChan <- res: + case <-req.Context().Done(): + } + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } } func (c *CapabilityTypesServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { if c.srv.Get == nil { return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} } - const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Chaos/locations/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/targetTypes/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/capabilityTypes/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Chaos/locations/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/targetTypes/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/capabilityTypes/(?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) } - locationNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("locationName")]) + locationParam, err := url.PathUnescape(matches[regex.SubexpIndex("location")]) if err != nil { return nil, err } @@ -99,7 +114,7 @@ func (c *CapabilityTypesServerTransport) dispatchGet(req *http.Request) (*http.R if err != nil { return nil, err } - respr, errRespr := c.srv.Get(req.Context(), locationNameParam, targetTypeNameParam, capabilityTypeNameParam, nil) + respr, errRespr := c.srv.Get(req.Context(), locationParam, targetTypeNameParam, capabilityTypeNameParam, nil) if respErr := server.GetError(errRespr, req); respErr != nil { return nil, respErr } @@ -120,14 +135,14 @@ func (c *CapabilityTypesServerTransport) dispatchNewListPager(req *http.Request) } newListPager := c.newListPager.get(req) if newListPager == nil { - const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Chaos/locations/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/targetTypes/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/capabilityTypes` + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Chaos/locations/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/targetTypes/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/capabilityTypes` 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() - locationNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("locationName")]) + locationParam, err := url.PathUnescape(matches[regex.SubexpIndex("location")]) if err != nil { return nil, err } @@ -146,7 +161,7 @@ func (c *CapabilityTypesServerTransport) dispatchNewListPager(req *http.Request) ContinuationToken: continuationTokenParam, } } - resp := c.srv.NewListPager(locationNameParam, targetTypeNameParam, options) + resp := c.srv.NewListPager(locationParam, targetTypeNameParam, options) newListPager = &resp c.newListPager.add(req, newListPager) server.PagerResponderInjectNextLinks(newListPager, req, func(page *armchaos.CapabilityTypesClientListResponse, createLink func() string) { @@ -166,3 +181,9 @@ func (c *CapabilityTypesServerTransport) dispatchNewListPager(req *http.Request) } return resp, nil } + +// set this to conditionally intercept incoming requests to CapabilityTypesServerTransport +var capabilityTypesServerTransportInterceptor 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/chaos/armchaos/fake/experimentexecutions_server.go b/sdk/resourcemanager/chaos/armchaos/fake/experimentexecutions_server.go new file mode 100644 index 000000000000..0d0e02b081d9 --- /dev/null +++ b/sdk/resourcemanager/chaos/armchaos/fake/experimentexecutions_server.go @@ -0,0 +1,220 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/chaos/armchaos/v2" + "net/http" + "net/url" + "regexp" +) + +// ExperimentExecutionsServer is a fake server for instances of the armchaos.ExperimentExecutionsClient type. +type ExperimentExecutionsServer struct { + // GetExecution is the fake for method ExperimentExecutionsClient.GetExecution + // HTTP status codes to indicate success: http.StatusOK + GetExecution func(ctx context.Context, resourceGroupName string, experimentName string, executionID string, options *armchaos.ExperimentExecutionsClientGetExecutionOptions) (resp azfake.Responder[armchaos.ExperimentExecutionsClientGetExecutionResponse], errResp azfake.ErrorResponder) + + // GetExecutionDetails is the fake for method ExperimentExecutionsClient.GetExecutionDetails + // HTTP status codes to indicate success: http.StatusOK + GetExecutionDetails func(ctx context.Context, resourceGroupName string, experimentName string, executionID string, options *armchaos.ExperimentExecutionsClientGetExecutionDetailsOptions) (resp azfake.Responder[armchaos.ExperimentExecutionsClientGetExecutionDetailsResponse], errResp azfake.ErrorResponder) + + // NewListAllExecutionsPager is the fake for method ExperimentExecutionsClient.NewListAllExecutionsPager + // HTTP status codes to indicate success: http.StatusOK + NewListAllExecutionsPager func(resourceGroupName string, experimentName string, options *armchaos.ExperimentExecutionsClientListAllExecutionsOptions) (resp azfake.PagerResponder[armchaos.ExperimentExecutionsClientListAllExecutionsResponse]) +} + +// NewExperimentExecutionsServerTransport creates a new instance of ExperimentExecutionsServerTransport with the provided implementation. +// The returned ExperimentExecutionsServerTransport instance is connected to an instance of armchaos.ExperimentExecutionsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewExperimentExecutionsServerTransport(srv *ExperimentExecutionsServer) *ExperimentExecutionsServerTransport { + return &ExperimentExecutionsServerTransport{ + srv: srv, + newListAllExecutionsPager: newTracker[azfake.PagerResponder[armchaos.ExperimentExecutionsClientListAllExecutionsResponse]](), + } +} + +// ExperimentExecutionsServerTransport connects instances of armchaos.ExperimentExecutionsClient to instances of ExperimentExecutionsServer. +// Don't use this type directly, use NewExperimentExecutionsServerTransport instead. +type ExperimentExecutionsServerTransport struct { + srv *ExperimentExecutionsServer + newListAllExecutionsPager *tracker[azfake.PagerResponder[armchaos.ExperimentExecutionsClientListAllExecutionsResponse]] +} + +// Do implements the policy.Transporter interface for ExperimentExecutionsServerTransport. +func (e *ExperimentExecutionsServerTransport) 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 *ExperimentExecutionsServerTransport) 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 experimentExecutionsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = experimentExecutionsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ExperimentExecutionsClient.GetExecution": + res.resp, res.err = e.dispatchGetExecution(req) + case "ExperimentExecutionsClient.GetExecutionDetails": + res.resp, res.err = e.dispatchGetExecutionDetails(req) + case "ExperimentExecutionsClient.NewListAllExecutionsPager": + res.resp, res.err = e.dispatchNewListAllExecutionsPager(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 *ExperimentExecutionsServerTransport) dispatchGetExecution(req *http.Request) (*http.Response, error) { + if e.srv.GetExecution == nil { + return nil, &nonRetriableError{errors.New("fake for method GetExecution not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Chaos/experiments/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/executions/(?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 + } + experimentNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("experimentName")]) + if err != nil { + return nil, err + } + executionIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("executionId")]) + if err != nil { + return nil, err + } + respr, errRespr := e.srv.GetExecution(req.Context(), resourceGroupNameParam, experimentNameParam, executionIDParam, 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).ExperimentExecution, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (e *ExperimentExecutionsServerTransport) dispatchGetExecutionDetails(req *http.Request) (*http.Response, error) { + if e.srv.GetExecutionDetails == nil { + return nil, &nonRetriableError{errors.New("fake for method GetExecutionDetails not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Chaos/experiments/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/executions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/getExecutionDetails` + 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 + } + experimentNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("experimentName")]) + if err != nil { + return nil, err + } + executionIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("executionId")]) + if err != nil { + return nil, err + } + respr, errRespr := e.srv.GetExecutionDetails(req.Context(), resourceGroupNameParam, experimentNameParam, executionIDParam, 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).ExperimentExecutionDetails, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (e *ExperimentExecutionsServerTransport) dispatchNewListAllExecutionsPager(req *http.Request) (*http.Response, error) { + if e.srv.NewListAllExecutionsPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListAllExecutionsPager not implemented")} + } + newListAllExecutionsPager := e.newListAllExecutionsPager.get(req) + if newListAllExecutionsPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Chaos/experiments/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/executions` + 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 + } + experimentNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("experimentName")]) + if err != nil { + return nil, err + } + resp := e.srv.NewListAllExecutionsPager(resourceGroupNameParam, experimentNameParam, nil) + newListAllExecutionsPager = &resp + e.newListAllExecutionsPager.add(req, newListAllExecutionsPager) + server.PagerResponderInjectNextLinks(newListAllExecutionsPager, req, func(page *armchaos.ExperimentExecutionsClientListAllExecutionsResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListAllExecutionsPager, req) + if err != nil { + return nil, err + } + if !contains([]int{http.StatusOK}, resp.StatusCode) { + e.newListAllExecutionsPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListAllExecutionsPager) { + e.newListAllExecutionsPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ExperimentExecutionsServerTransport +var experimentExecutionsServerTransportInterceptor 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/chaos/armchaos/fake/experiments_server.go b/sdk/resourcemanager/chaos/armchaos/fake/experiments_server.go index 110967111c7d..41e0599a602e 100644 --- a/sdk/resourcemanager/chaos/armchaos/fake/experiments_server.go +++ b/sdk/resourcemanager/chaos/armchaos/fake/experiments_server.go @@ -1,10 +1,6 @@ -//go:build go1.18 -// +build go1.18 - // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. -// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. package fake @@ -16,7 +12,7 @@ import ( "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" - "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/chaos/armchaos" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/chaos/armchaos/v2" "net/http" "net/url" "regexp" @@ -26,29 +22,21 @@ import ( // ExperimentsServer is a fake server for instances of the armchaos.ExperimentsClient type. type ExperimentsServer struct { // BeginCancel is the fake for method ExperimentsClient.BeginCancel - // HTTP status codes to indicate success: http.StatusAccepted + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent BeginCancel func(ctx context.Context, resourceGroupName string, experimentName string, options *armchaos.ExperimentsClientBeginCancelOptions) (resp azfake.PollerResponder[armchaos.ExperimentsClientCancelResponse], errResp azfake.ErrorResponder) // BeginCreateOrUpdate is the fake for method ExperimentsClient.BeginCreateOrUpdate // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated - BeginCreateOrUpdate func(ctx context.Context, resourceGroupName string, experimentName string, experiment armchaos.Experiment, options *armchaos.ExperimentsClientBeginCreateOrUpdateOptions) (resp azfake.PollerResponder[armchaos.ExperimentsClientCreateOrUpdateResponse], errResp azfake.ErrorResponder) + BeginCreateOrUpdate func(ctx context.Context, resourceGroupName string, experimentName string, resource armchaos.Experiment, options *armchaos.ExperimentsClientBeginCreateOrUpdateOptions) (resp azfake.PollerResponder[armchaos.ExperimentsClientCreateOrUpdateResponse], errResp azfake.ErrorResponder) // BeginDelete is the fake for method ExperimentsClient.BeginDelete - // HTTP status codes to indicate success: http.StatusAccepted + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent BeginDelete func(ctx context.Context, resourceGroupName string, experimentName string, options *armchaos.ExperimentsClientBeginDeleteOptions) (resp azfake.PollerResponder[armchaos.ExperimentsClientDeleteResponse], errResp azfake.ErrorResponder) - // ExecutionDetails is the fake for method ExperimentsClient.ExecutionDetails - // HTTP status codes to indicate success: http.StatusOK - ExecutionDetails func(ctx context.Context, resourceGroupName string, experimentName string, executionID string, options *armchaos.ExperimentsClientExecutionDetailsOptions) (resp azfake.Responder[armchaos.ExperimentsClientExecutionDetailsResponse], errResp azfake.ErrorResponder) - // Get is the fake for method ExperimentsClient.Get // HTTP status codes to indicate success: http.StatusOK Get func(ctx context.Context, resourceGroupName string, experimentName string, options *armchaos.ExperimentsClientGetOptions) (resp azfake.Responder[armchaos.ExperimentsClientGetResponse], errResp azfake.ErrorResponder) - // GetExecution is the fake for method ExperimentsClient.GetExecution - // HTTP status codes to indicate success: http.StatusOK - GetExecution func(ctx context.Context, resourceGroupName string, experimentName string, executionID string, options *armchaos.ExperimentsClientGetExecutionOptions) (resp azfake.Responder[armchaos.ExperimentsClientGetExecutionResponse], errResp azfake.ErrorResponder) - // NewListPager is the fake for method ExperimentsClient.NewListPager // HTTP status codes to indicate success: http.StatusOK NewListPager func(resourceGroupName string, options *armchaos.ExperimentsClientListOptions) (resp azfake.PagerResponder[armchaos.ExperimentsClientListResponse]) @@ -57,17 +45,13 @@ type ExperimentsServer struct { // HTTP status codes to indicate success: http.StatusOK NewListAllPager func(options *armchaos.ExperimentsClientListAllOptions) (resp azfake.PagerResponder[armchaos.ExperimentsClientListAllResponse]) - // NewListAllExecutionsPager is the fake for method ExperimentsClient.NewListAllExecutionsPager - // HTTP status codes to indicate success: http.StatusOK - NewListAllExecutionsPager func(resourceGroupName string, experimentName string, options *armchaos.ExperimentsClientListAllExecutionsOptions) (resp azfake.PagerResponder[armchaos.ExperimentsClientListAllExecutionsResponse]) - // BeginStart is the fake for method ExperimentsClient.BeginStart - // HTTP status codes to indicate success: http.StatusAccepted + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent BeginStart func(ctx context.Context, resourceGroupName string, experimentName string, options *armchaos.ExperimentsClientBeginStartOptions) (resp azfake.PollerResponder[armchaos.ExperimentsClientStartResponse], errResp azfake.ErrorResponder) // BeginUpdate is the fake for method ExperimentsClient.BeginUpdate - // HTTP status codes to indicate success: http.StatusAccepted - BeginUpdate func(ctx context.Context, resourceGroupName string, experimentName string, experiment armchaos.ExperimentUpdate, options *armchaos.ExperimentsClientBeginUpdateOptions) (resp azfake.PollerResponder[armchaos.ExperimentsClientUpdateResponse], errResp azfake.ErrorResponder) + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted + BeginUpdate func(ctx context.Context, resourceGroupName string, experimentName string, properties armchaos.ExperimentUpdate, options *armchaos.ExperimentsClientBeginUpdateOptions) (resp azfake.PollerResponder[armchaos.ExperimentsClientUpdateResponse], errResp azfake.ErrorResponder) } // NewExperimentsServerTransport creates a new instance of ExperimentsServerTransport with the provided implementation. @@ -75,30 +59,28 @@ type ExperimentsServer struct { // azcore.ClientOptions.Transporter field in the client's constructor parameters. func NewExperimentsServerTransport(srv *ExperimentsServer) *ExperimentsServerTransport { return &ExperimentsServerTransport{ - srv: srv, - beginCancel: newTracker[azfake.PollerResponder[armchaos.ExperimentsClientCancelResponse]](), - beginCreateOrUpdate: newTracker[azfake.PollerResponder[armchaos.ExperimentsClientCreateOrUpdateResponse]](), - beginDelete: newTracker[azfake.PollerResponder[armchaos.ExperimentsClientDeleteResponse]](), - newListPager: newTracker[azfake.PagerResponder[armchaos.ExperimentsClientListResponse]](), - newListAllPager: newTracker[azfake.PagerResponder[armchaos.ExperimentsClientListAllResponse]](), - newListAllExecutionsPager: newTracker[azfake.PagerResponder[armchaos.ExperimentsClientListAllExecutionsResponse]](), - beginStart: newTracker[azfake.PollerResponder[armchaos.ExperimentsClientStartResponse]](), - beginUpdate: newTracker[azfake.PollerResponder[armchaos.ExperimentsClientUpdateResponse]](), + srv: srv, + beginCancel: newTracker[azfake.PollerResponder[armchaos.ExperimentsClientCancelResponse]](), + beginCreateOrUpdate: newTracker[azfake.PollerResponder[armchaos.ExperimentsClientCreateOrUpdateResponse]](), + beginDelete: newTracker[azfake.PollerResponder[armchaos.ExperimentsClientDeleteResponse]](), + newListPager: newTracker[azfake.PagerResponder[armchaos.ExperimentsClientListResponse]](), + newListAllPager: newTracker[azfake.PagerResponder[armchaos.ExperimentsClientListAllResponse]](), + beginStart: newTracker[azfake.PollerResponder[armchaos.ExperimentsClientStartResponse]](), + beginUpdate: newTracker[azfake.PollerResponder[armchaos.ExperimentsClientUpdateResponse]](), } } // ExperimentsServerTransport connects instances of armchaos.ExperimentsClient to instances of ExperimentsServer. // Don't use this type directly, use NewExperimentsServerTransport instead. type ExperimentsServerTransport struct { - srv *ExperimentsServer - beginCancel *tracker[azfake.PollerResponder[armchaos.ExperimentsClientCancelResponse]] - beginCreateOrUpdate *tracker[azfake.PollerResponder[armchaos.ExperimentsClientCreateOrUpdateResponse]] - beginDelete *tracker[azfake.PollerResponder[armchaos.ExperimentsClientDeleteResponse]] - newListPager *tracker[azfake.PagerResponder[armchaos.ExperimentsClientListResponse]] - newListAllPager *tracker[azfake.PagerResponder[armchaos.ExperimentsClientListAllResponse]] - newListAllExecutionsPager *tracker[azfake.PagerResponder[armchaos.ExperimentsClientListAllExecutionsResponse]] - beginStart *tracker[azfake.PollerResponder[armchaos.ExperimentsClientStartResponse]] - beginUpdate *tracker[azfake.PollerResponder[armchaos.ExperimentsClientUpdateResponse]] + srv *ExperimentsServer + beginCancel *tracker[azfake.PollerResponder[armchaos.ExperimentsClientCancelResponse]] + beginCreateOrUpdate *tracker[azfake.PollerResponder[armchaos.ExperimentsClientCreateOrUpdateResponse]] + beginDelete *tracker[azfake.PollerResponder[armchaos.ExperimentsClientDeleteResponse]] + newListPager *tracker[azfake.PagerResponder[armchaos.ExperimentsClientListResponse]] + newListAllPager *tracker[azfake.PagerResponder[armchaos.ExperimentsClientListAllResponse]] + beginStart *tracker[azfake.PollerResponder[armchaos.ExperimentsClientStartResponse]] + beginUpdate *tracker[azfake.PollerResponder[armchaos.ExperimentsClientUpdateResponse]] } // Do implements the policy.Transporter interface for ExperimentsServerTransport. @@ -109,41 +91,54 @@ func (e *ExperimentsServerTransport) Do(req *http.Request) (*http.Response, erro return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} } - var resp *http.Response - var err error - - switch method { - case "ExperimentsClient.BeginCancel": - resp, err = e.dispatchBeginCancel(req) - case "ExperimentsClient.BeginCreateOrUpdate": - resp, err = e.dispatchBeginCreateOrUpdate(req) - case "ExperimentsClient.BeginDelete": - resp, err = e.dispatchBeginDelete(req) - case "ExperimentsClient.ExecutionDetails": - resp, err = e.dispatchExecutionDetails(req) - case "ExperimentsClient.Get": - resp, err = e.dispatchGet(req) - case "ExperimentsClient.GetExecution": - resp, err = e.dispatchGetExecution(req) - case "ExperimentsClient.NewListPager": - resp, err = e.dispatchNewListPager(req) - case "ExperimentsClient.NewListAllPager": - resp, err = e.dispatchNewListAllPager(req) - case "ExperimentsClient.NewListAllExecutionsPager": - resp, err = e.dispatchNewListAllExecutionsPager(req) - case "ExperimentsClient.BeginStart": - resp, err = e.dispatchBeginStart(req) - case "ExperimentsClient.BeginUpdate": - resp, err = e.dispatchBeginUpdate(req) - default: - err = fmt.Errorf("unhandled API %s", method) - } + return e.dispatchToMethodFake(req, method) +} - if err != nil { - return nil, err - } +func (e *ExperimentsServerTransport) 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 experimentsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = experimentsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ExperimentsClient.BeginCancel": + res.resp, res.err = e.dispatchBeginCancel(req) + case "ExperimentsClient.BeginCreateOrUpdate": + res.resp, res.err = e.dispatchBeginCreateOrUpdate(req) + case "ExperimentsClient.BeginDelete": + res.resp, res.err = e.dispatchBeginDelete(req) + case "ExperimentsClient.Get": + res.resp, res.err = e.dispatchGet(req) + case "ExperimentsClient.NewListPager": + res.resp, res.err = e.dispatchNewListPager(req) + case "ExperimentsClient.NewListAllPager": + res.resp, res.err = e.dispatchNewListAllPager(req) + case "ExperimentsClient.BeginStart": + res.resp, res.err = e.dispatchBeginStart(req) + case "ExperimentsClient.BeginUpdate": + res.resp, res.err = e.dispatchBeginUpdate(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } - return resp, nil + } + select { + case resultChan <- res: + case <-req.Context().Done(): + } + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } } func (e *ExperimentsServerTransport) dispatchBeginCancel(req *http.Request) (*http.Response, error) { @@ -179,9 +174,9 @@ func (e *ExperimentsServerTransport) dispatchBeginCancel(req *http.Request) (*ht return nil, err } - if !contains([]int{http.StatusAccepted}, resp.StatusCode) { + if !contains([]int{http.StatusOK, http.StatusAccepted, http.StatusNoContent}, resp.StatusCode) { e.beginCancel.remove(req) - return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusAccepted", resp.StatusCode)} + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted, http.StatusNoContent", resp.StatusCode)} } if !server.PollerResponderMore(beginCancel) { e.beginCancel.remove(req) @@ -271,9 +266,9 @@ func (e *ExperimentsServerTransport) dispatchBeginDelete(req *http.Request) (*ht return nil, err } - if !contains([]int{http.StatusAccepted}, resp.StatusCode) { + if !contains([]int{http.StatusOK, http.StatusAccepted, http.StatusNoContent}, resp.StatusCode) { e.beginDelete.remove(req) - return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusAccepted", resp.StatusCode)} + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted, http.StatusNoContent", resp.StatusCode)} } if !server.PollerResponderMore(beginDelete) { e.beginDelete.remove(req) @@ -282,43 +277,6 @@ func (e *ExperimentsServerTransport) dispatchBeginDelete(req *http.Request) (*ht return resp, nil } -func (e *ExperimentsServerTransport) dispatchExecutionDetails(req *http.Request) (*http.Response, error) { - if e.srv.ExecutionDetails == nil { - return nil, &nonRetriableError{errors.New("fake for method ExecutionDetails not implemented")} - } - const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Chaos/experiments/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/executions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/getExecutionDetails` - 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 - } - experimentNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("experimentName")]) - if err != nil { - return nil, err - } - executionIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("executionId")]) - if err != nil { - return nil, err - } - respr, errRespr := e.srv.ExecutionDetails(req.Context(), resourceGroupNameParam, experimentNameParam, executionIDParam, 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).ExperimentExecutionDetails, req) - if err != nil { - return nil, err - } - return resp, nil -} - func (e *ExperimentsServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { if e.srv.Get == nil { return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} @@ -352,43 +310,6 @@ func (e *ExperimentsServerTransport) dispatchGet(req *http.Request) (*http.Respo return resp, nil } -func (e *ExperimentsServerTransport) dispatchGetExecution(req *http.Request) (*http.Response, error) { - if e.srv.GetExecution == nil { - return nil, &nonRetriableError{errors.New("fake for method GetExecution not implemented")} - } - const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Chaos/experiments/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/executions/(?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 - } - experimentNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("experimentName")]) - if err != nil { - return nil, err - } - executionIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("executionId")]) - if err != nil { - return nil, err - } - respr, errRespr := e.srv.GetExecution(req.Context(), resourceGroupNameParam, experimentNameParam, executionIDParam, 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).ExperimentExecution, req) - if err != nil { - return nil, err - } - return resp, nil -} - func (e *ExperimentsServerTransport) dispatchNewListPager(req *http.Request) (*http.Response, error) { if e.srv.NewListPager == nil { return nil, &nonRetriableError{errors.New("fake for method NewListPager not implemented")} @@ -501,47 +422,6 @@ func (e *ExperimentsServerTransport) dispatchNewListAllPager(req *http.Request) return resp, nil } -func (e *ExperimentsServerTransport) dispatchNewListAllExecutionsPager(req *http.Request) (*http.Response, error) { - if e.srv.NewListAllExecutionsPager == nil { - return nil, &nonRetriableError{errors.New("fake for method NewListAllExecutionsPager not implemented")} - } - newListAllExecutionsPager := e.newListAllExecutionsPager.get(req) - if newListAllExecutionsPager == nil { - const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Chaos/experiments/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/executions` - 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 - } - experimentNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("experimentName")]) - if err != nil { - return nil, err - } - resp := e.srv.NewListAllExecutionsPager(resourceGroupNameParam, experimentNameParam, nil) - newListAllExecutionsPager = &resp - e.newListAllExecutionsPager.add(req, newListAllExecutionsPager) - server.PagerResponderInjectNextLinks(newListAllExecutionsPager, req, func(page *armchaos.ExperimentsClientListAllExecutionsResponse, createLink func() string) { - page.NextLink = to.Ptr(createLink()) - }) - } - resp, err := server.PagerResponderNext(newListAllExecutionsPager, req) - if err != nil { - return nil, err - } - if !contains([]int{http.StatusOK}, resp.StatusCode) { - e.newListAllExecutionsPager.remove(req) - return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} - } - if !server.PagerResponderMore(newListAllExecutionsPager) { - e.newListAllExecutionsPager.remove(req) - } - return resp, nil -} - func (e *ExperimentsServerTransport) dispatchBeginStart(req *http.Request) (*http.Response, error) { if e.srv.BeginStart == nil { return nil, &nonRetriableError{errors.New("fake for method BeginStart not implemented")} @@ -575,9 +455,9 @@ func (e *ExperimentsServerTransport) dispatchBeginStart(req *http.Request) (*htt return nil, err } - if !contains([]int{http.StatusAccepted}, resp.StatusCode) { + if !contains([]int{http.StatusOK, http.StatusAccepted, http.StatusNoContent}, resp.StatusCode) { e.beginStart.remove(req) - return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusAccepted", resp.StatusCode)} + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted, http.StatusNoContent", resp.StatusCode)} } if !server.PollerResponderMore(beginStart) { e.beginStart.remove(req) @@ -623,9 +503,9 @@ func (e *ExperimentsServerTransport) dispatchBeginUpdate(req *http.Request) (*ht return nil, err } - if !contains([]int{http.StatusAccepted}, resp.StatusCode) { + if !contains([]int{http.StatusOK, http.StatusAccepted}, resp.StatusCode) { e.beginUpdate.remove(req) - return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusAccepted", resp.StatusCode)} + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted", resp.StatusCode)} } if !server.PollerResponderMore(beginUpdate) { e.beginUpdate.remove(req) @@ -633,3 +513,9 @@ func (e *ExperimentsServerTransport) dispatchBeginUpdate(req *http.Request) (*ht return resp, nil } + +// set this to conditionally intercept incoming requests to ExperimentsServerTransport +var experimentsServerTransportInterceptor 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/chaos/armchaos/fake/internal.go b/sdk/resourcemanager/chaos/armchaos/fake/internal.go index 7d2f89ba4bb2..41e62ec29233 100644 --- a/sdk/resourcemanager/chaos/armchaos/fake/internal.go +++ b/sdk/resourcemanager/chaos/armchaos/fake/internal.go @@ -1,10 +1,6 @@ -//go:build go1.18 -// +build go1.18 - // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. -// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. package fake @@ -15,6 +11,11 @@ import ( "sync" ) +type result struct { + resp *http.Response + err error +} + type nonRetriableError struct { error } diff --git a/sdk/resourcemanager/chaos/armchaos/fake/operations_server.go b/sdk/resourcemanager/chaos/armchaos/fake/operations_server.go index fa65ac87d409..dc5306aa30d4 100644 --- a/sdk/resourcemanager/chaos/armchaos/fake/operations_server.go +++ b/sdk/resourcemanager/chaos/armchaos/fake/operations_server.go @@ -1,10 +1,6 @@ -//go:build go1.18 -// +build go1.18 - // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. -// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. package fake @@ -15,15 +11,15 @@ import ( "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" - "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/chaos/armchaos" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/chaos/armchaos/v2" "net/http" ) // OperationsServer is a fake server for instances of the armchaos.OperationsClient type. type OperationsServer struct { - // NewListAllPager is the fake for method OperationsClient.NewListAllPager + // NewListPager is the fake for method OperationsClient.NewListPager // HTTP status codes to indicate success: http.StatusOK - NewListAllPager func(options *armchaos.OperationsClientListAllOptions) (resp azfake.PagerResponder[armchaos.OperationsClientListAllResponse]) + NewListPager func(options *armchaos.OperationsClientListOptions) (resp azfake.PagerResponder[armchaos.OperationsClientListResponse]) } // NewOperationsServerTransport creates a new instance of OperationsServerTransport with the provided implementation. @@ -31,16 +27,16 @@ type OperationsServer struct { // azcore.ClientOptions.Transporter field in the client's constructor parameters. func NewOperationsServerTransport(srv *OperationsServer) *OperationsServerTransport { return &OperationsServerTransport{ - srv: srv, - newListAllPager: newTracker[azfake.PagerResponder[armchaos.OperationsClientListAllResponse]](), + srv: srv, + newListPager: newTracker[azfake.PagerResponder[armchaos.OperationsClientListResponse]](), } } // OperationsServerTransport connects instances of armchaos.OperationsClient to instances of OperationsServer. // Don't use this type directly, use NewOperationsServerTransport instead. type OperationsServerTransport struct { - srv *OperationsServer - newListAllPager *tracker[azfake.PagerResponder[armchaos.OperationsClientListAllResponse]] + srv *OperationsServer + newListPager *tracker[azfake.PagerResponder[armchaos.OperationsClientListResponse]] } // Do implements the policy.Transporter interface for OperationsServerTransport. @@ -51,46 +47,71 @@ func (o *OperationsServerTransport) Do(req *http.Request) (*http.Response, error return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} } - var resp *http.Response - var err error + return o.dispatchToMethodFake(req, method) +} - switch method { - case "OperationsClient.NewListAllPager": - resp, err = o.dispatchNewListAllPager(req) - default: - err = fmt.Errorf("unhandled API %s", method) - } +func (o *OperationsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result) + defer close(resultChan) - if err != nil { - return nil, err - } + go func() { + var intercepted bool + var res result + if operationsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = operationsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "OperationsClient.NewListPager": + res.resp, res.err = o.dispatchNewListPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } - return resp, nil + } + select { + case resultChan <- res: + case <-req.Context().Done(): + } + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } } -func (o *OperationsServerTransport) dispatchNewListAllPager(req *http.Request) (*http.Response, error) { - if o.srv.NewListAllPager == nil { - return nil, &nonRetriableError{errors.New("fake for method NewListAllPager not implemented")} +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")} } - newListAllPager := o.newListAllPager.get(req) - if newListAllPager == nil { - resp := o.srv.NewListAllPager(nil) - newListAllPager = &resp - o.newListAllPager.add(req, newListAllPager) - server.PagerResponderInjectNextLinks(newListAllPager, req, func(page *armchaos.OperationsClientListAllResponse, createLink func() string) { + 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 *armchaos.OperationsClientListResponse, createLink func() string) { page.NextLink = to.Ptr(createLink()) }) } - resp, err := server.PagerResponderNext(newListAllPager, req) + resp, err := server.PagerResponderNext(newListPager, req) if err != nil { return nil, err } if !contains([]int{http.StatusOK}, resp.StatusCode) { - o.newListAllPager.remove(req) + o.newListPager.remove(req) return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} } - if !server.PagerResponderMore(newListAllPager) { - o.newListAllPager.remove(req) + 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/chaos/armchaos/fake/operationstatuses_server.go b/sdk/resourcemanager/chaos/armchaos/fake/operationstatuses_server.go index 86d938265b0b..4c9112ec69c2 100644 --- a/sdk/resourcemanager/chaos/armchaos/fake/operationstatuses_server.go +++ b/sdk/resourcemanager/chaos/armchaos/fake/operationstatuses_server.go @@ -1,10 +1,6 @@ -//go:build go1.18 -// +build go1.18 - // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. -// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. package fake @@ -15,7 +11,7 @@ import ( azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" - "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/chaos/armchaos" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/chaos/armchaos/v2" "net/http" "net/url" "regexp" @@ -25,7 +21,7 @@ import ( type OperationStatusesServer struct { // Get is the fake for method OperationStatusesClient.Get // HTTP status codes to indicate success: http.StatusOK - Get func(ctx context.Context, location string, asyncOperationID string, options *armchaos.OperationStatusesClientGetOptions) (resp azfake.Responder[armchaos.OperationStatusesClientGetResponse], errResp azfake.ErrorResponder) + Get func(ctx context.Context, location string, operationID string, options *armchaos.OperationStatusesClientGetOptions) (resp azfake.Responder[armchaos.OperationStatusesClientGetResponse], errResp azfake.ErrorResponder) } // NewOperationStatusesServerTransport creates a new instance of OperationStatusesServerTransport with the provided implementation. @@ -49,28 +45,47 @@ func (o *OperationStatusesServerTransport) Do(req *http.Request) (*http.Response return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} } - var resp *http.Response - var err error + return o.dispatchToMethodFake(req, method) +} - switch method { - case "OperationStatusesClient.Get": - resp, err = o.dispatchGet(req) - default: - err = fmt.Errorf("unhandled API %s", method) - } +func (o *OperationStatusesServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result) + defer close(resultChan) - if err != nil { - return nil, err - } + go func() { + var intercepted bool + var res result + if operationStatusesServerTransportInterceptor != nil { + res.resp, res.err, intercepted = operationStatusesServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "OperationStatusesClient.Get": + res.resp, res.err = o.dispatchGet(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } - return resp, nil + } + select { + case resultChan <- res: + case <-req.Context().Done(): + } + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } } func (o *OperationStatusesServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { if o.srv.Get == nil { return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} } - const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Chaos/locations/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/operationStatuses/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Chaos/locations/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/operationStatuses/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` regex := regexp.MustCompile(regexStr) matches := regex.FindStringSubmatch(req.URL.EscapedPath()) if matches == nil || len(matches) < 3 { @@ -80,11 +95,11 @@ func (o *OperationStatusesServerTransport) dispatchGet(req *http.Request) (*http if err != nil { return nil, err } - asyncOperationIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("asyncOperationId")]) + operationIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("operationId")]) if err != nil { return nil, err } - respr, errRespr := o.srv.Get(req.Context(), locationParam, asyncOperationIDParam, nil) + respr, errRespr := o.srv.Get(req.Context(), locationParam, operationIDParam, nil) if respErr := server.GetError(errRespr, req); respErr != nil { return nil, respErr } @@ -92,9 +107,15 @@ func (o *OperationStatusesServerTransport) dispatchGet(req *http.Request) (*http 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).OperationStatus, req) + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).OperationStatusResult, req) if err != nil { return nil, err } return resp, nil } + +// set this to conditionally intercept incoming requests to OperationStatusesServerTransport +var operationStatusesServerTransportInterceptor 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/chaos/armchaos/fake/server_factory.go b/sdk/resourcemanager/chaos/armchaos/fake/server_factory.go index b2c30adf1bb3..daa29f62552f 100644 --- a/sdk/resourcemanager/chaos/armchaos/fake/server_factory.go +++ b/sdk/resourcemanager/chaos/armchaos/fake/server_factory.go @@ -1,10 +1,6 @@ -//go:build go1.18 -// +build go1.18 - // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. -// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. package fake @@ -19,13 +15,29 @@ import ( // ServerFactory is a fake server for instances of the armchaos.ClientFactory type. type ServerFactory struct { - CapabilitiesServer CapabilitiesServer - CapabilityTypesServer CapabilityTypesServer - ExperimentsServer ExperimentsServer + // CapabilitiesServer contains the fakes for client CapabilitiesClient + CapabilitiesServer CapabilitiesServer + + // CapabilityTypesServer contains the fakes for client CapabilityTypesClient + CapabilityTypesServer CapabilityTypesServer + + // ExperimentExecutionsServer contains the fakes for client ExperimentExecutionsClient + ExperimentExecutionsServer ExperimentExecutionsServer + + // ExperimentsServer contains the fakes for client ExperimentsClient + ExperimentsServer ExperimentsServer + + // OperationStatusesServer contains the fakes for client OperationStatusesClient OperationStatusesServer OperationStatusesServer - OperationsServer OperationsServer - TargetTypesServer TargetTypesServer - TargetsServer TargetsServer + + // OperationsServer contains the fakes for client OperationsClient + OperationsServer OperationsServer + + // TargetTypesServer contains the fakes for client TargetTypesClient + TargetTypesServer TargetTypesServer + + // TargetsServer contains the fakes for client TargetsClient + TargetsServer TargetsServer } // NewServerFactoryTransport creates a new instance of ServerFactoryTransport with the provided implementation. @@ -40,15 +52,16 @@ func NewServerFactoryTransport(srv *ServerFactory) *ServerFactoryTransport { // ServerFactoryTransport connects instances of armchaos.ClientFactory to instances of ServerFactory. // Don't use this type directly, use NewServerFactoryTransport instead. type ServerFactoryTransport struct { - srv *ServerFactory - trMu sync.Mutex - trCapabilitiesServer *CapabilitiesServerTransport - trCapabilityTypesServer *CapabilityTypesServerTransport - trExperimentsServer *ExperimentsServerTransport - trOperationStatusesServer *OperationStatusesServerTransport - trOperationsServer *OperationsServerTransport - trTargetTypesServer *TargetTypesServerTransport - trTargetsServer *TargetsServerTransport + srv *ServerFactory + trMu sync.Mutex + trCapabilitiesServer *CapabilitiesServerTransport + trCapabilityTypesServer *CapabilityTypesServerTransport + trExperimentExecutionsServer *ExperimentExecutionsServerTransport + trExperimentsServer *ExperimentsServerTransport + trOperationStatusesServer *OperationStatusesServerTransport + trOperationsServer *OperationsServerTransport + trTargetTypesServer *TargetTypesServerTransport + trTargetsServer *TargetsServerTransport } // Do implements the policy.Transporter interface for ServerFactoryTransport. @@ -72,6 +85,11 @@ func (s *ServerFactoryTransport) Do(req *http.Request) (*http.Response, error) { return NewCapabilityTypesServerTransport(&s.srv.CapabilityTypesServer) }) resp, err = s.trCapabilityTypesServer.Do(req) + case "ExperimentExecutionsClient": + initServer(s, &s.trExperimentExecutionsServer, func() *ExperimentExecutionsServerTransport { + return NewExperimentExecutionsServerTransport(&s.srv.ExperimentExecutionsServer) + }) + resp, err = s.trExperimentExecutionsServer.Do(req) case "ExperimentsClient": initServer(s, &s.trExperimentsServer, func() *ExperimentsServerTransport { return NewExperimentsServerTransport(&s.srv.ExperimentsServer) }) resp, err = s.trExperimentsServer.Do(req) diff --git a/sdk/resourcemanager/chaos/armchaos/fake/targets_server.go b/sdk/resourcemanager/chaos/armchaos/fake/targets_server.go index d2045d013f23..71df77f915fd 100644 --- a/sdk/resourcemanager/chaos/armchaos/fake/targets_server.go +++ b/sdk/resourcemanager/chaos/armchaos/fake/targets_server.go @@ -1,10 +1,6 @@ -//go:build go1.18 -// +build go1.18 - // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. -// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. package fake @@ -16,7 +12,7 @@ import ( "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" - "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/chaos/armchaos" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/chaos/armchaos/v2" "net/http" "net/url" "regexp" @@ -25,8 +21,8 @@ import ( // TargetsServer is a fake server for instances of the armchaos.TargetsClient type. type TargetsServer struct { // CreateOrUpdate is the fake for method TargetsClient.CreateOrUpdate - // HTTP status codes to indicate success: http.StatusOK - CreateOrUpdate func(ctx context.Context, resourceGroupName string, parentProviderNamespace string, parentResourceType string, parentResourceName string, targetName string, target armchaos.Target, options *armchaos.TargetsClientCreateOrUpdateOptions) (resp azfake.Responder[armchaos.TargetsClientCreateOrUpdateResponse], errResp azfake.ErrorResponder) + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + CreateOrUpdate func(ctx context.Context, resourceGroupName string, parentProviderNamespace string, parentResourceType string, parentResourceName string, targetName string, resource armchaos.Target, options *armchaos.TargetsClientCreateOrUpdateOptions) (resp azfake.Responder[armchaos.TargetsClientCreateOrUpdateResponse], errResp azfake.ErrorResponder) // Delete is the fake for method TargetsClient.Delete // HTTP status codes to indicate success: http.StatusOK, http.StatusNoContent @@ -66,27 +62,46 @@ func (t *TargetsServerTransport) Do(req *http.Request) (*http.Response, error) { return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} } - var resp *http.Response - var err error + return t.dispatchToMethodFake(req, method) +} - switch method { - case "TargetsClient.CreateOrUpdate": - resp, err = t.dispatchCreateOrUpdate(req) - case "TargetsClient.Delete": - resp, err = t.dispatchDelete(req) - case "TargetsClient.Get": - resp, err = t.dispatchGet(req) - case "TargetsClient.NewListPager": - resp, err = t.dispatchNewListPager(req) - default: - err = fmt.Errorf("unhandled API %s", method) - } +func (t *TargetsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result) + defer close(resultChan) - if err != nil { - return nil, err - } + go func() { + var intercepted bool + var res result + if targetsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = targetsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "TargetsClient.CreateOrUpdate": + res.resp, res.err = t.dispatchCreateOrUpdate(req) + case "TargetsClient.Delete": + res.resp, res.err = t.dispatchDelete(req) + case "TargetsClient.Get": + res.resp, res.err = t.dispatchGet(req) + case "TargetsClient.NewListPager": + res.resp, res.err = t.dispatchNewListPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } - return resp, nil + } + select { + case resultChan <- res: + case <-req.Context().Done(): + } + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } } func (t *TargetsServerTransport) dispatchCreateOrUpdate(req *http.Request) (*http.Response, error) { @@ -128,8 +143,8 @@ func (t *TargetsServerTransport) dispatchCreateOrUpdate(req *http.Request) (*htt 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)} + 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).Target, req) if err != nil { @@ -288,3 +303,9 @@ func (t *TargetsServerTransport) dispatchNewListPager(req *http.Request) (*http. } return resp, nil } + +// set this to conditionally intercept incoming requests to TargetsServerTransport +var targetsServerTransportInterceptor 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/chaos/armchaos/fake/targettypes_server.go b/sdk/resourcemanager/chaos/armchaos/fake/targettypes_server.go index d3a7428a0477..0bef0d182e66 100644 --- a/sdk/resourcemanager/chaos/armchaos/fake/targettypes_server.go +++ b/sdk/resourcemanager/chaos/armchaos/fake/targettypes_server.go @@ -1,10 +1,6 @@ -//go:build go1.18 -// +build go1.18 - // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. -// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. package fake @@ -16,7 +12,7 @@ import ( "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" - "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/chaos/armchaos" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/chaos/armchaos/v2" "net/http" "net/url" "regexp" @@ -26,11 +22,11 @@ import ( type TargetTypesServer struct { // Get is the fake for method TargetTypesClient.Get // HTTP status codes to indicate success: http.StatusOK - Get func(ctx context.Context, locationName string, targetTypeName string, options *armchaos.TargetTypesClientGetOptions) (resp azfake.Responder[armchaos.TargetTypesClientGetResponse], errResp azfake.ErrorResponder) + Get func(ctx context.Context, location string, targetTypeName string, options *armchaos.TargetTypesClientGetOptions) (resp azfake.Responder[armchaos.TargetTypesClientGetResponse], errResp azfake.ErrorResponder) // NewListPager is the fake for method TargetTypesClient.NewListPager // HTTP status codes to indicate success: http.StatusOK - NewListPager func(locationName string, options *armchaos.TargetTypesClientListOptions) (resp azfake.PagerResponder[armchaos.TargetTypesClientListResponse]) + NewListPager func(location string, options *armchaos.TargetTypesClientListOptions) (resp azfake.PagerResponder[armchaos.TargetTypesClientListResponse]) } // NewTargetTypesServerTransport creates a new instance of TargetTypesServerTransport with the provided implementation. @@ -58,36 +54,55 @@ func (t *TargetTypesServerTransport) Do(req *http.Request) (*http.Response, erro return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} } - var resp *http.Response - var err error + return t.dispatchToMethodFake(req, method) +} - switch method { - case "TargetTypesClient.Get": - resp, err = t.dispatchGet(req) - case "TargetTypesClient.NewListPager": - resp, err = t.dispatchNewListPager(req) - default: - err = fmt.Errorf("unhandled API %s", method) - } +func (t *TargetTypesServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result) + defer close(resultChan) - if err != nil { - return nil, err - } + go func() { + var intercepted bool + var res result + if targetTypesServerTransportInterceptor != nil { + res.resp, res.err, intercepted = targetTypesServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "TargetTypesClient.Get": + res.resp, res.err = t.dispatchGet(req) + case "TargetTypesClient.NewListPager": + res.resp, res.err = t.dispatchNewListPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } - return resp, nil + } + select { + case resultChan <- res: + case <-req.Context().Done(): + } + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } } func (t *TargetTypesServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { if t.srv.Get == nil { return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} } - const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Chaos/locations/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/targetTypes/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Chaos/locations/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/targetTypes/(?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) } - locationNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("locationName")]) + locationParam, err := url.PathUnescape(matches[regex.SubexpIndex("location")]) if err != nil { return nil, err } @@ -95,7 +110,7 @@ func (t *TargetTypesServerTransport) dispatchGet(req *http.Request) (*http.Respo if err != nil { return nil, err } - respr, errRespr := t.srv.Get(req.Context(), locationNameParam, targetTypeNameParam, nil) + respr, errRespr := t.srv.Get(req.Context(), locationParam, targetTypeNameParam, nil) if respErr := server.GetError(errRespr, req); respErr != nil { return nil, respErr } @@ -116,14 +131,14 @@ func (t *TargetTypesServerTransport) dispatchNewListPager(req *http.Request) (*h } newListPager := t.newListPager.get(req) if newListPager == nil { - const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Chaos/locations/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/targetTypes` + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Chaos/locations/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/targetTypes` regex := regexp.MustCompile(regexStr) matches := regex.FindStringSubmatch(req.URL.EscapedPath()) if matches == nil || len(matches) < 2 { return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) } qp := req.URL.Query() - locationNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("locationName")]) + locationParam, err := url.PathUnescape(matches[regex.SubexpIndex("location")]) if err != nil { return nil, err } @@ -138,7 +153,7 @@ func (t *TargetTypesServerTransport) dispatchNewListPager(req *http.Request) (*h ContinuationToken: continuationTokenParam, } } - resp := t.srv.NewListPager(locationNameParam, options) + resp := t.srv.NewListPager(locationParam, options) newListPager = &resp t.newListPager.add(req, newListPager) server.PagerResponderInjectNextLinks(newListPager, req, func(page *armchaos.TargetTypesClientListResponse, createLink func() string) { @@ -158,3 +173,9 @@ func (t *TargetTypesServerTransport) dispatchNewListPager(req *http.Request) (*h } return resp, nil } + +// set this to conditionally intercept incoming requests to TargetTypesServerTransport +var targetTypesServerTransportInterceptor 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/chaos/armchaos/fake/time_rfc3339.go b/sdk/resourcemanager/chaos/armchaos/fake/time_rfc3339.go index 81f308b0d343..87ee11e83b32 100644 --- a/sdk/resourcemanager/chaos/armchaos/fake/time_rfc3339.go +++ b/sdk/resourcemanager/chaos/armchaos/fake/time_rfc3339.go @@ -1,10 +1,6 @@ -//go:build go1.18 -// +build go1.18 - // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. -// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. package fake @@ -60,6 +56,9 @@ func (t *dateTimeRFC3339) UnmarshalJSON(data []byte) error { } 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 diff --git a/sdk/resourcemanager/chaos/armchaos/go.mod b/sdk/resourcemanager/chaos/armchaos/go.mod index 33ee3f5921ed..dbb606233e31 100644 --- a/sdk/resourcemanager/chaos/armchaos/go.mod +++ b/sdk/resourcemanager/chaos/armchaos/go.mod @@ -1,4 +1,4 @@ -module github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/chaos/armchaos +module github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/chaos/armchaos/v2 go 1.23.0 diff --git a/sdk/resourcemanager/chaos/armchaos/interfaces.go b/sdk/resourcemanager/chaos/armchaos/interfaces.go index e75b88834683..c509305b4a7e 100644 --- a/sdk/resourcemanager/chaos/armchaos/interfaces.go +++ b/sdk/resourcemanager/chaos/armchaos/interfaces.go @@ -1,10 +1,6 @@ -//go:build go1.18 -// +build go1.18 - // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. -// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. package armchaos diff --git a/sdk/resourcemanager/chaos/armchaos/models.go b/sdk/resourcemanager/chaos/armchaos/models.go index 20da634461d9..97bedade5f21 100644 --- a/sdk/resourcemanager/chaos/armchaos/models.go +++ b/sdk/resourcemanager/chaos/armchaos/models.go @@ -1,10 +1,6 @@ -//go:build go1.18 -// +build go1.18 - // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. -// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. package armchaos @@ -48,16 +44,16 @@ type BranchStatus struct { // Capability - Model that represents a Capability resource. type Capability struct { - // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} - ID *string + // The properties of a capability resource. + Properties *CapabilityProperties - // READ-ONLY; The name of the resource + // READ-ONLY; String that represents a Capability resource name. Name *string - // READ-ONLY; The properties of a capability resource. - Properties *CapabilityProperties + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string - // READ-ONLY; The standard system metadata of a resource type. + // 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" @@ -66,11 +62,11 @@ type Capability struct { // CapabilityListResult - Model that represents a list of Capability resources and a link for pagination. type CapabilityListResult struct { - // READ-ONLY; URL to retrieve the next page of Capability resources. - NextLink *string - - // READ-ONLY; List of Capability resources. + // REQUIRED; The Capability items on this page Value []*Capability + + // The link to the next page of items + NextLink *string } // CapabilityProperties - Model that represents the Capability properties model. @@ -93,19 +89,16 @@ type CapabilityProperties struct { // CapabilityType - Model that represents a Capability Type resource. type CapabilityType struct { - // Location of the Capability Type resource. - Location *string - - // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} - ID *string + // The properties of the capability type resource. + Properties *CapabilityTypeProperties - // READ-ONLY; The name of the resource + // READ-ONLY; String that represents a Capability Type resource name. Name *string - // READ-ONLY; The properties of the capability type resource. - Properties *CapabilityTypeProperties + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string - // READ-ONLY; The system metadata properties of the capability type resource. + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. SystemData *SystemData // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" @@ -114,24 +107,21 @@ type CapabilityType struct { // CapabilityTypeListResult - Model that represents a list of Capability Type resources and a link for pagination. type CapabilityTypeListResult struct { - // READ-ONLY; URL to retrieve the next page of Capability Type resources. - NextLink *string - - // READ-ONLY; List of Capability Type resources. + // REQUIRED; The CapabilityType items on this page Value []*CapabilityType + + // The link to the next page of items + NextLink *string } // CapabilityTypeProperties - Model that represents the Capability Type properties model. type CapabilityTypeProperties struct { - // Control plane actions necessary to execute capability type. + // READ-ONLY; Control plane actions necessary to execute capability type. AzureRbacActions []*string - // Data plane actions necessary to execute capability type. + // READ-ONLY; Data plane actions necessary to execute capability type. AzureRbacDataActions []*string - // Runtime properties of this Capability Type. - RuntimeProperties *CapabilityTypePropertiesRuntimeProperties - // READ-ONLY; Localized string of the description. Description *string @@ -147,6 +137,12 @@ type CapabilityTypeProperties struct { // READ-ONLY; String of the Publisher that this Capability Type extends. Publisher *string + // READ-ONLY; Required Azure Role Definition Ids to execute capability type. + RequiredAzureRoleDefinitionIDs []*string + + // READ-ONLY; Runtime properties of this Capability Type. + RuntimeProperties *CapabilityTypePropertiesRuntimeProperties + // READ-ONLY; String of the Target Type that this Capability Type extends. TargetType *string @@ -174,8 +170,9 @@ type ContinuousAction struct { // REQUIRED; String that represents a selector. SelectorID *string - // REQUIRED; Enum that discriminates between action models. - Type *string + // CONSTANT; Enum that discriminates between action models. + // Field has constant value ExperimentActionTypeContinuous, any specified value is ignored. + Type *ExperimentActionType } // GetExperimentAction implements the ExperimentActionClassification interface for type ContinuousAction. @@ -194,8 +191,9 @@ type DelayAction struct { // REQUIRED; String that represents a Capability URN. Name *string - // REQUIRED; Enum that discriminates between action models. - Type *string + // CONSTANT; Enum that discriminates between action models. + // Field has constant value ExperimentActionTypeDelay, any specified value is ignored. + Type *ExperimentActionType } // GetExperimentAction implements the ExperimentActionClassification interface for type DelayAction. @@ -217,8 +215,9 @@ type DiscreteAction struct { // REQUIRED; String that represents a selector. SelectorID *string - // REQUIRED; Enum that discriminates between action models. - Type *string + // CONSTANT; Enum that discriminates between action models. + // Field has constant value ExperimentActionTypeDiscrete, any specified value is ignored. + Type *ExperimentActionType } // GetExperimentAction implements the ExperimentActionClassification interface for type DiscreteAction. @@ -232,12 +231,15 @@ func (d *DiscreteAction) GetExperimentAction() *ExperimentAction { // ErrorAdditionalInfo - The resource management error additional info. type ErrorAdditionalInfo struct { // READ-ONLY; The additional info. - Info any + Info *ErrorAdditionalInfoInfo // READ-ONLY; The additional info type. Type *string } +type ErrorAdditionalInfoInfo struct { +} + // ErrorDetail - The error detail. type ErrorDetail struct { // READ-ONLY; The error additional info. @@ -256,13 +258,6 @@ type ErrorDetail struct { Target *string } -// ErrorResponse - Common error response for all Azure Resource Manager APIs to return error details for failed operations. -// (This also follows the OData error response format.). -type ErrorResponse struct { - // The error object. - Error *ErrorDetail -} - // Experiment - Model that represents a Experiment resource. type Experiment struct { // REQUIRED; The geo-location where the resource lives @@ -271,8 +266,11 @@ type Experiment struct { // REQUIRED; The properties of the experiment resource. Properties *ExperimentProperties - // The identity of the experiment resource. - Identity *ResourceIdentity + // READ-ONLY; String that represents a Experiment resource name. + Name *string + + // The managed service identities assigned to this resource. + Identity *ManagedServiceIdentity // Resource tags. Tags map[string]*string @@ -280,10 +278,7 @@ type Experiment struct { // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} ID *string - // READ-ONLY; The name of the resource - Name *string - - // READ-ONLY; The system metadata of the experiment resource. + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. SystemData *SystemData // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" @@ -295,8 +290,8 @@ type ExperimentAction struct { // REQUIRED; String that represents a Capability URN. Name *string - // REQUIRED; Enum that discriminates between action models. - Type *string + // REQUIRED; Chaos experiment action discriminator type + Type *ExperimentActionType } // GetExperimentAction implements the ExperimentActionClassification interface for type ExperimentAction. @@ -316,13 +311,16 @@ type ExperimentExecution struct { // The properties of experiment execution status. Properties *ExperimentExecutionProperties - // READ-ONLY; String of the fully qualified resource ID. + // READ-ONLY; GUID that represents a Experiment execution detail. + Name *string + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} ID *string - // READ-ONLY; String of the resource name. - Name *string + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData - // READ-ONLY; String of the resource type. + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" Type *string } @@ -398,11 +396,11 @@ type ExperimentExecutionDetailsPropertiesRunInformation struct { // ExperimentExecutionListResult - Model that represents a list of Experiment executions and a link for pagination. type ExperimentExecutionListResult struct { - // READ-ONLY; URL to retrieve the next page of Experiment executions. - NextLink *string - - // READ-ONLY; List of Experiment executions. + // REQUIRED; The ExperimentExecution items on this page Value []*ExperimentExecution + + // The link to the next page of items + NextLink *string } // ExperimentExecutionProperties - Model that represents the execution properties of an Experiment. @@ -419,11 +417,11 @@ type ExperimentExecutionProperties struct { // ExperimentListResult - Model that represents a list of Experiment resources and a link for pagination. type ExperimentListResult struct { - // READ-ONLY; URL to retrieve the next page of Experiment resources. - NextLink *string - - // READ-ONLY; List of Experiment resources. + // REQUIRED; The Experiment items on this page Value []*Experiment + + // The link to the next page of items + NextLink *string } // ExperimentProperties - Model that represents the Experiment properties model. @@ -449,10 +447,10 @@ type ExperimentStep struct { // ExperimentUpdate - Describes an experiment update. type ExperimentUpdate struct { - // The identity of the experiment resource. - Identity *ResourceIdentity + // The managed service identities assigned to this resource. + Identity *ManagedServiceIdentity - // The tags of the experiment resource. + // Resource tags. Tags map[string]*string } @@ -465,16 +463,32 @@ type KeyValuePair struct { Value *string } +// ManagedServiceIdentity - Managed service identity (system assigned and/or user assigned identities) +type ManagedServiceIdentity struct { + // REQUIRED; The type of managed identity assigned to this resource. + Type *ManagedServiceIdentityType + + // The identities assigned to this resource by the user. + 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 +} + // 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. + // READ-ONLY; Extensible 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. + // READ-ONLY; Whether the operation applies to data-plane. This is "true" for data-plane operations and "false" for Azure + // Resource Manager/control-plane operations. IsDataAction *bool // READ-ONLY; The name of the operation, as per Resource-Based Access Control (RBAC). Examples: "Microsoft.Compute/virtualMachines/write", @@ -486,7 +500,7 @@ type Operation struct { Origin *Origin } -// OperationDisplay - Localized display information for this particular operation. +// OperationDisplay - Localized display information for and operation. type OperationDisplay struct { // READ-ONLY; The short, localized friendly description of the operation; suitable for tool tips and detailed views. Description *string @@ -507,61 +521,41 @@ type OperationDisplay struct { // 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 + // REQUIRED; The Operation items on this page Value []*Operation + + // The link to the next page of items + NextLink *string } -// OperationStatus - The status of operation. -type OperationStatus struct { +// OperationStatusResult - The current status of an async operation. +type OperationStatusResult struct { + // REQUIRED; Operation status. + Status *string + // The end time of the operation. - EndTime *string + EndTime *time.Time - // The error object. + // If present, details of the operation error. Error *ErrorDetail - // The operation Id. - ID *string - - // The operation name. - Name *string - - // The start time of the operation. - StartTime *string - - // The status of the operation. - Status *string -} - -// Resource - Common fields that are returned in the response for all Azure Resource Manager resources -type Resource struct { - // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + // Fully qualified ID for the async operation. ID *string - // READ-ONLY; The name of the resource + // Name of the async operation. Name *string - // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" - Type *string -} - -// ResourceIdentity - The identity of a resource. -type ResourceIdentity struct { - // REQUIRED; String of the resource identity type. - Type *ResourceIdentityType + // The operations list. + Operations []*OperationStatusResult - // The list of user identities associated with the Experiment. The user identity dictionary key references will be ARM resource - // ids in the form: - // '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}'. - UserAssignedIdentities map[string]*UserAssignedIdentity + // Percent of the operation that is complete. + PercentComplete *float64 - // READ-ONLY; GUID that represents the principal ID of this resource identity. - PrincipalID *string + // The start time of the operation. + StartTime *time.Time - // READ-ONLY; GUID that represents the tenant ID of this resource identity. - TenantID *string + // READ-ONLY; Fully qualified ID of the resource against which the original async operation was started. + ResourceID *string } // StepStatus - Model that represents the a list of branches and branch statuses. @@ -605,16 +599,16 @@ type Target struct { // REQUIRED; The properties of the target resource. Properties map[string]any - // Location of the target resource. + // READ-ONLY; String that represents a Target resource name. + Name *string + + // Azure resource location. Location *string // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} ID *string - // READ-ONLY; The name of the resource - Name *string - - // READ-ONLY; The system metadata of the target resource. + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. SystemData *SystemData // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" @@ -623,7 +617,7 @@ type Target struct { // TargetFilter - Model that represents available filter types that can be applied to a targets list. type TargetFilter struct { - // REQUIRED; Enum that discriminates between filter types. Currently only Simple type is supported. + // REQUIRED; Chaos target filter discriminator type Type *FilterType } @@ -632,11 +626,11 @@ func (t *TargetFilter) GetTargetFilter() *TargetFilter { return t } // TargetListResult - Model that represents a list of Target resources and a link for pagination. type TargetListResult struct { - // READ-ONLY; URL to retrieve the next page of Target resources. - NextLink *string - - // READ-ONLY; List of Target resources. + // REQUIRED; The Target items on this page Value []*Target + + // The link to the next page of items + NextLink *string } // TargetListSelector - Model that represents a list selector. @@ -647,12 +641,10 @@ type TargetListSelector struct { // REQUIRED; List of Target references. Targets []*TargetReference - // REQUIRED; Enum of the selector type. + // CONSTANT; Enum of the selector type. + // Field has constant value SelectorTypeList, any specified value is ignored. Type *SelectorType - // OPTIONAL; Contains additional key/value pairs not defined in the schema. - AdditionalProperties map[string]any - // Model that represents available filter types that can be applied to a targets list. Filter TargetFilterClassification } @@ -660,10 +652,9 @@ type TargetListSelector struct { // GetTargetSelector implements the TargetSelectorClassification interface for type TargetListSelector. func (t *TargetListSelector) GetTargetSelector() *TargetSelector { return &TargetSelector{ - AdditionalProperties: t.AdditionalProperties, - Filter: t.Filter, - ID: t.ID, - Type: t.Type, + Filter: t.Filter, + ID: t.ID, + Type: t.Type, } } @@ -678,12 +669,10 @@ type TargetQuerySelector struct { // REQUIRED; Subscription id list to scope resource query. SubscriptionIDs []*string - // REQUIRED; Enum of the selector type. + // CONSTANT; Enum of the selector type. + // Field has constant value SelectorTypeQuery, any specified value is ignored. Type *SelectorType - // OPTIONAL; Contains additional key/value pairs not defined in the schema. - AdditionalProperties map[string]any - // Model that represents available filter types that can be applied to a targets list. Filter TargetFilterClassification } @@ -691,10 +680,9 @@ type TargetQuerySelector struct { // GetTargetSelector implements the TargetSelectorClassification interface for type TargetQuerySelector. func (t *TargetQuerySelector) GetTargetSelector() *TargetSelector { return &TargetSelector{ - AdditionalProperties: t.AdditionalProperties, - Filter: t.Filter, - ID: t.ID, - Type: t.Type, + Filter: t.Filter, + ID: t.ID, + Type: t.Type, } } @@ -712,12 +700,9 @@ type TargetSelector struct { // REQUIRED; String of the selector ID. ID *string - // REQUIRED; Enum of the selector type. + // REQUIRED; Chaos target selector discriminator type Type *SelectorType - // OPTIONAL; Contains additional key/value pairs not defined in the schema. - AdditionalProperties map[string]any - // Model that represents available filter types that can be applied to a targets list. Filter TargetFilterClassification } @@ -727,7 +712,8 @@ func (t *TargetSelector) GetTargetSelector() *TargetSelector { return t } // TargetSimpleFilter - Model that represents a simple target filter. type TargetSimpleFilter struct { - // REQUIRED; Enum that discriminates between filter types. Currently only Simple type is supported. + // CONSTANT; Enum that discriminates between filter types. Currently only `Simple` type is supported. + // Field has constant value FilterTypeSimple, any specified value is ignored. Type *FilterType // Model that represents the Simple filter parameters. @@ -752,16 +738,13 @@ type TargetType struct { // REQUIRED; The properties of the target type resource. Properties *TargetTypeProperties - // Location of the Target Type resource. - Location *string + // READ-ONLY; String that represents a Target Type resource name. + Name *string // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} ID *string - // READ-ONLY; The name of the resource - Name *string - - // READ-ONLY; The system metadata properties of the target type resource. + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. SystemData *SystemData // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" @@ -770,11 +753,11 @@ type TargetType struct { // TargetTypeListResult - Model that represents a list of Target Type resources and a link for pagination. type TargetTypeListResult struct { - // READ-ONLY; URL to retrieve the next page of Target Type resources. - NextLink *string - - // READ-ONLY; List of Target Type resources. + // REQUIRED; The TargetType items on this page Value []*TargetType + + // The link to the next page of items + NextLink *string } // TargetTypeProperties - Model that represents the base Target Type properties model. @@ -792,25 +775,6 @@ type TargetTypeProperties struct { ResourceTypes []*string } -// TrackedResource - The resource model definition for an Azure Resource Manager tracked top level resource which has 'tags' -// and a 'location' -type TrackedResource struct { - // REQUIRED; The geo-location where the resource lives - Location *string - - // Resource tags. - Tags map[string]*string - - // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} - ID *string - - // READ-ONLY; The name of the resource - Name *string - - // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" - Type *string -} - // UserAssignedIdentity - User assigned identity properties type UserAssignedIdentity struct { // READ-ONLY; The client ID of the assigned identity. diff --git a/sdk/resourcemanager/chaos/armchaos/models_serde.go b/sdk/resourcemanager/chaos/armchaos/models_serde.go index 81388afb9ed1..89af45d18a82 100644 --- a/sdk/resourcemanager/chaos/armchaos/models_serde.go +++ b/sdk/resourcemanager/chaos/armchaos/models_serde.go @@ -1,10 +1,6 @@ -//go:build go1.18 -// +build go1.18 - // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. -// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. package armchaos @@ -222,7 +218,6 @@ func (c *CapabilityProperties) UnmarshalJSON(data []byte) error { func (c CapabilityType) MarshalJSON() ([]byte, error) { objectMap := make(map[string]any) populate(objectMap, "id", c.ID) - populate(objectMap, "location", c.Location) populate(objectMap, "name", c.Name) populate(objectMap, "properties", c.Properties) populate(objectMap, "systemData", c.SystemData) @@ -242,9 +237,6 @@ func (c *CapabilityType) UnmarshalJSON(data []byte) error { case "id": err = unpopulate(val, "ID", &c.ID) delete(rawMsg, key) - case "location": - err = unpopulate(val, "Location", &c.Location) - delete(rawMsg, key) case "name": err = unpopulate(val, "Name", &c.Name) delete(rawMsg, key) @@ -306,6 +298,7 @@ func (c CapabilityTypeProperties) MarshalJSON() ([]byte, error) { populate(objectMap, "kind", c.Kind) populate(objectMap, "parametersSchema", c.ParametersSchema) populate(objectMap, "publisher", c.Publisher) + populate(objectMap, "requiredAzureRoleDefinitionIds", c.RequiredAzureRoleDefinitionIDs) populate(objectMap, "runtimeProperties", c.RuntimeProperties) populate(objectMap, "targetType", c.TargetType) populate(objectMap, "urn", c.Urn) @@ -342,6 +335,9 @@ func (c *CapabilityTypeProperties) UnmarshalJSON(data []byte) error { case "publisher": err = unpopulate(val, "Publisher", &c.Publisher) delete(rawMsg, key) + case "requiredAzureRoleDefinitionIds": + err = unpopulate(val, "RequiredAzureRoleDefinitionIDs", &c.RequiredAzureRoleDefinitionIDs) + delete(rawMsg, key) case "runtimeProperties": err = unpopulate(val, "RuntimeProperties", &c.RuntimeProperties) delete(rawMsg, key) @@ -393,7 +389,7 @@ func (c ContinuousAction) MarshalJSON() ([]byte, error) { populate(objectMap, "name", c.Name) populate(objectMap, "parameters", c.Parameters) populate(objectMap, "selectorId", c.SelectorID) - objectMap["type"] = "continuous" + objectMap["type"] = ExperimentActionTypeContinuous return json.Marshal(objectMap) } @@ -434,7 +430,7 @@ func (d DelayAction) MarshalJSON() ([]byte, error) { objectMap := make(map[string]any) populate(objectMap, "duration", d.Duration) populate(objectMap, "name", d.Name) - objectMap["type"] = "delay" + objectMap["type"] = ExperimentActionTypeDelay return json.Marshal(objectMap) } @@ -470,7 +466,7 @@ func (d DiscreteAction) MarshalJSON() ([]byte, error) { populate(objectMap, "name", d.Name) populate(objectMap, "parameters", d.Parameters) populate(objectMap, "selectorId", d.SelectorID) - objectMap["type"] = "discrete" + objectMap["type"] = ExperimentActionTypeDiscrete return json.Marshal(objectMap) } @@ -506,7 +502,7 @@ func (d *DiscreteAction) UnmarshalJSON(data []byte) error { // MarshalJSON implements the json.Marshaller interface for type ErrorAdditionalInfo. func (e ErrorAdditionalInfo) MarshalJSON() ([]byte, error) { objectMap := make(map[string]any) - populateAny(objectMap, "info", e.Info) + populate(objectMap, "info", e.Info) populate(objectMap, "type", e.Type) return json.Marshal(objectMap) } @@ -577,33 +573,6 @@ func (e *ErrorDetail) UnmarshalJSON(data []byte) error { return nil } -// MarshalJSON implements the json.Marshaller interface for type ErrorResponse. -func (e ErrorResponse) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]any) - populate(objectMap, "error", e.Error) - return json.Marshal(objectMap) -} - -// UnmarshalJSON implements the json.Unmarshaller interface for type ErrorResponse. -func (e *ErrorResponse) UnmarshalJSON(data []byte) error { - var rawMsg map[string]json.RawMessage - if err := json.Unmarshal(data, &rawMsg); err != nil { - return fmt.Errorf("unmarshalling type %T: %v", e, err) - } - for key, val := range rawMsg { - var err error - switch key { - case "error": - err = unpopulate(val, "Error", &e.Error) - delete(rawMsg, key) - } - if err != nil { - return fmt.Errorf("unmarshalling type %T: %v", e, err) - } - } - return nil -} - // MarshalJSON implements the json.Marshaller interface for type Experiment. func (e Experiment) MarshalJSON() ([]byte, error) { objectMap := make(map[string]any) @@ -663,7 +632,7 @@ func (e *Experiment) UnmarshalJSON(data []byte) error { func (e ExperimentAction) MarshalJSON() ([]byte, error) { objectMap := make(map[string]any) populate(objectMap, "name", e.Name) - objectMap["type"] = e.Type + populate(objectMap, "type", e.Type) return json.Marshal(objectMap) } @@ -727,6 +696,7 @@ func (e ExperimentExecution) MarshalJSON() ([]byte, error) { 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) } @@ -749,6 +719,9 @@ func (e *ExperimentExecution) UnmarshalJSON(data []byte) error { 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) @@ -1172,6 +1145,45 @@ func (k *KeyValuePair) UnmarshalJSON(data []byte) error { 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 Operation. func (o Operation) MarshalJSON() ([]byte, error) { objectMap := make(map[string]any) @@ -1285,20 +1297,23 @@ func (o *OperationListResult) UnmarshalJSON(data []byte) error { return nil } -// MarshalJSON implements the json.Marshaller interface for type OperationStatus. -func (o OperationStatus) MarshalJSON() ([]byte, error) { +// MarshalJSON implements the json.Marshaller interface for type OperationStatusResult. +func (o OperationStatusResult) MarshalJSON() ([]byte, error) { objectMap := make(map[string]any) - populate(objectMap, "endTime", o.EndTime) + populateDateTimeRFC3339(objectMap, "endTime", o.EndTime) populate(objectMap, "error", o.Error) populate(objectMap, "id", o.ID) populate(objectMap, "name", o.Name) - populate(objectMap, "startTime", o.StartTime) + populate(objectMap, "operations", o.Operations) + populate(objectMap, "percentComplete", o.PercentComplete) + populate(objectMap, "resourceId", o.ResourceID) + populateDateTimeRFC3339(objectMap, "startTime", o.StartTime) populate(objectMap, "status", o.Status) return json.Marshal(objectMap) } -// UnmarshalJSON implements the json.Unmarshaller interface for type OperationStatus. -func (o *OperationStatus) UnmarshalJSON(data []byte) error { +// UnmarshalJSON implements the json.Unmarshaller interface for type OperationStatusResult. +func (o *OperationStatusResult) 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) @@ -1307,7 +1322,7 @@ func (o *OperationStatus) UnmarshalJSON(data []byte) error { var err error switch key { case "endTime": - err = unpopulate(val, "EndTime", &o.EndTime) + err = unpopulateDateTimeRFC3339(val, "EndTime", &o.EndTime) delete(rawMsg, key) case "error": err = unpopulate(val, "Error", &o.Error) @@ -1318,8 +1333,17 @@ func (o *OperationStatus) UnmarshalJSON(data []byte) error { case "name": err = unpopulate(val, "Name", &o.Name) delete(rawMsg, key) + case "operations": + err = unpopulate(val, "Operations", &o.Operations) + delete(rawMsg, key) + case "percentComplete": + err = unpopulate(val, "PercentComplete", &o.PercentComplete) + delete(rawMsg, key) + case "resourceId": + err = unpopulate(val, "ResourceID", &o.ResourceID) + delete(rawMsg, key) case "startTime": - err = unpopulate(val, "StartTime", &o.StartTime) + err = unpopulateDateTimeRFC3339(val, "StartTime", &o.StartTime) delete(rawMsg, key) case "status": err = unpopulate(val, "Status", &o.Status) @@ -1332,80 +1356,6 @@ func (o *OperationStatus) UnmarshalJSON(data []byte) error { return nil } -// MarshalJSON implements the json.Marshaller interface for type Resource. -func (r Resource) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]any) - populate(objectMap, "id", r.ID) - populate(objectMap, "name", r.Name) - populate(objectMap, "type", r.Type) - return json.Marshal(objectMap) -} - -// UnmarshalJSON implements the json.Unmarshaller interface for type Resource. -func (r *Resource) UnmarshalJSON(data []byte) error { - 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 "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 ResourceIdentity. -func (r ResourceIdentity) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]any) - populate(objectMap, "principalId", r.PrincipalID) - populate(objectMap, "tenantId", r.TenantID) - populate(objectMap, "type", r.Type) - populate(objectMap, "userAssignedIdentities", r.UserAssignedIdentities) - return json.Marshal(objectMap) -} - -// UnmarshalJSON implements the json.Unmarshaller interface for type ResourceIdentity. -func (r *ResourceIdentity) 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 "principalId": - err = unpopulate(val, "PrincipalID", &r.PrincipalID) - delete(rawMsg, key) - case "tenantId": - err = unpopulate(val, "TenantID", &r.TenantID) - delete(rawMsg, key) - case "type": - err = unpopulate(val, "Type", &r.Type) - delete(rawMsg, key) - case "userAssignedIdentities": - err = unpopulate(val, "UserAssignedIdentities", &r.UserAssignedIdentities) - 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 StepStatus. func (s StepStatus) MarshalJSON() ([]byte, error) { objectMap := make(map[string]any) @@ -1542,7 +1492,7 @@ func (t *Target) UnmarshalJSON(data []byte) error { // MarshalJSON implements the json.Marshaller interface for type TargetFilter. func (t TargetFilter) MarshalJSON() ([]byte, error) { objectMap := make(map[string]any) - objectMap["type"] = t.Type + populate(objectMap, "type", t.Type) return json.Marshal(objectMap) } @@ -1604,11 +1554,6 @@ func (t TargetListSelector) MarshalJSON() ([]byte, error) { populate(objectMap, "id", t.ID) populate(objectMap, "targets", t.Targets) objectMap["type"] = SelectorTypeList - if t.AdditionalProperties != nil { - for key, val := range t.AdditionalProperties { - objectMap[key] = val - } - } return json.Marshal(objectMap) } @@ -1633,16 +1578,6 @@ func (t *TargetListSelector) UnmarshalJSON(data []byte) error { case "type": err = unpopulate(val, "Type", &t.Type) delete(rawMsg, key) - default: - if t.AdditionalProperties == nil { - t.AdditionalProperties = map[string]any{} - } - if val != nil { - var aux any - err = json.Unmarshal(val, &aux) - t.AdditionalProperties[key] = aux - } - delete(rawMsg, key) } if err != nil { return fmt.Errorf("unmarshalling type %T: %v", t, err) @@ -1659,11 +1594,6 @@ func (t TargetQuerySelector) MarshalJSON() ([]byte, error) { populate(objectMap, "queryString", t.QueryString) populate(objectMap, "subscriptionIds", t.SubscriptionIDs) objectMap["type"] = SelectorTypeQuery - if t.AdditionalProperties != nil { - for key, val := range t.AdditionalProperties { - objectMap[key] = val - } - } return json.Marshal(objectMap) } @@ -1691,16 +1621,6 @@ func (t *TargetQuerySelector) UnmarshalJSON(data []byte) error { case "type": err = unpopulate(val, "Type", &t.Type) delete(rawMsg, key) - default: - if t.AdditionalProperties == nil { - t.AdditionalProperties = map[string]any{} - } - if val != nil { - var aux any - err = json.Unmarshal(val, &aux) - t.AdditionalProperties[key] = aux - } - delete(rawMsg, key) } if err != nil { return fmt.Errorf("unmarshalling type %T: %v", t, err) @@ -1745,12 +1665,7 @@ func (t TargetSelector) MarshalJSON() ([]byte, error) { objectMap := make(map[string]any) populate(objectMap, "filter", t.Filter) populate(objectMap, "id", t.ID) - objectMap["type"] = t.Type - if t.AdditionalProperties != nil { - for key, val := range t.AdditionalProperties { - objectMap[key] = val - } - } + populate(objectMap, "type", t.Type) return json.Marshal(objectMap) } @@ -1772,16 +1687,6 @@ func (t *TargetSelector) UnmarshalJSON(data []byte) error { case "type": err = unpopulate(val, "Type", &t.Type) delete(rawMsg, key) - default: - if t.AdditionalProperties == nil { - t.AdditionalProperties = map[string]any{} - } - if val != nil { - var aux any - err = json.Unmarshal(val, &aux) - t.AdditionalProperties[key] = aux - } - delete(rawMsg, key) } if err != nil { return fmt.Errorf("unmarshalling type %T: %v", t, err) @@ -1852,7 +1757,6 @@ func (t *TargetSimpleFilterParameters) UnmarshalJSON(data []byte) error { func (t TargetType) MarshalJSON() ([]byte, error) { objectMap := make(map[string]any) populate(objectMap, "id", t.ID) - populate(objectMap, "location", t.Location) populate(objectMap, "name", t.Name) populate(objectMap, "properties", t.Properties) populate(objectMap, "systemData", t.SystemData) @@ -1872,9 +1776,6 @@ func (t *TargetType) UnmarshalJSON(data []byte) error { case "id": err = unpopulate(val, "ID", &t.ID) delete(rawMsg, key) - case "location": - err = unpopulate(val, "Location", &t.Location) - delete(rawMsg, key) case "name": err = unpopulate(val, "Name", &t.Name) delete(rawMsg, key) @@ -1965,49 +1866,6 @@ func (t *TargetTypeProperties) UnmarshalJSON(data []byte) error { return nil } -// MarshalJSON implements the json.Marshaller interface for type TrackedResource. -func (t TrackedResource) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]any) - populate(objectMap, "id", t.ID) - populate(objectMap, "location", t.Location) - populate(objectMap, "name", t.Name) - populate(objectMap, "tags", t.Tags) - populate(objectMap, "type", t.Type) - return json.Marshal(objectMap) -} - -// UnmarshalJSON implements the json.Unmarshaller interface for type TrackedResource. -func (t *TrackedResource) UnmarshalJSON(data []byte) error { - var rawMsg map[string]json.RawMessage - if err := json.Unmarshal(data, &rawMsg); err != nil { - return fmt.Errorf("unmarshalling type %T: %v", t, err) - } - for key, val := range rawMsg { - var err error - switch key { - case "id": - err = unpopulate(val, "ID", &t.ID) - delete(rawMsg, key) - case "location": - err = unpopulate(val, "Location", &t.Location) - delete(rawMsg, key) - case "name": - err = unpopulate(val, "Name", &t.Name) - delete(rawMsg, key) - case "tags": - err = unpopulate(val, "Tags", &t.Tags) - delete(rawMsg, key) - case "type": - err = unpopulate(val, "Type", &t.Type) - delete(rawMsg, key) - } - if err != nil { - return fmt.Errorf("unmarshalling type %T: %v", t, err) - } - } - return nil -} - // MarshalJSON implements the json.Marshaller interface for type UserAssignedIdentity. func (u UserAssignedIdentity) MarshalJSON() ([]byte, error) { objectMap := make(map[string]any) @@ -2049,16 +1907,6 @@ func populate(m map[string]any, k string, v any) { } } -func populateAny(m map[string]any, k string, v any) { - if v == nil { - return - } else if azcore.IsNullValue(v) { - m[k] = nil - } else { - m[k] = v - } -} - func unpopulate(data json.RawMessage, fn string, v any) error { if data == nil || string(data) == "null" { return nil diff --git a/sdk/resourcemanager/chaos/armchaos/operations_client.go b/sdk/resourcemanager/chaos/armchaos/operations_client.go index 09f52bccdddc..b0cca90240f4 100644 --- a/sdk/resourcemanager/chaos/armchaos/operations_client.go +++ b/sdk/resourcemanager/chaos/armchaos/operations_client.go @@ -1,10 +1,6 @@ -//go:build go1.18 -// +build go1.18 - // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. -// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. package armchaos @@ -37,52 +33,52 @@ func NewOperationsClient(credential azcore.TokenCredential, options *arm.ClientO return client, nil } -// NewListAllPager - Get a list all available Operations. +// NewListPager - List the operations for the provider // -// Generated from API version 2024-01-01 -// - options - OperationsClientListAllOptions contains the optional parameters for the OperationsClient.NewListAllPager method. -func (client *OperationsClient) NewListAllPager(options *OperationsClientListAllOptions) *runtime.Pager[OperationsClientListAllResponse] { - return runtime.NewPager(runtime.PagingHandler[OperationsClientListAllResponse]{ - More: func(page OperationsClientListAllResponse) bool { +// Generated from API version 2025-01-01 +// - options - OperationsClientListOptions contains the optional parameters for the OperationsClient.NewListPager method. +func (client *OperationsClient) NewListPager(options *OperationsClientListOptions) *runtime.Pager[OperationsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[OperationsClientListResponse]{ + More: func(page OperationsClientListResponse) bool { return page.NextLink != nil && len(*page.NextLink) > 0 }, - Fetcher: func(ctx context.Context, page *OperationsClientListAllResponse) (OperationsClientListAllResponse, error) { - ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "OperationsClient.NewListAllPager") + 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.listAllCreateRequest(ctx, options) + return client.listCreateRequest(ctx, options) }, nil) if err != nil { - return OperationsClientListAllResponse{}, err + return OperationsClientListResponse{}, err } - return client.listAllHandleResponse(resp) + return client.listHandleResponse(resp) }, Tracer: client.internal.Tracer(), }) } -// listAllCreateRequest creates the ListAll request. -func (client *OperationsClient) listAllCreateRequest(ctx context.Context, options *OperationsClientListAllOptions) (*policy.Request, error) { +// listCreateRequest creates the List request. +func (client *OperationsClient) listCreateRequest(ctx context.Context, _ *OperationsClientListOptions) (*policy.Request, error) { urlPath := "/providers/Microsoft.Chaos/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", "2024-01-01") + reqQP.Set("api-version", "2025-01-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil } -// listAllHandleResponse handles the ListAll response. -func (client *OperationsClient) listAllHandleResponse(resp *http.Response) (OperationsClientListAllResponse, error) { - result := OperationsClientListAllResponse{} +// 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 OperationsClientListAllResponse{}, err + return OperationsClientListResponse{}, err } return result, nil } diff --git a/sdk/resourcemanager/chaos/armchaos/operations_client_example_test.go b/sdk/resourcemanager/chaos/armchaos/operations_client_example_test.go new file mode 100644 index 000000000000..d83048c64504 --- /dev/null +++ b/sdk/resourcemanager/chaos/armchaos/operations_client_example_test.go @@ -0,0 +1,55 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armchaos_test + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azidentity" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/chaos/armchaos/v2" + "log" +) + +// Generated from example definition: 2025-01-01/Operations_List.json +func ExampleOperationsClient_NewListPager() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armchaos.NewClientFactory("", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + pager := clientFactory.NewOperationsClient().NewListPager(nil) + for pager.More() { + page, err := pager.NextPage(ctx) + if err != nil { + log.Fatalf("failed to advance page: %v", err) + } + for _, v := range page.Value { + // You could use page here. We use blank identifier for just demo purposes. + _ = v + } + // If the HTTP response code is 200 as defined in example definition, your page structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // page = armchaos.OperationsClientListResponse{ + // OperationListResult: armchaos.OperationListResult{ + // NextLink: to.Ptr("https://management.azure.com/providers/Microsoft.Chaos/operations?continuationToken=myContinuationToken&api-version=2024-11-01-preview"), + // Value: []*armchaos.Operation{ + // { + // Name: to.Ptr("Microsoft.Chaos/experiments/read"), + // Display: &armchaos.OperationDisplay{ + // Provider: to.Ptr("Microsoft Chaos"), + // Resource: to.Ptr("Chaos Experiment"), + // Operation: to.Ptr("Gets all Chaos Experiments."), + // Description: to.Ptr("Gets all Chaos Experiments in a resource group."), + // }, + // IsDataAction: to.Ptr(false), + // Origin: to.Ptr(armchaos.OriginUserSystem), + // }, + // }, + // }, + // } + } +} diff --git a/sdk/resourcemanager/chaos/armchaos/operations_live_test.go b/sdk/resourcemanager/chaos/armchaos/operations_live_test.go index bfdd647bf766..cc9420d59ea5 100644 --- a/sdk/resourcemanager/chaos/armchaos/operations_live_test.go +++ b/sdk/resourcemanager/chaos/armchaos/operations_live_test.go @@ -14,7 +14,7 @@ import ( "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/internal/recording" - "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/chaos/armchaos" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/chaos/armchaos/v2" "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/internal/v3/testutil" "github.com/stretchr/testify/suite" ) diff --git a/sdk/resourcemanager/chaos/armchaos/operationstatuses_client.go b/sdk/resourcemanager/chaos/armchaos/operationstatuses_client.go index f5e384736644..db468c36237e 100644 --- a/sdk/resourcemanager/chaos/armchaos/operationstatuses_client.go +++ b/sdk/resourcemanager/chaos/armchaos/operationstatuses_client.go @@ -1,10 +1,6 @@ -//go:build go1.18 -// +build go1.18 - // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. -// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. package armchaos @@ -20,7 +16,7 @@ import ( "strings" ) -// OperationStatusesClient contains the methods for the OperationStatuses group. +// OperationStatusesClient - Chaos Studio async operation status resource operations. // Don't use this type directly, use NewOperationStatusesClient() instead. type OperationStatusesClient struct { internal *arm.Client @@ -28,7 +24,7 @@ type OperationStatusesClient struct { } // NewOperationStatusesClient creates a new instance of OperationStatusesClient with the specified values. -// - subscriptionID - GUID that represents an Azure subscription ID. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. // - credential - used to authorize requests. Usually a credential from azidentity. // - options - pass nil to accept the default values. func NewOperationStatusesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*OperationStatusesClient, error) { @@ -43,20 +39,20 @@ func NewOperationStatusesClient(subscriptionID string, credential azcore.TokenCr return client, nil } -// Get - Get the status of a long running azure asynchronous operation. +// Get - Returns the current status of an async operation. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2024-01-01 -// - location - The name of the Azure region. -// - asyncOperationID - The operation Id. +// Generated from API version 2025-01-01 +// - location - The location name. +// - operationID - The ID of an ongoing async operation. // - options - OperationStatusesClientGetOptions contains the optional parameters for the OperationStatusesClient.Get method. -func (client *OperationStatusesClient) Get(ctx context.Context, location string, asyncOperationID string, options *OperationStatusesClientGetOptions) (OperationStatusesClientGetResponse, error) { +func (client *OperationStatusesClient) Get(ctx context.Context, location string, operationID string, options *OperationStatusesClientGetOptions) (OperationStatusesClientGetResponse, error) { var err error const operationName = "OperationStatusesClient.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, location, asyncOperationID, options) + req, err := client.getCreateRequest(ctx, location, operationID, options) if err != nil { return OperationStatusesClientGetResponse{}, err } @@ -73,26 +69,26 @@ func (client *OperationStatusesClient) Get(ctx context.Context, location string, } // getCreateRequest creates the Get request. -func (client *OperationStatusesClient) getCreateRequest(ctx context.Context, location string, asyncOperationID string, options *OperationStatusesClientGetOptions) (*policy.Request, error) { - urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Chaos/locations/{location}/operationStatuses/{asyncOperationId}" +func (client *OperationStatusesClient) getCreateRequest(ctx context.Context, location string, operationID string, _ *OperationStatusesClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Chaos/locations/{location}/operationStatuses/{operationId}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) if location == "" { return nil, errors.New("parameter location cannot be empty") } urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location)) - if asyncOperationID == "" { - return nil, errors.New("parameter asyncOperationID cannot be empty") + if operationID == "" { + return nil, errors.New("parameter operationID cannot be empty") } - urlPath = strings.ReplaceAll(urlPath, "{asyncOperationId}", url.PathEscape(asyncOperationID)) - if client.subscriptionID == "" { - return nil, errors.New("parameter client.subscriptionID cannot be empty") - } - urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + urlPath = strings.ReplaceAll(urlPath, "{operationId}", url.PathEscape(operationID)) req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) if err != nil { return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2024-01-01") + reqQP.Set("api-version", "2025-01-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -101,7 +97,7 @@ func (client *OperationStatusesClient) getCreateRequest(ctx context.Context, loc // getHandleResponse handles the Get response. func (client *OperationStatusesClient) getHandleResponse(resp *http.Response) (OperationStatusesClientGetResponse, error) { result := OperationStatusesClientGetResponse{} - if err := runtime.UnmarshalAsJSON(resp, &result.OperationStatus); err != nil { + if err := runtime.UnmarshalAsJSON(resp, &result.OperationStatusResult); err != nil { return OperationStatusesClientGetResponse{}, err } return result, nil diff --git a/sdk/resourcemanager/chaos/armchaos/operationstatuses_client_example_test.go b/sdk/resourcemanager/chaos/armchaos/operationstatuses_client_example_test.go index e72b29a01520..f9dbd3095bf6 100644 --- a/sdk/resourcemanager/chaos/armchaos/operationstatuses_client_example_test.go +++ b/sdk/resourcemanager/chaos/armchaos/operationstatuses_client_example_test.go @@ -1,45 +1,40 @@ -//go:build go1.18 -// +build go1.18 - // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. -// DO NOT EDIT. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. package armchaos_test import ( "context" - "log" - "github.com/Azure/azure-sdk-for-go/sdk/azidentity" - "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/chaos/armchaos" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/chaos/armchaos/v2" + "log" ) -// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/e4009d2f8d3bf0271757e522c7d1c1997e193d44/specification/chaos/resource-manager/Microsoft.Chaos/stable/2024-01-01/examples/GetOperationStatus.json +// Generated from example definition: 2025-01-01/OperationStatuses_Get.json func ExampleOperationStatusesClient_Get() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() - clientFactory, err := armchaos.NewClientFactory("", cred, nil) + clientFactory, err := armchaos.NewClientFactory("e25c0d12-0335-4fec-8ef8-3b4f9a10649e", cred, nil) if err != nil { log.Fatalf("failed to create client: %v", err) } - res, err := clientFactory.NewOperationStatusesClient().Get(ctx, "West US", "713192d7-503f-477a-9cfe-4efc3ee2bd11", nil) + res, err := clientFactory.NewOperationStatusesClient().Get(ctx, "westus2", "4bdadd97-207c-4de8-9bba-08339ae099c7", nil) if err != nil { log.Fatalf("failed to finish the request: %v", err) } // You could use response here. We use blank identifier for just demo purposes. _ = res // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. - // res.OperationStatus = armchaos.OperationStatus{ - // Name: to.Ptr("713192d7-503f-477a-9cfe-4efc3ee2bd11"), - // EndTime: to.Ptr("2017-01-01T16:13:13.933Z"), - // ID: to.Ptr("/subscriptions/613192d7-503f-477a-9cfe-4efc3ee2bd60/locations/westus/operationStatuses/713192d7-503f-477a-9cfe-4efc3ee2bd11"), - // StartTime: to.Ptr("2017-01-01T13:13:13.933Z"), - // Status: to.Ptr("Succeeded"), + // res = armchaos.OperationStatusesClientGetResponse{ + // OperationStatusResult: &armchaos.OperationStatusResult{ + // ID: to.Ptr("/subscriptions/e25c0d12-0335-4fec-8ef8-3b4f9a10649e/providers/Microsoft.Chaos/locations/westus2/operationStatuses/4bdadd97-207c-4de8-9bba-08339ae099c7"), + // Name: to.Ptr("4bdadd97-207c-4de8-9bba-08339ae099c7"), + // StartTime: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2024-11-14T21:52:52.2552574Z"); return t}()), + // Status: to.Ptr("Creating"), + // }, // } } diff --git a/sdk/resourcemanager/chaos/armchaos/options.go b/sdk/resourcemanager/chaos/armchaos/options.go index 088c8b736b47..077801ac9aa1 100644 --- a/sdk/resourcemanager/chaos/armchaos/options.go +++ b/sdk/resourcemanager/chaos/armchaos/options.go @@ -1,10 +1,6 @@ -//go:build go1.18 -// +build go1.18 - // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. -// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. package armchaos @@ -40,58 +36,60 @@ type CapabilityTypesClientListOptions struct { ContinuationToken *string } +// ExperimentExecutionsClientGetExecutionDetailsOptions contains the optional parameters for the ExperimentExecutionsClient.GetExecutionDetails +// method. +type ExperimentExecutionsClientGetExecutionDetailsOptions struct { + // placeholder for future optional parameters +} + +// ExperimentExecutionsClientGetExecutionOptions contains the optional parameters for the ExperimentExecutionsClient.GetExecution +// method. +type ExperimentExecutionsClientGetExecutionOptions struct { + // placeholder for future optional parameters +} + +// ExperimentExecutionsClientListAllExecutionsOptions contains the optional parameters for the ExperimentExecutionsClient.NewListAllExecutionsPager +// method. +type ExperimentExecutionsClientListAllExecutionsOptions struct { + // placeholder for future optional parameters +} + // ExperimentsClientBeginCancelOptions contains the optional parameters for the ExperimentsClient.BeginCancel method. type ExperimentsClientBeginCancelOptions struct { - // Resumes the LRO from the provided token. + // Resumes the long-running operation from the provided token. ResumeToken string } // ExperimentsClientBeginCreateOrUpdateOptions contains the optional parameters for the ExperimentsClient.BeginCreateOrUpdate // method. type ExperimentsClientBeginCreateOrUpdateOptions struct { - // Resumes the LRO from the provided token. + // Resumes the long-running operation from the provided token. ResumeToken string } // ExperimentsClientBeginDeleteOptions contains the optional parameters for the ExperimentsClient.BeginDelete method. type ExperimentsClientBeginDeleteOptions struct { - // Resumes the LRO from the provided token. + // Resumes the long-running operation from the provided token. ResumeToken string } // ExperimentsClientBeginStartOptions contains the optional parameters for the ExperimentsClient.BeginStart method. type ExperimentsClientBeginStartOptions struct { - // Resumes the LRO from the provided token. + // Resumes the long-running operation from the provided token. ResumeToken string } // ExperimentsClientBeginUpdateOptions contains the optional parameters for the ExperimentsClient.BeginUpdate method. type ExperimentsClientBeginUpdateOptions struct { - // Resumes the LRO from the provided token. + // Resumes the long-running operation from the provided token. ResumeToken string } -// ExperimentsClientExecutionDetailsOptions contains the optional parameters for the ExperimentsClient.ExecutionDetails method. -type ExperimentsClientExecutionDetailsOptions struct { - // placeholder for future optional parameters -} - -// ExperimentsClientGetExecutionOptions contains the optional parameters for the ExperimentsClient.GetExecution method. -type ExperimentsClientGetExecutionOptions struct { - // placeholder for future optional parameters -} - // ExperimentsClientGetOptions contains the optional parameters for the ExperimentsClient.Get method. type ExperimentsClientGetOptions struct { // placeholder for future optional parameters } -// ExperimentsClientListAllExecutionsOptions contains the optional parameters for the ExperimentsClient.NewListAllExecutionsPager -// method. -type ExperimentsClientListAllExecutionsOptions struct { - // placeholder for future optional parameters -} - // ExperimentsClientListAllOptions contains the optional parameters for the ExperimentsClient.NewListAllPager method. type ExperimentsClientListAllOptions struct { // String that sets the continuation token. @@ -117,8 +115,8 @@ type OperationStatusesClientGetOptions struct { // placeholder for future optional parameters } -// OperationsClientListAllOptions contains the optional parameters for the OperationsClient.NewListAllPager method. -type OperationsClientListAllOptions struct { +// OperationsClientListOptions contains the optional parameters for the OperationsClient.NewListPager method. +type OperationsClientListOptions struct { // placeholder for future optional parameters } diff --git a/sdk/resourcemanager/chaos/armchaos/polymorphic_helpers.go b/sdk/resourcemanager/chaos/armchaos/polymorphic_helpers.go index ebf835864e47..3e998574aca5 100644 --- a/sdk/resourcemanager/chaos/armchaos/polymorphic_helpers.go +++ b/sdk/resourcemanager/chaos/armchaos/polymorphic_helpers.go @@ -1,10 +1,6 @@ -//go:build go1.18 -// +build go1.18 - // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. -// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. package armchaos @@ -20,11 +16,11 @@ func unmarshalExperimentActionClassification(rawMsg json.RawMessage) (Experiment } var b ExperimentActionClassification switch m["type"] { - case "continuous": + case string(ExperimentActionTypeContinuous): b = &ContinuousAction{} - case "delay": + case string(ExperimentActionTypeDelay): b = &DelayAction{} - case "discrete": + case string(ExperimentActionTypeDiscrete): b = &DiscreteAction{} default: b = &ExperimentAction{} diff --git a/sdk/resourcemanager/chaos/armchaos/responses.go b/sdk/resourcemanager/chaos/armchaos/responses.go index 7f27a717922c..d208610a4b71 100644 --- a/sdk/resourcemanager/chaos/armchaos/responses.go +++ b/sdk/resourcemanager/chaos/armchaos/responses.go @@ -1,10 +1,6 @@ -//go:build go1.18 -// +build go1.18 - // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. -// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. package armchaos @@ -43,6 +39,24 @@ type CapabilityTypesClientListResponse struct { CapabilityTypeListResult } +// ExperimentExecutionsClientGetExecutionDetailsResponse contains the response from method ExperimentExecutionsClient.GetExecutionDetails. +type ExperimentExecutionsClientGetExecutionDetailsResponse struct { + // Model that represents the execution details of an Experiment. + ExperimentExecutionDetails +} + +// ExperimentExecutionsClientGetExecutionResponse contains the response from method ExperimentExecutionsClient.GetExecution. +type ExperimentExecutionsClientGetExecutionResponse struct { + // Model that represents the execution of a Experiment. + ExperimentExecution +} + +// ExperimentExecutionsClientListAllExecutionsResponse contains the response from method ExperimentExecutionsClient.NewListAllExecutionsPager. +type ExperimentExecutionsClientListAllExecutionsResponse struct { + // Model that represents a list of Experiment executions and a link for pagination. + ExperimentExecutionListResult +} + // ExperimentsClientCancelResponse contains the response from method ExperimentsClient.BeginCancel. type ExperimentsClientCancelResponse struct { // placeholder for future response values @@ -59,30 +73,12 @@ type ExperimentsClientDeleteResponse struct { // placeholder for future response values } -// ExperimentsClientExecutionDetailsResponse contains the response from method ExperimentsClient.ExecutionDetails. -type ExperimentsClientExecutionDetailsResponse struct { - // Model that represents the execution details of an Experiment. - ExperimentExecutionDetails -} - -// ExperimentsClientGetExecutionResponse contains the response from method ExperimentsClient.GetExecution. -type ExperimentsClientGetExecutionResponse struct { - // Model that represents the execution of a Experiment. - ExperimentExecution -} - // ExperimentsClientGetResponse contains the response from method ExperimentsClient.Get. type ExperimentsClientGetResponse struct { // Model that represents a Experiment resource. Experiment } -// ExperimentsClientListAllExecutionsResponse contains the response from method ExperimentsClient.NewListAllExecutionsPager. -type ExperimentsClientListAllExecutionsResponse struct { - // Model that represents a list of Experiment executions and a link for pagination. - ExperimentExecutionListResult -} - // ExperimentsClientListAllResponse contains the response from method ExperimentsClient.NewListAllPager. type ExperimentsClientListAllResponse struct { // Model that represents a list of Experiment resources and a link for pagination. @@ -108,12 +104,12 @@ type ExperimentsClientUpdateResponse struct { // OperationStatusesClientGetResponse contains the response from method OperationStatusesClient.Get. type OperationStatusesClientGetResponse struct { - // The status of operation. - OperationStatus + // The current status of an async operation. + OperationStatusResult } -// OperationsClientListAllResponse contains the response from method OperationsClient.NewListAllPager. -type OperationsClientListAllResponse struct { +// 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 } diff --git a/sdk/resourcemanager/chaos/armchaos/targets_client.go b/sdk/resourcemanager/chaos/armchaos/targets_client.go index 9254b1b2c863..6b30e4c8cdb5 100644 --- a/sdk/resourcemanager/chaos/armchaos/targets_client.go +++ b/sdk/resourcemanager/chaos/armchaos/targets_client.go @@ -1,10 +1,6 @@ -//go:build go1.18 -// +build go1.18 - // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. -// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. package armchaos @@ -28,7 +24,7 @@ type TargetsClient struct { } // NewTargetsClient creates a new instance of TargetsClient with the specified values. -// - subscriptionID - GUID that represents an Azure subscription ID. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. // - credential - used to authorize requests. Usually a credential from azidentity. // - options - pass nil to accept the default values. func NewTargetsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*TargetsClient, error) { @@ -46,21 +42,21 @@ func NewTargetsClient(subscriptionID string, credential azcore.TokenCredential, // CreateOrUpdate - Create or update a Target resource that extends a tracked regional resource. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2024-01-01 -// - resourceGroupName - String that represents an Azure resource group. -// - parentProviderNamespace - String that represents a resource provider namespace. -// - parentResourceType - String that represents a resource type. -// - parentResourceName - String that represents a resource name. +// Generated from API version 2025-01-01 +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - parentProviderNamespace - The parent resource provider namespace. +// - parentResourceType - The parent resource type. +// - parentResourceName - The parent resource name. // - targetName - String that represents a Target resource name. -// - target - Target resource to be created or updated. +// - resource - Target resource to be created or updated. // - options - TargetsClientCreateOrUpdateOptions contains the optional parameters for the TargetsClient.CreateOrUpdate method. -func (client *TargetsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, parentProviderNamespace string, parentResourceType string, parentResourceName string, targetName string, target Target, options *TargetsClientCreateOrUpdateOptions) (TargetsClientCreateOrUpdateResponse, error) { +func (client *TargetsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, parentProviderNamespace string, parentResourceType string, parentResourceName string, targetName string, resource Target, options *TargetsClientCreateOrUpdateOptions) (TargetsClientCreateOrUpdateResponse, error) { var err error const operationName = "TargetsClient.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, parentProviderNamespace, parentResourceType, parentResourceName, targetName, target, options) + req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, parentProviderNamespace, parentResourceType, parentResourceName, targetName, resource, options) if err != nil { return TargetsClientCreateOrUpdateResponse{}, err } @@ -68,7 +64,7 @@ func (client *TargetsClient) CreateOrUpdate(ctx context.Context, resourceGroupNa if err != nil { return TargetsClientCreateOrUpdateResponse{}, err } - if !runtime.HasStatusCode(httpResp, http.StatusOK) { + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { err = runtime.NewResponseError(httpResp) return TargetsClientCreateOrUpdateResponse{}, err } @@ -77,7 +73,7 @@ func (client *TargetsClient) CreateOrUpdate(ctx context.Context, resourceGroupNa } // createOrUpdateCreateRequest creates the CreateOrUpdate request. -func (client *TargetsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, parentProviderNamespace string, parentResourceType string, parentResourceName string, targetName string, target Target, options *TargetsClientCreateOrUpdateOptions) (*policy.Request, error) { +func (client *TargetsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, parentProviderNamespace string, parentResourceType string, parentResourceName string, targetName string, resource Target, _ *TargetsClientCreateOrUpdateOptions) (*policy.Request, error) { urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{parentProviderNamespace}/{parentResourceType}/{parentResourceName}/providers/Microsoft.Chaos/targets/{targetName}" if client.subscriptionID == "" { return nil, errors.New("parameter client.subscriptionID cannot be empty") @@ -108,10 +104,11 @@ func (client *TargetsClient) createOrUpdateCreateRequest(ctx context.Context, re return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2024-01-01") + reqQP.Set("api-version", "2025-01-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} - if err := runtime.MarshalAsJSON(req, target); err != nil { + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, resource); err != nil { return nil, err } return req, nil @@ -129,11 +126,11 @@ func (client *TargetsClient) createOrUpdateHandleResponse(resp *http.Response) ( // Delete - Delete a Target resource that extends a tracked regional resource. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2024-01-01 -// - resourceGroupName - String that represents an Azure resource group. -// - parentProviderNamespace - String that represents a resource provider namespace. -// - parentResourceType - String that represents a resource type. -// - parentResourceName - String that represents a resource name. +// Generated from API version 2025-01-01 +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - parentProviderNamespace - The parent resource provider namespace. +// - parentResourceType - The parent resource type. +// - parentResourceName - The parent resource name. // - targetName - String that represents a Target resource name. // - options - TargetsClientDeleteOptions contains the optional parameters for the TargetsClient.Delete method. func (client *TargetsClient) Delete(ctx context.Context, resourceGroupName string, parentProviderNamespace string, parentResourceType string, parentResourceName string, targetName string, options *TargetsClientDeleteOptions) (TargetsClientDeleteResponse, error) { @@ -158,7 +155,7 @@ func (client *TargetsClient) Delete(ctx context.Context, resourceGroupName strin } // deleteCreateRequest creates the Delete request. -func (client *TargetsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, parentProviderNamespace string, parentResourceType string, parentResourceName string, targetName string, options *TargetsClientDeleteOptions) (*policy.Request, error) { +func (client *TargetsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, parentProviderNamespace string, parentResourceType string, parentResourceName string, targetName string, _ *TargetsClientDeleteOptions) (*policy.Request, error) { urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{parentProviderNamespace}/{parentResourceType}/{parentResourceName}/providers/Microsoft.Chaos/targets/{targetName}" if client.subscriptionID == "" { return nil, errors.New("parameter client.subscriptionID cannot be empty") @@ -189,7 +186,7 @@ func (client *TargetsClient) deleteCreateRequest(ctx context.Context, resourceGr return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2024-01-01") + reqQP.Set("api-version", "2025-01-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -198,11 +195,11 @@ func (client *TargetsClient) deleteCreateRequest(ctx context.Context, resourceGr // Get - Get a Target resource that extends a tracked regional resource. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2024-01-01 -// - resourceGroupName - String that represents an Azure resource group. -// - parentProviderNamespace - String that represents a resource provider namespace. -// - parentResourceType - String that represents a resource type. -// - parentResourceName - String that represents a resource name. +// Generated from API version 2025-01-01 +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - parentProviderNamespace - The parent resource provider namespace. +// - parentResourceType - The parent resource type. +// - parentResourceName - The parent resource name. // - targetName - String that represents a Target resource name. // - options - TargetsClientGetOptions contains the optional parameters for the TargetsClient.Get method. func (client *TargetsClient) Get(ctx context.Context, resourceGroupName string, parentProviderNamespace string, parentResourceType string, parentResourceName string, targetName string, options *TargetsClientGetOptions) (TargetsClientGetResponse, error) { @@ -228,7 +225,7 @@ func (client *TargetsClient) Get(ctx context.Context, resourceGroupName string, } // getCreateRequest creates the Get request. -func (client *TargetsClient) getCreateRequest(ctx context.Context, resourceGroupName string, parentProviderNamespace string, parentResourceType string, parentResourceName string, targetName string, options *TargetsClientGetOptions) (*policy.Request, error) { +func (client *TargetsClient) getCreateRequest(ctx context.Context, resourceGroupName string, parentProviderNamespace string, parentResourceType string, parentResourceName string, targetName string, _ *TargetsClientGetOptions) (*policy.Request, error) { urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{parentProviderNamespace}/{parentResourceType}/{parentResourceName}/providers/Microsoft.Chaos/targets/{targetName}" if client.subscriptionID == "" { return nil, errors.New("parameter client.subscriptionID cannot be empty") @@ -259,7 +256,7 @@ func (client *TargetsClient) getCreateRequest(ctx context.Context, resourceGroup return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2024-01-01") + reqQP.Set("api-version", "2025-01-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -276,11 +273,11 @@ func (client *TargetsClient) getHandleResponse(resp *http.Response) (TargetsClie // NewListPager - Get a list of Target resources that extend a tracked regional resource. // -// Generated from API version 2024-01-01 -// - resourceGroupName - String that represents an Azure resource group. -// - parentProviderNamespace - String that represents a resource provider namespace. -// - parentResourceType - String that represents a resource type. -// - parentResourceName - String that represents a resource name. +// Generated from API version 2025-01-01 +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - parentProviderNamespace - The parent resource provider namespace. +// - parentResourceType - The parent resource type. +// - parentResourceName - The parent resource name. // - options - TargetsClientListOptions contains the optional parameters for the TargetsClient.NewListPager method. func (client *TargetsClient) NewListPager(resourceGroupName string, parentProviderNamespace string, parentResourceType string, parentResourceName string, options *TargetsClientListOptions) *runtime.Pager[TargetsClientListResponse] { return runtime.NewPager(runtime.PagingHandler[TargetsClientListResponse]{ @@ -333,7 +330,7 @@ func (client *TargetsClient) listCreateRequest(ctx context.Context, resourceGrou return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2024-01-01") + reqQP.Set("api-version", "2025-01-01") if options != nil && options.ContinuationToken != nil { reqQP.Set("continuationToken", *options.ContinuationToken) } diff --git a/sdk/resourcemanager/chaos/armchaos/targets_client_example_test.go b/sdk/resourcemanager/chaos/armchaos/targets_client_example_test.go index 3e8729e5b735..14255f853165 100644 --- a/sdk/resourcemanager/chaos/armchaos/targets_client_example_test.go +++ b/sdk/resourcemanager/chaos/armchaos/targets_client_example_test.go @@ -1,169 +1,161 @@ -//go:build go1.18 -// +build go1.18 - // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. -// DO NOT EDIT. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. package armchaos_test import ( "context" - "log" - "github.com/Azure/azure-sdk-for-go/sdk/azidentity" - "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/chaos/armchaos" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/chaos/armchaos/v2" + "log" ) -// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/e4009d2f8d3bf0271757e522c7d1c1997e193d44/specification/chaos/resource-manager/Microsoft.Chaos/stable/2024-01-01/examples/ListTargets.json -func ExampleTargetsClient_NewListPager() { - cred, err := azidentity.NewDefaultAzureCredential(nil) - if err != nil { - log.Fatalf("failed to obtain a credential: %v", err) - } - ctx := context.Background() - clientFactory, err := armchaos.NewClientFactory("", cred, nil) - if err != nil { - log.Fatalf("failed to create client: %v", err) - } - pager := clientFactory.NewTargetsClient().NewListPager("exampleRG", "Microsoft.Compute", "virtualMachines", "exampleVM", &armchaos.TargetsClientListOptions{ContinuationToken: nil}) - for pager.More() { - page, err := pager.NextPage(ctx) - if err != nil { - log.Fatalf("failed to advance page: %v", err) - } - for _, v := range page.Value { - // You could use page here. We use blank identifier for just demo purposes. - _ = v - } - // If the HTTP response code is 200 as defined in example definition, your page structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. - // page.TargetListResult = armchaos.TargetListResult{ - // Value: []*armchaos.Target{ - // { - // Name: to.Ptr("Microsoft-Agent"), - // Type: to.Ptr("Microsoft.Chaos/targets"), - // ID: to.Ptr("/subscriptions/6b052e15-03d3-4f17-b2e1-be7f07588291/resourceGroups/exampleRG/providers/Microsoft.Compute/virtualMachines/exampleVM/providers/Microsoft.Chaos/targets/Microsoft-Agent"), - // Location: to.Ptr("centraluseuap"), - // Properties: map[string]any{ - // "agentProfileId": "ac4e8251-fdc9-4277-8e87-dc57fe5794cf", - // "identities": []any{ - // map[string]any{ - // "type": "CertificateSubjectIssuer", - // "subject": "CN=example.subject", - // }, - // }, - // }, - // SystemData: &armchaos.SystemData{ - // CreatedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2021-07-01T00:00:00.000Z"); return t}()), - // LastModifiedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2021-07-01T00:00:00.000Z"); return t}()), - // }, - // }}, - // } - } -} - -// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/e4009d2f8d3bf0271757e522c7d1c1997e193d44/specification/chaos/resource-manager/Microsoft.Chaos/stable/2024-01-01/examples/GetTarget.json -func ExampleTargetsClient_Get() { +// Generated from example definition: 2025-01-01/Targets_CreateOrUpdate.json +func ExampleTargetsClient_CreateOrUpdate() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() - clientFactory, err := armchaos.NewClientFactory("", cred, nil) + clientFactory, err := armchaos.NewClientFactory("6b052e15-03d3-4f17-b2e1-be7f07588291", cred, nil) if err != nil { log.Fatalf("failed to create client: %v", err) } - res, err := clientFactory.NewTargetsClient().Get(ctx, "exampleRG", "Microsoft.Compute", "virtualMachines", "exampleVM", "Microsoft-Agent", nil) + res, err := clientFactory.NewTargetsClient().CreateOrUpdate(ctx, "exampleRG", "Microsoft.Compute", "virtualMachines", "exampleVM", "Microsoft-VirtualMachine", armchaos.Target{ + Properties: map[string]any{}, + }, nil) if err != nil { log.Fatalf("failed to finish the request: %v", err) } // You could use response here. We use blank identifier for just demo purposes. _ = res // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. - // res.Target = armchaos.Target{ - // Name: to.Ptr("Microsoft-Agent"), - // Type: to.Ptr("Microsoft.Chaos/targets"), - // ID: to.Ptr("/subscriptions/6b052e15-03d3-4f17-b2e1-be7f07588291/resourceGroups/exampleRG/providers/Microsoft.Compute/virtualMachines/exampleVM/providers/Microsoft.Chaos/targets/Microsoft-Agent"), - // Location: to.Ptr("centraluseuap"), - // Properties: map[string]any{ - // "agentProfileId": "ac4e8251-fdc9-4277-8e87-dc57fe5794cf", - // "identities": []any{ - // map[string]any{ - // "type": "CertificateSubjectIssuer", - // "subject": "CN=example.subject", - // }, + // res = armchaos.TargetsClientCreateOrUpdateResponse{ + // Target: &armchaos.Target{ + // Name: to.Ptr("Microsoft-VirtualMachine"), + // Type: to.Ptr("Microsoft.Chaos/targets"), + // ID: to.Ptr("/subscriptions/6b052e15-03d3-4f17-b2e1-be7f07588291/resourceGroups/exampleRG/providers/Microsoft.Compute/virtualMachines/exampleVM/providers/Microsoft.Chaos/targets/Microsoft-VirtualMachine"), + // Properties: map[string]any{ + // }, + // SystemData: &armchaos.SystemData{ + // CreatedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2021-07-01T00:00:00.0Z"); return t}()), + // LastModifiedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2021-07-01T00:00:00.0Z"); return t}()), // }, - // }, - // SystemData: &armchaos.SystemData{ - // CreatedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2021-07-01T00:00:00.000Z"); return t}()), - // LastModifiedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2021-07-01T00:00:00.000Z"); return t}()), // }, // } } -// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/e4009d2f8d3bf0271757e522c7d1c1997e193d44/specification/chaos/resource-manager/Microsoft.Chaos/stable/2024-01-01/examples/DeleteTarget.json +// Generated from example definition: 2025-01-01/Targets_Delete.json func ExampleTargetsClient_Delete() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() - clientFactory, err := armchaos.NewClientFactory("", cred, nil) + clientFactory, err := armchaos.NewClientFactory("6b052e15-03d3-4f17-b2e1-be7f07588291", cred, nil) if err != nil { log.Fatalf("failed to create client: %v", err) } - _, err = clientFactory.NewTargetsClient().Delete(ctx, "exampleRG", "Microsoft.Compute", "virtualMachines", "exampleVM", "Microsoft-Agent", nil) + res, err := clientFactory.NewTargetsClient().Delete(ctx, "exampleRG", "Microsoft.Compute", "virtualMachines", "exampleVM", "Microsoft-Agent", nil) if err != nil { log.Fatalf("failed to finish the request: %v", err) } + // You could use response here. We use blank identifier for just demo purposes. + _ = res + // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // res = armchaos.TargetsClientDeleteResponse{ + // } } -// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/e4009d2f8d3bf0271757e522c7d1c1997e193d44/specification/chaos/resource-manager/Microsoft.Chaos/stable/2024-01-01/examples/CreateUpdateTarget.json -func ExampleTargetsClient_CreateOrUpdate() { +// Generated from example definition: 2025-01-01/Targets_Get.json +func ExampleTargetsClient_Get() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() - clientFactory, err := armchaos.NewClientFactory("", cred, nil) + clientFactory, err := armchaos.NewClientFactory("6b052e15-03d3-4f17-b2e1-be7f07588291", cred, nil) if err != nil { log.Fatalf("failed to create client: %v", err) } - res, err := clientFactory.NewTargetsClient().CreateOrUpdate(ctx, "exampleRG", "Microsoft.Compute", "virtualMachines", "exampleVM", "Microsoft-Agent", armchaos.Target{ - Properties: map[string]any{ - "identities": []any{ - map[string]any{ - "type": "CertificateSubjectIssuer", - "subject": "CN=example.subject", - }, - }, - }, - }, nil) + res, err := clientFactory.NewTargetsClient().Get(ctx, "exampleRG", "Microsoft.Compute", "virtualMachines", "exampleVM", "Microsoft-Agent", nil) if err != nil { log.Fatalf("failed to finish the request: %v", err) } // You could use response here. We use blank identifier for just demo purposes. _ = res // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. - // res.Target = armchaos.Target{ - // Name: to.Ptr("Microsoft-Agent"), - // Type: to.Ptr("Microsoft.Chaos/targets"), - // ID: to.Ptr("/subscriptions/6b052e15-03d3-4f17-b2e1-be7f07588291/resourceGroups/exampleRG/providers/Microsoft.Compute/virtualMachines/exampleVM/providers/Microsoft.Chaos/targets/Microsoft-Agent"), - // Location: to.Ptr("centraluseuap"), - // Properties: map[string]any{ - // "agentProfileId": "ac4e8251-fdc9-4277-8e87-dc57fe5794cf", - // "identities": []any{ - // map[string]any{ - // "type": "CertificateSubjectIssuer", - // "subject": "CN=example.subject", + // res = armchaos.TargetsClientGetResponse{ + // Target: &armchaos.Target{ + // Name: to.Ptr("Microsoft-Agent"), + // Type: to.Ptr("Microsoft.Chaos/targets"), + // ID: to.Ptr("/subscriptions/6b052e15-03d3-4f17-b2e1-be7f07588291/resourceGroups/exampleRG/providers/Microsoft.Compute/virtualMachines/exampleVM/providers/Microsoft.Chaos/targets/Microsoft-Agent"), + // Location: to.Ptr("centraluseuap"), + // Properties: map[string]any{ + // "agentProfileId": "ac4e8251-fdc9-4277-8e87-dc57fe5794cf", + // "identities": any{ + // map[string]any{ + // "type": "CertificateSubjectIssuer", + // "subject": "CN=example.subject", + // }, // }, // }, - // }, - // SystemData: &armchaos.SystemData{ - // CreatedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2021-07-01T00:00:00.000Z"); return t}()), - // LastModifiedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2021-07-01T00:00:00.000Z"); return t}()), + // SystemData: &armchaos.SystemData{ + // CreatedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2021-07-01T00:00:00.0Z"); return t}()), + // LastModifiedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2021-07-01T00:00:00.0Z"); return t}()), + // }, // }, // } } + +// Generated from example definition: 2025-01-01/Targets_List.json +func ExampleTargetsClient_NewListPager() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armchaos.NewClientFactory("6b052e15-03d3-4f17-b2e1-be7f07588291", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + pager := clientFactory.NewTargetsClient().NewListPager("exampleRG", "Microsoft.Compute", "virtualMachines", "exampleVM", nil) + for pager.More() { + page, err := pager.NextPage(ctx) + if err != nil { + log.Fatalf("failed to advance page: %v", err) + } + for _, v := range page.Value { + // You could use page here. We use blank identifier for just demo purposes. + _ = v + } + // If the HTTP response code is 200 as defined in example definition, your page structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // page = armchaos.TargetsClientListResponse{ + // TargetListResult: armchaos.TargetListResult{ + // NextLink: to.Ptr("https://management.azure.com/subscriptions/6b052e15-03d3-4f17-b2e1-be7f07588291/resourceGroups/exampleRG/providers/Microsoft.Compute/virtualMachines/exampleVM/providers/Microsoft.Chaos/targets?continuationToken=&api-version=2024-11-01-preview"), + // Value: []*armchaos.Target{ + // { + // Name: to.Ptr("Microsoft-Agent"), + // Type: to.Ptr("Microsoft.Chaos/targets"), + // ID: to.Ptr("/subscriptions/6b052e15-03d3-4f17-b2e1-be7f07588291/resourceGroups/exampleRG/providers/Microsoft.Compute/virtualMachines/exampleVM/providers/Microsoft.Chaos/targets/Microsoft-Agent"), + // Location: to.Ptr("centraluseuap"), + // Properties: map[string]any{ + // "agentProfileId": "ac4e8251-fdc9-4277-8e87-dc57fe5794cf", + // "identities": any{ + // map[string]any{ + // "type": "CertificateSubjectIssuer", + // "subject": "CN=example.subject", + // }, + // }, + // }, + // SystemData: &armchaos.SystemData{ + // CreatedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2021-07-01T00:00:00.0Z"); return t}()), + // LastModifiedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2021-07-01T00:00:00.0Z"); return t}()), + // }, + // }, + // }, + // }, + // } + } +} diff --git a/sdk/resourcemanager/chaos/armchaos/targets_live_test.go b/sdk/resourcemanager/chaos/armchaos/targets_live_test.go index cf78e4a3a1a6..3d17da23c2d4 100644 --- a/sdk/resourcemanager/chaos/armchaos/targets_live_test.go +++ b/sdk/resourcemanager/chaos/armchaos/targets_live_test.go @@ -15,7 +15,7 @@ import ( "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" "github.com/Azure/azure-sdk-for-go/sdk/internal/recording" - "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/chaos/armchaos" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/chaos/armchaos/v2" "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/internal/v3/testutil" "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/resources/armresources" "github.com/stretchr/testify/suite" diff --git a/sdk/resourcemanager/chaos/armchaos/targettypes_client.go b/sdk/resourcemanager/chaos/armchaos/targettypes_client.go index c84ab3f33eb4..2a76543b7f3d 100644 --- a/sdk/resourcemanager/chaos/armchaos/targettypes_client.go +++ b/sdk/resourcemanager/chaos/armchaos/targettypes_client.go @@ -1,10 +1,6 @@ -//go:build go1.18 -// +build go1.18 - // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. -// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. package armchaos @@ -28,7 +24,7 @@ type TargetTypesClient struct { } // NewTargetTypesClient creates a new instance of TargetTypesClient with the specified values. -// - subscriptionID - GUID that represents an Azure subscription ID. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. // - credential - used to authorize requests. Usually a credential from azidentity. // - options - pass nil to accept the default values. func NewTargetTypesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*TargetTypesClient, error) { @@ -46,17 +42,17 @@ func NewTargetTypesClient(subscriptionID string, credential azcore.TokenCredenti // Get - Get a Target Type resources for given location. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2024-01-01 -// - locationName - String that represents a Location resource name. +// Generated from API version 2025-01-01 +// - location - The name of the Azure region. // - targetTypeName - String that represents a Target Type resource name. // - options - TargetTypesClientGetOptions contains the optional parameters for the TargetTypesClient.Get method. -func (client *TargetTypesClient) Get(ctx context.Context, locationName string, targetTypeName string, options *TargetTypesClientGetOptions) (TargetTypesClientGetResponse, error) { +func (client *TargetTypesClient) Get(ctx context.Context, location string, targetTypeName string, options *TargetTypesClientGetOptions) (TargetTypesClientGetResponse, error) { var err error const operationName = "TargetTypesClient.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, locationName, targetTypeName, options) + req, err := client.getCreateRequest(ctx, location, targetTypeName, options) if err != nil { return TargetTypesClientGetResponse{}, err } @@ -73,16 +69,16 @@ func (client *TargetTypesClient) Get(ctx context.Context, locationName string, t } // getCreateRequest creates the Get request. -func (client *TargetTypesClient) getCreateRequest(ctx context.Context, locationName string, targetTypeName string, options *TargetTypesClientGetOptions) (*policy.Request, error) { - urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Chaos/locations/{locationName}/targetTypes/{targetTypeName}" +func (client *TargetTypesClient) getCreateRequest(ctx context.Context, location string, targetTypeName string, _ *TargetTypesClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Chaos/locations/{location}/targetTypes/{targetTypeName}" if client.subscriptionID == "" { return nil, errors.New("parameter client.subscriptionID cannot be empty") } urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) - if locationName == "" { - return nil, errors.New("parameter locationName cannot be empty") + if location == "" { + return nil, errors.New("parameter location cannot be empty") } - urlPath = strings.ReplaceAll(urlPath, "{locationName}", url.PathEscape(locationName)) + urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location)) if targetTypeName == "" { return nil, errors.New("parameter targetTypeName cannot be empty") } @@ -92,7 +88,7 @@ func (client *TargetTypesClient) getCreateRequest(ctx context.Context, locationN return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2024-01-01") + reqQP.Set("api-version", "2025-01-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -109,10 +105,10 @@ func (client *TargetTypesClient) getHandleResponse(resp *http.Response) (TargetT // NewListPager - Get a list of Target Type resources for given location. // -// Generated from API version 2024-01-01 -// - locationName - String that represents a Location resource name. +// Generated from API version 2025-01-01 +// - location - The name of the Azure region. // - options - TargetTypesClientListOptions contains the optional parameters for the TargetTypesClient.NewListPager method. -func (client *TargetTypesClient) NewListPager(locationName string, options *TargetTypesClientListOptions) *runtime.Pager[TargetTypesClientListResponse] { +func (client *TargetTypesClient) NewListPager(location string, options *TargetTypesClientListOptions) *runtime.Pager[TargetTypesClientListResponse] { return runtime.NewPager(runtime.PagingHandler[TargetTypesClientListResponse]{ More: func(page TargetTypesClientListResponse) bool { return page.NextLink != nil && len(*page.NextLink) > 0 @@ -124,7 +120,7 @@ func (client *TargetTypesClient) NewListPager(locationName string, options *Targ nextLink = *page.NextLink } resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { - return client.listCreateRequest(ctx, locationName, options) + return client.listCreateRequest(ctx, location, options) }, nil) if err != nil { return TargetTypesClientListResponse{}, err @@ -136,22 +132,22 @@ func (client *TargetTypesClient) NewListPager(locationName string, options *Targ } // listCreateRequest creates the List request. -func (client *TargetTypesClient) listCreateRequest(ctx context.Context, locationName string, options *TargetTypesClientListOptions) (*policy.Request, error) { - urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Chaos/locations/{locationName}/targetTypes" +func (client *TargetTypesClient) listCreateRequest(ctx context.Context, location string, options *TargetTypesClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Chaos/locations/{location}/targetTypes" if client.subscriptionID == "" { return nil, errors.New("parameter client.subscriptionID cannot be empty") } urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) - if locationName == "" { - return nil, errors.New("parameter locationName cannot be empty") + if location == "" { + return nil, errors.New("parameter location cannot be empty") } - urlPath = strings.ReplaceAll(urlPath, "{locationName}", url.PathEscape(locationName)) + urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location)) req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) if err != nil { return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2024-01-01") + reqQP.Set("api-version", "2025-01-01") if options != nil && options.ContinuationToken != nil { reqQP.Set("continuationToken", *options.ContinuationToken) } diff --git a/sdk/resourcemanager/chaos/armchaos/targettypes_client_example_test.go b/sdk/resourcemanager/chaos/armchaos/targettypes_client_example_test.go index c26ec4669bc6..caa24bc5fbcb 100644 --- a/sdk/resourcemanager/chaos/armchaos/targettypes_client_example_test.go +++ b/sdk/resourcemanager/chaos/armchaos/targettypes_client_example_test.go @@ -1,34 +1,64 @@ -//go:build go1.18 -// +build go1.18 - // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. -// DO NOT EDIT. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. package armchaos_test import ( "context" - "log" - "github.com/Azure/azure-sdk-for-go/sdk/azidentity" - "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/chaos/armchaos" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/chaos/armchaos/v2" + "log" ) -// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/e4009d2f8d3bf0271757e522c7d1c1997e193d44/specification/chaos/resource-manager/Microsoft.Chaos/stable/2024-01-01/examples/ListTargetTypes.json +// Generated from example definition: 2025-01-01/TargetTypes_Get.json +func ExampleTargetTypesClient_Get() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armchaos.NewClientFactory("6b052e15-03d3-4f17-b2e1-be7f07588291", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + res, err := clientFactory.NewTargetTypesClient().Get(ctx, "westus2", "Microsoft-Agent", nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + // You could use response here. We use blank identifier for just demo purposes. + _ = res + // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // res = armchaos.TargetTypesClientGetResponse{ + // TargetType: &armchaos.TargetType{ + // Name: to.Ptr("Microsoft-Agent"), + // Type: to.Ptr("Microsoft.Chaos/locations/targetTypes"), + // ID: to.Ptr("/subscriptions/6b052e15-03d3-4f17-b2e1-be7f07588291/providers/Microsoft.Chaos/locations/westus2/targetTypes/Microsoft-Agent"), + // Properties: &armchaos.TargetTypeProperties{ + // Description: to.Ptr("A target represents Chaos Agent."), + // DisplayName: to.Ptr("Chaos Agent"), + // PropertiesSchema: to.Ptr("https://schema.centralus.chaos-prod.azure.com/targets/Microsoft-VirtualMachine.json"), + // ResourceTypes: []*string{ + // to.Ptr("Microsoft.Compute/virtualMachines"), + // to.Ptr("Microsoft.Compute/virtualMachineScaleSets"), + // }, + // }, + // }, + // } +} + +// Generated from example definition: 2025-01-01/TargetTypes_List.json func ExampleTargetTypesClient_NewListPager() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() - clientFactory, err := armchaos.NewClientFactory("", cred, nil) + clientFactory, err := armchaos.NewClientFactory("6b052e15-03d3-4f17-b2e1-be7f07588291", cred, nil) if err != nil { log.Fatalf("failed to create client: %v", err) } - pager := clientFactory.NewTargetTypesClient().NewListPager("westus2", &armchaos.TargetTypesClientListOptions{ContinuationToken: nil}) + pager := clientFactory.NewTargetTypesClient().NewListPager("westus2", nil) for pager.More() { page, err := pager.NextPage(ctx) if err != nil { @@ -39,56 +69,26 @@ func ExampleTargetTypesClient_NewListPager() { _ = v } // If the HTTP response code is 200 as defined in example definition, your page structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. - // page.TargetTypeListResult = armchaos.TargetTypeListResult{ - // Value: []*armchaos.TargetType{ - // { - // Name: to.Ptr("Microsoft-Agent"), - // Type: to.Ptr("Microsoft.Chaos/locations/targetTypes"), - // ID: to.Ptr("/subscriptions/6b052e15-03d3-4f17-b2e1-be7f07588291/providers/Microsoft.Chaos/locations/westus2/targetTypes/Microsoft-Agent"), - // Location: to.Ptr("centraluseuap"), - // Properties: &armchaos.TargetTypeProperties{ - // Description: to.Ptr("A target represents Chaos Agent."), - // DisplayName: to.Ptr("Chaos Agent"), - // PropertiesSchema: to.Ptr("https://schema.centralus.chaos-prod.azure.com/targets/Microsoft-VirtualMachine.json"), - // ResourceTypes: []*string{ - // to.Ptr("Microsoft.Compute/virtualMachines"), - // to.Ptr("Microsoft.Compute/virtualMachineScaleSets")}, + // page = armchaos.TargetTypesClientListResponse{ + // TargetTypeListResult: armchaos.TargetTypeListResult{ + // NextLink: to.Ptr("https://management.azure.com/subscriptions/6b052e15-03d3-4f17-b2e1-be7f07588291/providers/Microsoft.Chaos/locations/westus2/targetTypes?continuationToken=&api-version=2024-11-01-preview"), + // Value: []*armchaos.TargetType{ + // { + // Name: to.Ptr("Microsoft-Agent"), + // Type: to.Ptr("Microsoft.Chaos/locations/targetTypes"), + // ID: to.Ptr("/subscriptions/6b052e15-03d3-4f17-b2e1-be7f07588291/providers/Microsoft.Chaos/locations/westus2/targetTypes/Microsoft-Agent"), + // Properties: &armchaos.TargetTypeProperties{ + // Description: to.Ptr("A target represents Chaos Agent."), + // DisplayName: to.Ptr("Chaos Agent"), + // PropertiesSchema: to.Ptr("https://schema.centralus.chaos-prod.azure.com/targets/Microsoft-VirtualMachine.json"), + // ResourceTypes: []*string{ + // to.Ptr("Microsoft.Compute/virtualMachines"), + // to.Ptr("Microsoft.Compute/virtualMachineScaleSets"), + // }, // }, - // }}, - // } + // }, + // }, + // }, + // } } } - -// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/e4009d2f8d3bf0271757e522c7d1c1997e193d44/specification/chaos/resource-manager/Microsoft.Chaos/stable/2024-01-01/examples/GetTargetType.json -func ExampleTargetTypesClient_Get() { - cred, err := azidentity.NewDefaultAzureCredential(nil) - if err != nil { - log.Fatalf("failed to obtain a credential: %v", err) - } - ctx := context.Background() - clientFactory, err := armchaos.NewClientFactory("", cred, nil) - if err != nil { - log.Fatalf("failed to create client: %v", err) - } - res, err := clientFactory.NewTargetTypesClient().Get(ctx, "westus2", "Microsoft-Agent", nil) - if err != nil { - log.Fatalf("failed to finish the request: %v", err) - } - // You could use response here. We use blank identifier for just demo purposes. - _ = res - // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. - // res.TargetType = armchaos.TargetType{ - // Name: to.Ptr("Microsoft-Agent"), - // Type: to.Ptr("Microsoft.Chaos/locations/targetTypes"), - // ID: to.Ptr("/subscriptions/6b052e15-03d3-4f17-b2e1-be7f07588291/providers/Microsoft.Chaos/locations/westus2/targetTypes/Microsoft-Agent"), - // Location: to.Ptr("centraluseuap"), - // Properties: &armchaos.TargetTypeProperties{ - // Description: to.Ptr("A target represents Chaos Agent."), - // DisplayName: to.Ptr("Chaos Agent"), - // PropertiesSchema: to.Ptr("https://schema.centralus.chaos-prod.azure.com/targets/Microsoft-VirtualMachine.json"), - // ResourceTypes: []*string{ - // to.Ptr("Microsoft.Compute/virtualMachines"), - // to.Ptr("Microsoft.Compute/virtualMachineScaleSets")}, - // }, - // } -} diff --git a/sdk/resourcemanager/chaos/armchaos/targettypes_live_test.go b/sdk/resourcemanager/chaos/armchaos/targettypes_live_test.go index 494f73e36464..74d58009e393 100644 --- a/sdk/resourcemanager/chaos/armchaos/targettypes_live_test.go +++ b/sdk/resourcemanager/chaos/armchaos/targettypes_live_test.go @@ -14,7 +14,7 @@ import ( "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/internal/recording" - "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/chaos/armchaos" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/chaos/armchaos/v2" "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/internal/v3/testutil" "github.com/stretchr/testify/suite" ) diff --git a/sdk/resourcemanager/chaos/armchaos/time_rfc3339.go b/sdk/resourcemanager/chaos/armchaos/time_rfc3339.go index 136b2093dcd6..89003ff52115 100644 --- a/sdk/resourcemanager/chaos/armchaos/time_rfc3339.go +++ b/sdk/resourcemanager/chaos/armchaos/time_rfc3339.go @@ -1,10 +1,6 @@ -//go:build go1.18 -// +build go1.18 - // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. -// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. package armchaos @@ -60,6 +56,9 @@ func (t *dateTimeRFC3339) UnmarshalJSON(data []byte) error { } 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 diff --git a/sdk/resourcemanager/chaos/armchaos/tsp-location.yaml b/sdk/resourcemanager/chaos/armchaos/tsp-location.yaml new file mode 100644 index 000000000000..e36fe5cda89a --- /dev/null +++ b/sdk/resourcemanager/chaos/armchaos/tsp-location.yaml @@ -0,0 +1,4 @@ +directory: specification/chaos/Chaos.Management +commit: 1f578543d267d08febc1bebf4e33ffe14363ddfc +repo: Azure/azure-rest-api-specs +additionalDirectories: diff --git a/sdk/resourcemanager/commonedgesitemanageroperations/armcommonedgesitemanageroperations/CHANGELOG.md b/sdk/resourcemanager/commonedgesitemanageroperations/armcommonedgesitemanageroperations/CHANGELOG.md new file mode 100644 index 000000000000..aceb2c5a0558 --- /dev/null +++ b/sdk/resourcemanager/commonedgesitemanageroperations/armcommonedgesitemanageroperations/CHANGELOG.md @@ -0,0 +1,8 @@ +# Release History + +## 0.1.0 (2025-04-27) +### Other Changes + +The package of `github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/commonedgesitemanageroperations/armcommonedgesitemanageroperations` 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/commonedgesitemanageroperations/armcommonedgesitemanageroperations/LICENSE.txt b/sdk/resourcemanager/commonedgesitemanageroperations/armcommonedgesitemanageroperations/LICENSE.txt new file mode 100644 index 000000000000..dc0c2ffb3dc1 --- /dev/null +++ b/sdk/resourcemanager/commonedgesitemanageroperations/armcommonedgesitemanageroperations/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/commonedgesitemanageroperations/armcommonedgesitemanageroperations/README.md b/sdk/resourcemanager/commonedgesitemanageroperations/armcommonedgesitemanageroperations/README.md new file mode 100644 index 000000000000..71798fcdb727 --- /dev/null +++ b/sdk/resourcemanager/commonedgesitemanageroperations/armcommonedgesitemanageroperations/README.md @@ -0,0 +1,90 @@ +# Azure Commonedgesitemanageroperations Module for Go + +The `armcommonedgesitemanageroperations` module provides operations for working with Azure Commonedgesitemanageroperations. + +[Source code](https://github.com/Azure/azure-sdk-for-go/tree/main/sdk/resourcemanager/commonedgesitemanageroperations/armcommonedgesitemanageroperations) + +# 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 Commonedgesitemanageroperations module: + +```sh +go get github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/commonedgesitemanageroperations/armcommonedgesitemanageroperations +``` + +## Authorization + +When creating a client, you will need to provide a credential for authenticating with Azure Commonedgesitemanageroperations. 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 Commonedgesitemanageroperations 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 := armcommonedgesitemanageroperations.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 := armcommonedgesitemanageroperations.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.() +``` + +## 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 `Commonedgesitemanageroperations` 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/commonedgesitemanageroperations/armcommonedgesitemanageroperations/ci.yml b/sdk/resourcemanager/commonedgesitemanageroperations/armcommonedgesitemanageroperations/ci.yml new file mode 100644 index 000000000000..aa2264bb7bef --- /dev/null +++ b/sdk/resourcemanager/commonedgesitemanageroperations/armcommonedgesitemanageroperations/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/commonedgesitemanageroperations/armcommonedgesitemanageroperations/ + +pr: + branches: + include: + - main + - feature/* + - hotfix/* + - release/* + paths: + include: + - sdk/resourcemanager/commonedgesitemanageroperations/armcommonedgesitemanageroperations/ + +extends: + template: /eng/pipelines/templates/jobs/archetype-sdk-client.yml + parameters: + ServiceDirectory: 'resourcemanager/commonedgesitemanageroperations/armcommonedgesitemanageroperations' diff --git a/sdk/resourcemanager/commonedgesitemanageroperations/armcommonedgesitemanageroperations/client_factory.go b/sdk/resourcemanager/commonedgesitemanageroperations/armcommonedgesitemanageroperations/client_factory.go new file mode 100644 index 000000000000..70cf2a807c53 --- /dev/null +++ b/sdk/resourcemanager/commonedgesitemanageroperations/armcommonedgesitemanageroperations/client_factory.go @@ -0,0 +1,37 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcommonedgesitemanageroperations + +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 { + 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. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - pass nil to accept the default values. +func NewClientFactory(credential azcore.TokenCredential, options *arm.ClientOptions) (*ClientFactory, error) { + internal, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + return &ClientFactory{ + internal: internal, + }, nil +} + +// NewOperationsClient creates a new instance of OperationsClient. +func (c *ClientFactory) NewOperationsClient() *OperationsClient { + return &OperationsClient{ + internal: c.internal, + } +} diff --git a/sdk/resourcemanager/commonedgesitemanageroperations/armcommonedgesitemanageroperations/constants.go b/sdk/resourcemanager/commonedgesitemanageroperations/armcommonedgesitemanageroperations/constants.go new file mode 100644 index 000000000000..e8557d10db4a --- /dev/null +++ b/sdk/resourcemanager/commonedgesitemanageroperations/armcommonedgesitemanageroperations/constants.go @@ -0,0 +1,47 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcommonedgesitemanageroperations + +const ( + moduleName = "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/commonedgesitemanageroperations/armcommonedgesitemanageroperations" + moduleVersion = "v0.1.0" +) + +// ActionType - Extensible enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. +type ActionType string + +const ( + // ActionTypeInternal - Actions are for internal-only APIs. + ActionTypeInternal ActionType = "Internal" +) + +// PossibleActionTypeValues returns the possible values for the ActionType const type. +func PossibleActionTypeValues() []ActionType { + return []ActionType{ + ActionTypeInternal, + } +} + +// 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 - Indicates the operation is initiated by a system. + OriginSystem Origin = "system" + // OriginUser - Indicates the operation is initiated by a user. + OriginUser Origin = "user" + // OriginUserSystem - Indicates the operation is initiated by a user or system. + OriginUserSystem Origin = "user,system" +) + +// PossibleOriginValues returns the possible values for the Origin const type. +func PossibleOriginValues() []Origin { + return []Origin{ + OriginSystem, + OriginUser, + OriginUserSystem, + } +} diff --git a/sdk/resourcemanager/commonedgesitemanageroperations/armcommonedgesitemanageroperations/fake/internal.go b/sdk/resourcemanager/commonedgesitemanageroperations/armcommonedgesitemanageroperations/fake/internal.go new file mode 100644 index 000000000000..7425b6a669e2 --- /dev/null +++ b/sdk/resourcemanager/commonedgesitemanageroperations/armcommonedgesitemanageroperations/fake/internal.go @@ -0,0 +1,65 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "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 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/commonedgesitemanageroperations/armcommonedgesitemanageroperations/fake/operations_server.go b/sdk/resourcemanager/commonedgesitemanageroperations/armcommonedgesitemanageroperations/fake/operations_server.go new file mode 100644 index 000000000000..7de928cb204c --- /dev/null +++ b/sdk/resourcemanager/commonedgesitemanageroperations/armcommonedgesitemanageroperations/fake/operations_server.go @@ -0,0 +1,117 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/commonedgesitemanageroperations/armcommonedgesitemanageroperations" + "net/http" +) + +// OperationsServer is a fake server for instances of the armcommonedgesitemanageroperations.OperationsClient type. +type OperationsServer struct { + // NewListPager is the fake for method OperationsClient.NewListPager + // HTTP status codes to indicate success: http.StatusOK + NewListPager func(options *armcommonedgesitemanageroperations.OperationsClientListOptions) (resp azfake.PagerResponder[armcommonedgesitemanageroperations.OperationsClientListResponse]) +} + +// NewOperationsServerTransport creates a new instance of OperationsServerTransport with the provided implementation. +// The returned OperationsServerTransport instance is connected to an instance of armcommonedgesitemanageroperations.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[armcommonedgesitemanageroperations.OperationsClientListResponse]](), + } +} + +// OperationsServerTransport connects instances of armcommonedgesitemanageroperations.OperationsClient to instances of OperationsServer. +// Don't use this type directly, use NewOperationsServerTransport instead. +type OperationsServerTransport struct { + srv *OperationsServer + newListPager *tracker[azfake.PagerResponder[armcommonedgesitemanageroperations.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 *armcommonedgesitemanageroperations.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/commonedgesitemanageroperations/armcommonedgesitemanageroperations/fake/server_factory.go b/sdk/resourcemanager/commonedgesitemanageroperations/armcommonedgesitemanageroperations/fake/server_factory.go new file mode 100644 index 000000000000..04f376b5276f --- /dev/null +++ b/sdk/resourcemanager/commonedgesitemanageroperations/armcommonedgesitemanageroperations/fake/server_factory.go @@ -0,0 +1,72 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "errors" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" + "sync" +) + +// ServerFactory is a fake server for instances of the armcommonedgesitemanageroperations.ClientFactory type. +type ServerFactory struct { + // OperationsServer contains the fakes for client OperationsClient + OperationsServer OperationsServer +} + +// NewServerFactoryTransport creates a new instance of ServerFactoryTransport with the provided implementation. +// The returned ServerFactoryTransport instance is connected to an instance of armcommonedgesitemanageroperations.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 armcommonedgesitemanageroperations.ClientFactory to instances of ServerFactory. +// Don't use this type directly, use NewServerFactoryTransport instead. +type ServerFactoryTransport struct { + srv *ServerFactory + trMu sync.Mutex + trOperationsServer *OperationsServerTransport +} + +// 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 "OperationsClient": + initServer(s, &s.trOperationsServer, func() *OperationsServerTransport { return NewOperationsServerTransport(&s.srv.OperationsServer) }) + resp, err = s.trOperationsServer.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/commonedgesitemanageroperations/armcommonedgesitemanageroperations/go.mod b/sdk/resourcemanager/commonedgesitemanageroperations/armcommonedgesitemanageroperations/go.mod new file mode 100644 index 000000000000..83d36226b9c7 --- /dev/null +++ b/sdk/resourcemanager/commonedgesitemanageroperations/armcommonedgesitemanageroperations/go.mod @@ -0,0 +1,23 @@ +module github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/commonedgesitemanageroperations/armcommonedgesitemanageroperations + +go 1.23.0 + +toolchain go1.23.8 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.17.1 + github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.7.0 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.10.0 // indirect + github.com/AzureAD/microsoft-authentication-library-for-go v1.2.2 // indirect + github.com/golang-jwt/jwt/v5 v5.2.1 // indirect + github.com/google/uuid v1.6.0 // indirect + github.com/kylelemons/godebug v1.1.0 // indirect + github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c // indirect + golang.org/x/crypto v0.36.0 // indirect + golang.org/x/net v0.37.0 // indirect + golang.org/x/sys v0.31.0 // indirect + golang.org/x/text v0.23.0 // indirect +) diff --git a/sdk/resourcemanager/commonedgesitemanageroperations/armcommonedgesitemanageroperations/go.sum b/sdk/resourcemanager/commonedgesitemanageroperations/armcommonedgesitemanageroperations/go.sum new file mode 100644 index 000000000000..1f92486fbbcf --- /dev/null +++ b/sdk/resourcemanager/commonedgesitemanageroperations/armcommonedgesitemanageroperations/go.sum @@ -0,0 +1,33 @@ +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/azidentity v1.7.0 h1:tfLQ34V6F7tVSwoTf/4lH5sE0o6eCJuNDTmH09nDpbc= +github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.7.0/go.mod h1:9kIvujWAA58nmPmWB1m23fyWic1kYZMxD9CxaWn4Qpg= +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/AzureAD/microsoft-authentication-library-for-go v1.2.2 h1:XHOnouVk1mxXfQidrMEnLlPk9UMeRtyBTnEFtxkV0kU= +github.com/AzureAD/microsoft-authentication-library-for-go v1.2.2/go.mod h1:wP83P5OoQ5p6ip3ScPr0BAq0BvuPAvacpEuSzyouqAI= +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/golang-jwt/jwt/v5 v5.2.1 h1:OuVbFODueb089Lh128TAcimifWaLhJwVflnrgM17wHk= +github.com/golang-jwt/jwt/v5 v5.2.1/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk= +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc= +github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= +github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c h1:+mdjkGKdHQG3305AYmdv1U2eRNDiU2ErMBj1gwrq8eQ= +github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c/go.mod h1:7rwL4CYBLnjLxUqIJNnCWiEdr3bn6IUYi15bNlnbCCU= +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/crypto v0.36.0 h1:AnAEvhDddvBdpY+uR+MyHmuZzzNqXSe/GvuDeob5L34= +golang.org/x/crypto v0.36.0/go.mod h1:Y4J0ReaxCR1IMaabaSMugxJES1EpwhBHhv2bDHklZvc= +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/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.31.0 h1:ioabZlmFYtWhL+TRYpcnNlLwhyxaM9kWTDEmfnprqik= +golang.org/x/sys v0.31.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= +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/commonedgesitemanageroperations/armcommonedgesitemanageroperations/models.go b/sdk/resourcemanager/commonedgesitemanageroperations/armcommonedgesitemanageroperations/models.go new file mode 100644 index 000000000000..f9bd4e0047d1 --- /dev/null +++ b/sdk/resourcemanager/commonedgesitemanageroperations/armcommonedgesitemanageroperations/models.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) Go Code Generator. DO NOT EDIT. + +package armcommonedgesitemanageroperations + +// 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; Extensible 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 Azure + // Resource Manager/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 and 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 { + // REQUIRED; The Operation items on this page + Value []*Operation + + // The link to the next page of items + NextLink *string +} diff --git a/sdk/resourcemanager/commonedgesitemanageroperations/armcommonedgesitemanageroperations/models_serde.go b/sdk/resourcemanager/commonedgesitemanageroperations/armcommonedgesitemanageroperations/models_serde.go new file mode 100644 index 000000000000..90a3c297f88b --- /dev/null +++ b/sdk/resourcemanager/commonedgesitemanageroperations/armcommonedgesitemanageroperations/models_serde.go @@ -0,0 +1,145 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcommonedgesitemanageroperations + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "reflect" +) + +// 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 +} + +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/commonedgesitemanageroperations/armcommonedgesitemanageroperations/operations_client.go b/sdk/resourcemanager/commonedgesitemanageroperations/armcommonedgesitemanageroperations/operations_client.go new file mode 100644 index 000000000000..ac7ee1e62067 --- /dev/null +++ b/sdk/resourcemanager/commonedgesitemanageroperations/armcommonedgesitemanageroperations/operations_client.go @@ -0,0 +1,84 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcommonedgesitemanageroperations + +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 2024-02-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.Edge/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", "2024-02-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/commonedgesitemanageroperations/armcommonedgesitemanageroperations/operations_client_example_test.go b/sdk/resourcemanager/commonedgesitemanageroperations/armcommonedgesitemanageroperations/operations_client_example_test.go new file mode 100644 index 000000000000..4ecc002d340c --- /dev/null +++ b/sdk/resourcemanager/commonedgesitemanageroperations/armcommonedgesitemanageroperations/operations_client_example_test.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) Go Code Generator. DO NOT EDIT. + +package armcommonedgesitemanageroperations_test + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azidentity" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/commonedgesitemanageroperations/armcommonedgesitemanageroperations" + "log" +) + +// Generated from example definition: 2024-02-01-preview/Operations_List_MaximumSet_Gen.json +func ExampleOperationsClient_NewListPager_operationsListMaximumSetGenGeneratedByMaximumSetRule() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armcommonedgesitemanageroperations.NewClientFactory(cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + pager := clientFactory.NewOperationsClient().NewListPager(nil) + for pager.More() { + page, err := pager.NextPage(ctx) + if err != nil { + log.Fatalf("failed to advance page: %v", err) + } + for _, v := range page.Value { + // You could use page here. We use blank identifier for just demo purposes. + _ = v + } + // If the HTTP response code is 200 as defined in example definition, your page structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // page = armcommonedgesitemanageroperations.OperationsClientListResponse{ + // OperationListResult: armcommonedgesitemanageroperations.OperationListResult{ + // Value: []*armcommonedgesitemanageroperations.Operation{ + // { + // Name: to.Ptr("jaczxpiqtdkz"), + // IsDataAction: to.Ptr(true), + // Display: &armcommonedgesitemanageroperations.OperationDisplay{ + // Provider: to.Ptr("oapgkefpoeegxjy"), + // Resource: to.Ptr("zyprevbuvdzgvb"), + // Operation: to.Ptr("heesmjbscdhwik"), + // Description: to.Ptr("ezjkmigqsov"), + // }, + // Origin: to.Ptr(armcommonedgesitemanageroperations.OriginUser), + // ActionType: to.Ptr(armcommonedgesitemanageroperations.ActionTypeInternal), + // }, + // }, + // NextLink: to.Ptr("https://microsoft.com/a"), + // }, + // } + } +} + +// Generated from example definition: 2024-02-01-preview/Operations_List_MinimumSet_Gen.json +func ExampleOperationsClient_NewListPager_operationsListMaximumSetGenGeneratedByMinimumSetRule() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armcommonedgesitemanageroperations.NewClientFactory(cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + pager := clientFactory.NewOperationsClient().NewListPager(nil) + for pager.More() { + page, err := pager.NextPage(ctx) + if err != nil { + log.Fatalf("failed to advance page: %v", err) + } + for _, v := range page.Value { + // You could use page here. We use blank identifier for just demo purposes. + _ = v + } + // If the HTTP response code is 200 as defined in example definition, your page structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // page = armcommonedgesitemanageroperations.OperationsClientListResponse{ + // OperationListResult: armcommonedgesitemanageroperations.OperationListResult{ + // }, + // } + } +} diff --git a/sdk/resourcemanager/commonedgesitemanageroperations/armcommonedgesitemanageroperations/options.go b/sdk/resourcemanager/commonedgesitemanageroperations/armcommonedgesitemanageroperations/options.go new file mode 100644 index 000000000000..356d8c2d1002 --- /dev/null +++ b/sdk/resourcemanager/commonedgesitemanageroperations/armcommonedgesitemanageroperations/options.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcommonedgesitemanageroperations + +// OperationsClientListOptions contains the optional parameters for the OperationsClient.NewListPager method. +type OperationsClientListOptions struct { + // placeholder for future optional parameters +} diff --git a/sdk/resourcemanager/commonedgesitemanageroperations/armcommonedgesitemanageroperations/responses.go b/sdk/resourcemanager/commonedgesitemanageroperations/armcommonedgesitemanageroperations/responses.go new file mode 100644 index 000000000000..c3ea5c30c19c --- /dev/null +++ b/sdk/resourcemanager/commonedgesitemanageroperations/armcommonedgesitemanageroperations/responses.go @@ -0,0 +1,11 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcommonedgesitemanageroperations + +// 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 +} diff --git a/sdk/resourcemanager/commonedgesitemanageroperations/armcommonedgesitemanageroperations/tsp-location.yaml b/sdk/resourcemanager/commonedgesitemanageroperations/armcommonedgesitemanageroperations/tsp-location.yaml new file mode 100644 index 000000000000..ee67cbf2f980 --- /dev/null +++ b/sdk/resourcemanager/commonedgesitemanageroperations/armcommonedgesitemanageroperations/tsp-location.yaml @@ -0,0 +1,4 @@ +directory: specification/edge/Microsoft.Edge.Management +commit: 1f578543d267d08febc1bebf4e33ffe14363ddfc +repo: Azure/azure-rest-api-specs +additionalDirectories: diff --git a/sdk/resourcemanager/computefleet/armcomputefleet/CHANGELOG.md b/sdk/resourcemanager/computefleet/armcomputefleet/CHANGELOG.md index d91bbac6cf58..46119fb9bc84 100644 --- a/sdk/resourcemanager/computefleet/armcomputefleet/CHANGELOG.md +++ b/sdk/resourcemanager/computefleet/armcomputefleet/CHANGELOG.md @@ -1,5 +1,15 @@ # Release History +## 2.0.0 (2025-04-27) +### Breaking Changes + +- `ManagedServiceIdentityTypeSystemAndUserAssigned` from enum `ManagedServiceIdentityType` has been removed + +### Features Added + +- New value `ManagedServiceIdentityTypeSystemAssignedUserAssigned` added to enum type `ManagedServiceIdentityType` + + ## 1.0.0 (2024-10-22) ### Breaking Changes diff --git a/sdk/resourcemanager/computefleet/armcomputefleet/README.md b/sdk/resourcemanager/computefleet/armcomputefleet/README.md index 92d31274c769..6ee68315561b 100644 --- a/sdk/resourcemanager/computefleet/armcomputefleet/README.md +++ b/sdk/resourcemanager/computefleet/armcomputefleet/README.md @@ -18,7 +18,7 @@ This project uses [Go modules](https://github.com/golang/go/wiki/Modules) for ve Install the Azure Compute Fleet module: ```sh -go get github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/computefleet/armcomputefleet +go get github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/computefleet/armcomputefleet/v2 ``` ## Authorization diff --git a/sdk/resourcemanager/computefleet/armcomputefleet/constants.go b/sdk/resourcemanager/computefleet/armcomputefleet/constants.go index 9a5b1d23be3c..15db93573c51 100644 --- a/sdk/resourcemanager/computefleet/armcomputefleet/constants.go +++ b/sdk/resourcemanager/computefleet/armcomputefleet/constants.go @@ -6,7 +6,7 @@ package armcomputefleet const ( moduleName = "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/computefleet/armcomputefleet" - moduleVersion = "v1.0.0" + moduleVersion = "v2.0.0" ) // AcceleratorManufacturer - Accelerator manufacturers supported by Azure VMs. @@ -188,9 +188,9 @@ func PossibleDiffDiskOptionsValues() []DiffDiskOptions { // resource disk space for Ephemeral OS disk provisioning. For more information on // Ephemeral OS disk size requirements, please refer Ephemeral OS disk size // requirements for Windows VM at -// https://docs.microsoft.com/azure/virtual-machines/windows/ephemeral-os-disks#size-requirements +// https://learn.microsoft.com/azure/virtual-machines/windows/ephemeral-os-disks#size-requirements // and Linux VM at -// https://docs.microsoft.com/azure/virtual-machines/linux/ephemeral-os-disks#size-requirements +// https://learn.microsoft.com/azure/virtual-machines/linux/ephemeral-os-disks#size-requirements // Minimum api-version for NvmeDisk: 2024-03-01. type DiffDiskPlacement string @@ -215,10 +215,10 @@ func PossibleDiffDiskPlacementValues() []DiffDiskPlacement { // DiskControllerTypes - Specifies the disk controller type configured for the VM and // VirtualMachineScaleSet. This property is only supported for virtual machines // whose operating system disk and VM sku supports Generation 2 -// (https://docs.microsoft.com/en-us/azure/virtual-machines/generation-2), please +// (https://learn.microsoft.com/en-us/azure/virtual-machines/generation-2), please // check the HyperVGenerations capability returned as part of VM sku capabilities // in the response of Microsoft.Compute SKUs api for the region contains V2 -// (https://docs.microsoft.com/rest/api/compute/resourceskus/list). For more +// (https://learn.microsoft.com/rest/api/compute/resourceskus/list). For more // information about Disk Controller Types supported please refer to // https://aka.ms/azure-diskcontrollertypes. type DiskControllerTypes string @@ -449,10 +449,10 @@ type ManagedServiceIdentityType string const ( // ManagedServiceIdentityTypeNone - No managed identity. ManagedServiceIdentityTypeNone ManagedServiceIdentityType = "None" - // ManagedServiceIdentityTypeSystemAndUserAssigned - System and user assigned managed identity. - ManagedServiceIdentityTypeSystemAndUserAssigned ManagedServiceIdentityType = "SystemAssigned,UserAssigned" // ManagedServiceIdentityTypeSystemAssigned - System assigned managed identity. ManagedServiceIdentityTypeSystemAssigned ManagedServiceIdentityType = "SystemAssigned" + // ManagedServiceIdentityTypeSystemAssignedUserAssigned - System and user assigned managed identity. + ManagedServiceIdentityTypeSystemAssignedUserAssigned ManagedServiceIdentityType = "SystemAssigned,UserAssigned" // ManagedServiceIdentityTypeUserAssigned - User assigned managed identity. ManagedServiceIdentityTypeUserAssigned ManagedServiceIdentityType = "UserAssigned" ) @@ -461,8 +461,8 @@ const ( func PossibleManagedServiceIdentityTypeValues() []ManagedServiceIdentityType { return []ManagedServiceIdentityType{ ManagedServiceIdentityTypeNone, - ManagedServiceIdentityTypeSystemAndUserAssigned, ManagedServiceIdentityTypeSystemAssigned, + ManagedServiceIdentityTypeSystemAssignedUserAssigned, ManagedServiceIdentityTypeUserAssigned, } } @@ -799,9 +799,9 @@ func PossibleSpotAllocationStrategyValues() []SpotAllocationStrategy { // zone redundant storage. StandardSSD_ZRS uses Standard SSD zone redundant // storage. For more information regarding disks supported for Windows Virtual // Machines, refer to -// https://docs.microsoft.com/azure/virtual-machines/windows/disks-types and, for +// https://learn.microsoft.com/azure/virtual-machines/windows/disks-types and, for // Linux Virtual Machines, refer to -// https://docs.microsoft.com/azure/virtual-machines/linux/disks-types +// https://learn.microsoft.com/azure/virtual-machines/linux/disks-types type StorageAccountTypes string const ( diff --git a/sdk/resourcemanager/computefleet/armcomputefleet/fake/fleets_server.go b/sdk/resourcemanager/computefleet/armcomputefleet/fake/fleets_server.go index 50095603add1..efd507989a10 100644 --- a/sdk/resourcemanager/computefleet/armcomputefleet/fake/fleets_server.go +++ b/sdk/resourcemanager/computefleet/armcomputefleet/fake/fleets_server.go @@ -12,7 +12,7 @@ import ( "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" - "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/computefleet/armcomputefleet" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/computefleet/armcomputefleet/v2" "net/http" "net/url" "regexp" @@ -25,7 +25,7 @@ type FleetsServer struct { BeginCreateOrUpdate func(ctx context.Context, resourceGroupName string, fleetName string, resource armcomputefleet.Fleet, options *armcomputefleet.FleetsClientBeginCreateOrUpdateOptions) (resp azfake.PollerResponder[armcomputefleet.FleetsClientCreateOrUpdateResponse], errResp azfake.ErrorResponder) // BeginDelete is the fake for method FleetsClient.BeginDelete - // HTTP status codes to indicate success: http.StatusAccepted, http.StatusNoContent + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent BeginDelete func(ctx context.Context, resourceGroupName string, fleetName string, options *armcomputefleet.FleetsClientBeginDeleteOptions) (resp azfake.PollerResponder[armcomputefleet.FleetsClientDeleteResponse], errResp azfake.ErrorResponder) // Get is the fake for method FleetsClient.Get @@ -88,29 +88,48 @@ func (f *FleetsServerTransport) Do(req *http.Request) (*http.Response, error) { } func (f *FleetsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { - var resp *http.Response - var err error - - switch method { - case "FleetsClient.BeginCreateOrUpdate": - resp, err = f.dispatchBeginCreateOrUpdate(req) - case "FleetsClient.BeginDelete": - resp, err = f.dispatchBeginDelete(req) - case "FleetsClient.Get": - resp, err = f.dispatchGet(req) - case "FleetsClient.NewListByResourceGroupPager": - resp, err = f.dispatchNewListByResourceGroupPager(req) - case "FleetsClient.NewListBySubscriptionPager": - resp, err = f.dispatchNewListBySubscriptionPager(req) - case "FleetsClient.NewListVirtualMachineScaleSetsPager": - resp, err = f.dispatchNewListVirtualMachineScaleSetsPager(req) - case "FleetsClient.BeginUpdate": - resp, err = f.dispatchBeginUpdate(req) - default: - err = fmt.Errorf("unhandled API %s", method) - } - - return resp, err + resultChan := make(chan result) + defer close(resultChan) + + go func() { + var intercepted bool + var res result + if fleetsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = fleetsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "FleetsClient.BeginCreateOrUpdate": + res.resp, res.err = f.dispatchBeginCreateOrUpdate(req) + case "FleetsClient.BeginDelete": + res.resp, res.err = f.dispatchBeginDelete(req) + case "FleetsClient.Get": + res.resp, res.err = f.dispatchGet(req) + case "FleetsClient.NewListByResourceGroupPager": + res.resp, res.err = f.dispatchNewListByResourceGroupPager(req) + case "FleetsClient.NewListBySubscriptionPager": + res.resp, res.err = f.dispatchNewListBySubscriptionPager(req) + case "FleetsClient.NewListVirtualMachineScaleSetsPager": + res.resp, res.err = f.dispatchNewListVirtualMachineScaleSetsPager(req) + case "FleetsClient.BeginUpdate": + res.resp, res.err = f.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 (f *FleetsServerTransport) dispatchBeginCreateOrUpdate(req *http.Request) (*http.Response, error) { @@ -194,9 +213,9 @@ func (f *FleetsServerTransport) dispatchBeginDelete(req *http.Request) (*http.Re return nil, err } - if !contains([]int{http.StatusAccepted, http.StatusNoContent}, resp.StatusCode) { + if !contains([]int{http.StatusOK, http.StatusAccepted, http.StatusNoContent}, resp.StatusCode) { f.beginDelete.remove(req) - return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusAccepted, http.StatusNoContent", resp.StatusCode)} + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted, http.StatusNoContent", resp.StatusCode)} } if !server.PollerResponderMore(beginDelete) { f.beginDelete.remove(req) @@ -396,3 +415,9 @@ func (f *FleetsServerTransport) dispatchBeginUpdate(req *http.Request) (*http.Re return resp, nil } + +// set this to conditionally intercept incoming requests to FleetsServerTransport +var fleetsServerTransportInterceptor 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/computefleet/armcomputefleet/fake/internal.go b/sdk/resourcemanager/computefleet/armcomputefleet/fake/internal.go index 56a8f624f5f3..7425b6a669e2 100644 --- a/sdk/resourcemanager/computefleet/armcomputefleet/fake/internal.go +++ b/sdk/resourcemanager/computefleet/armcomputefleet/fake/internal.go @@ -10,6 +10,11 @@ import ( "sync" ) +type result struct { + resp *http.Response + err error +} + type nonRetriableError struct { error } diff --git a/sdk/resourcemanager/computefleet/armcomputefleet/fake/operations_server.go b/sdk/resourcemanager/computefleet/armcomputefleet/fake/operations_server.go index a86d89fb4a63..1ca70f29e52a 100644 --- a/sdk/resourcemanager/computefleet/armcomputefleet/fake/operations_server.go +++ b/sdk/resourcemanager/computefleet/armcomputefleet/fake/operations_server.go @@ -11,7 +11,7 @@ import ( "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" - "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/computefleet/armcomputefleet" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/computefleet/armcomputefleet/v2" "net/http" ) @@ -51,17 +51,36 @@ func (o *OperationsServerTransport) Do(req *http.Request) (*http.Response, error } func (o *OperationsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { - var resp *http.Response - var err error + resultChan := make(chan result) + defer close(resultChan) - switch method { - case "OperationsClient.NewListPager": - resp, err = o.dispatchNewListPager(req) - default: - err = fmt.Errorf("unhandled API %s", method) - } + 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(): + } + }() - return resp, err + 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) { @@ -90,3 +109,9 @@ func (o *OperationsServerTransport) dispatchNewListPager(req *http.Request) (*ht } return resp, nil } + +// set this to conditionally intercept incoming requests to OperationsServerTransport +var operationsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/sdk/resourcemanager/computefleet/armcomputefleet/fleets_client_example_test.go b/sdk/resourcemanager/computefleet/armcomputefleet/fleets_client_example_test.go index 1499fe058820..2f3e667d135a 100644 --- a/sdk/resourcemanager/computefleet/armcomputefleet/fleets_client_example_test.go +++ b/sdk/resourcemanager/computefleet/armcomputefleet/fleets_client_example_test.go @@ -8,7 +8,7 @@ import ( "context" "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" "github.com/Azure/azure-sdk-for-go/sdk/azidentity" - "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/computefleet/armcomputefleet" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/computefleet/armcomputefleet/v2" "log" ) @@ -185,6 +185,7 @@ func ExampleFleetsClient_BeginCreateOrUpdate_fleetsCreateOrUpdate() { DeleteOption: to.Ptr(armcomputefleet.DiskDeleteOptionTypesDelete), }, }, + DiskControllerType: to.Ptr(armcomputefleet.DiskControllerTypes("uzb")), }, NetworkProfile: &armcomputefleet.VirtualMachineScaleSetNetworkProfile{ HealthProbe: &armcomputefleet.APIEntityReference{ @@ -566,6 +567,7 @@ func ExampleFleetsClient_BeginCreateOrUpdate_fleetsCreateOrUpdate() { // DeleteOption: to.Ptr(armcomputefleet.DiskDeleteOptionTypesDelete), // }, // }, + // DiskControllerType: to.Ptr(armcomputefleet.DiskControllerTypes("uzb")), // }, // NetworkProfile: &armcomputefleet.VirtualMachineScaleSetNetworkProfile{ // HealthProbe: &armcomputefleet.APIEntityReference{ @@ -888,6 +890,7 @@ func ExampleFleetsClient_BeginCreateOrUpdate_fleetsCreateOrUpdateMinimumSet() { }, }, }, + NetworkAPIVersion: to.Ptr(armcomputefleet.NetworkAPIVersion("2022-07-01")), }, }, ComputeAPIVersion: to.Ptr("2023-09-01"), @@ -988,6 +991,7 @@ func ExampleFleetsClient_BeginCreateOrUpdate_fleetsCreateOrUpdateMinimumSet() { // }, // }, // }, + // NetworkAPIVersion: to.Ptr(armcomputefleet.NetworkAPIVersion("2022-07-01")), // }, // }, // ComputeAPIVersion: to.Ptr("2023-09-01"), @@ -1208,6 +1212,7 @@ func ExampleFleetsClient_Get() { // DeleteOption: to.Ptr(armcomputefleet.DiskDeleteOptionTypesDelete), // }, // }, + // DiskControllerType: to.Ptr(armcomputefleet.DiskControllerTypes("uzb")), // }, // NetworkProfile: &armcomputefleet.VirtualMachineScaleSetNetworkProfile{ // HealthProbe: &armcomputefleet.APIEntityReference{ @@ -1627,6 +1632,7 @@ func ExampleFleetsClient_NewListByResourceGroupPager() { // DeleteOption: to.Ptr(armcomputefleet.DiskDeleteOptionTypesDelete), // }, // }, + // DiskControllerType: to.Ptr(armcomputefleet.DiskControllerTypes("uzb")), // }, // NetworkProfile: &armcomputefleet.VirtualMachineScaleSetNetworkProfile{ // HealthProbe: &armcomputefleet.APIEntityReference{ @@ -2050,6 +2056,7 @@ func ExampleFleetsClient_NewListBySubscriptionPager() { // DeleteOption: to.Ptr(armcomputefleet.DiskDeleteOptionTypesDelete), // }, // }, + // DiskControllerType: to.Ptr(armcomputefleet.DiskControllerTypes("uzb")), // }, // NetworkProfile: &armcomputefleet.VirtualMachineScaleSetNetworkProfile{ // HealthProbe: &armcomputefleet.APIEntityReference{ @@ -2313,7 +2320,6 @@ func ExampleFleetsClient_NewListVirtualMachineScaleSetsPager() { // VirtualMachineScaleSetListResult: armcomputefleet.VirtualMachineScaleSetListResult{ // Value: []*armcomputefleet.VirtualMachineScaleSet{ // { - // Name: to.Ptr("myVmss"), // ID: to.Ptr("/subscriptions/7B0CD4DB-3381-4013-9B31-FB6E6FD0FF1C/resourceGroups/rgazurefleet/providers/Microsoft.AzureFleet/fleets/myFleet/virtualMachineScaleSets/myVmss"), // Type: to.Ptr("Microsoft.AzureFleet/fleets/virtualMachineScaleSets"), // OperationStatus: to.Ptr(armcomputefleet.ProvisioningStateCreating), @@ -2518,6 +2524,7 @@ func ExampleFleetsClient_BeginUpdate() { DeleteOption: to.Ptr(armcomputefleet.DiskDeleteOptionTypesDelete), }, }, + DiskControllerType: to.Ptr(armcomputefleet.DiskControllerTypes("uzb")), }, NetworkProfile: &armcomputefleet.VirtualMachineScaleSetNetworkProfile{ HealthProbe: &armcomputefleet.APIEntityReference{ @@ -2884,6 +2891,7 @@ func ExampleFleetsClient_BeginUpdate() { // DeleteOption: to.Ptr(armcomputefleet.DiskDeleteOptionTypesDelete), // }, // }, + // DiskControllerType: to.Ptr(armcomputefleet.DiskControllerTypes("uzb")), // }, // NetworkProfile: &armcomputefleet.VirtualMachineScaleSetNetworkProfile{ // HealthProbe: &armcomputefleet.APIEntityReference{ diff --git a/sdk/resourcemanager/computefleet/armcomputefleet/go.mod b/sdk/resourcemanager/computefleet/armcomputefleet/go.mod index 67c3d9b64fab..f67046b16310 100644 --- a/sdk/resourcemanager/computefleet/armcomputefleet/go.mod +++ b/sdk/resourcemanager/computefleet/armcomputefleet/go.mod @@ -1,4 +1,4 @@ -module github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/computefleet/armcomputefleet +module github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/computefleet/armcomputefleet/v2 go 1.23.0 diff --git a/sdk/resourcemanager/computefleet/armcomputefleet/models.go b/sdk/resourcemanager/computefleet/armcomputefleet/models.go index caf2d6bf4392..4b7af780c514 100644 --- a/sdk/resourcemanager/computefleet/armcomputefleet/models.go +++ b/sdk/resourcemanager/computefleet/armcomputefleet/models.go @@ -117,9 +117,9 @@ type BaseVirtualMachineProfile struct { // Server operating system are:

RHEL_BYOS (for RHEL)

SLES_BYOS // (for SUSE)

For more information, see [Azure Hybrid Use Benefit for // Windows - // Server](https://docs.microsoft.com/azure/virtual-machines/windows/hybrid-use-benefit-licensing) + // Server](https://learn.microsoft.com/azure/virtual-machines/windows/hybrid-use-benefit-licensing) //

[Azure Hybrid Use Benefit for Linux - // Server](https://docs.microsoft.com/azure/virtual-machines/linux/azure-hybrid-benefit-linux) + // Server](https://learn.microsoft.com/azure/virtual-machines/linux/azure-hybrid-benefit-linux) //

Minimum api-version: 2015-06-15 LicenseType *string @@ -229,8 +229,8 @@ type DiffDiskSettings struct { // values are: **CacheDisk,** **ResourceDisk.** The defaulting behavior is: // **CacheDisk** if one is configured for the VM size otherwise **ResourceDisk** // is used. Refer to the VM size documentation for Windows VM at - // https://docs.microsoft.com/azure/virtual-machines/windows/sizes and Linux VM at - // https://docs.microsoft.com/azure/virtual-machines/linux/sizes to check which VM + // https://learn.microsoft.com/azure/virtual-machines/windows/sizes and Linux VM at + // https://learn.microsoft.com/azure/virtual-machines/linux/sizes to check which VM // sizes exposes a cache disk. Placement *DiffDiskPlacement } @@ -403,7 +403,7 @@ type KeyVaultSecretReference struct { // LinuxConfiguration - Specifies the Linux operating system settings on the virtual machine. For a // list of supported Linux distributions, see [Linux on Azure-Endorsed -// Distributions](https://docs.microsoft.com/azure/virtual-machines/linux/endorsed-distros). +// Distributions](https://learn.microsoft.com/azure/virtual-machines/linux/endorsed-distros). type LinuxConfiguration struct { // Specifies whether password authentication should be disabled. DisablePasswordAuthentication *bool @@ -509,12 +509,12 @@ type OSImageNotificationProfile struct { // Operation - Details of a REST API operation, returned from the Resource Provider Operations API type Operation struct { - // Extensible enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. - ActionType *ActionType - - // READ-ONLY; Localized display information for this particular operation. + // Localized display information for this particular operation. Display *OperationDisplay + // READ-ONLY; Extensible 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 Azure // Resource Manager/control-plane operations. IsDataAction *bool @@ -679,7 +679,7 @@ type SSHPublicKey struct { // SSH public key certificate used to authenticate with the VM through ssh. The // key needs to be at least 2048-bit and in ssh-rsa format. For creating ssh keys, // see [Create SSH keys on Linux and Mac for Linux VMs in - // Azure]https://docs.microsoft.com/azure/virtual-machines/linux/create-ssh-keys-detailed). + // Azure]https://learn.microsoft.com/azure/virtual-machines/linux/create-ssh-keys-detailed). KeyData *string // Specifies the full path on the created VM where ssh public key is stored. If @@ -908,6 +908,7 @@ type VMAttributes struct { LocalStorageInGiB *VMAttributeMinMaxDouble // Specifies whether the VMSize supporting local storage should be used to build Fleet or not. + // Included - Default if not specified as most Azure VMs support local storage. LocalStorageSupport *VMAttributeSupport // The range of memory in GiB per vCPU specified from min to max. Optional parameter. Either Min or Max is required if specified. @@ -991,14 +992,14 @@ type VMSizeProperties struct { // specified in the request body the default behavior is to set it to the value of // vCPUs available for that VM size exposed in api response of [List all available // virtual machine sizes in a - // region](https://docs.microsoft.com/en-us/rest/api/compute/resource-skus/list). + // region](https://learn.microsoft.com/en-us/rest/api/compute/resource-skus/list). VCPUsAvailable *int32 // Specifies the vCPU to physical core ratio. When this property is not specified // in the request body the default behavior is set to the value of vCPUsPerCore // for the VM Size exposed in api response of [List all available virtual machine // sizes in a - // region](https://docs.microsoft.com/en-us/rest/api/compute/resource-skus/list). + // region](https://learn.microsoft.com/en-us/rest/api/compute/resource-skus/list). // **Setting this property to 1 also means that hyper-threading is disabled.** VCPUsPerCore *int32 } @@ -1018,16 +1019,16 @@ type VaultCertificate struct { // This is the URL of a certificate that has been uploaded to Key Vault as a // secret. For adding a secret to the Key Vault, see [Add a key or secret to the // key - // vault](https://docs.microsoft.com/azure/key-vault/key-vault-get-started/#add). + // vault](https://learn.microsoft.com/azure/key-vault/key-vault-get-started/#add). // In this case, your certificate needs to be It is the Base64 encoding of the // following JSON Object which is encoded in UTF-8:

{
// "data":"",
"dataType":"pfx",
// "password":""
}
To install certificates on a virtual // machine it is recommended to use the [Azure Key Vault virtual machine extension // for - // Linux](https://docs.microsoft.com/azure/virtual-machines/extensions/key-vault-linux) + // Linux](https://learn.microsoft.com/azure/virtual-machines/extensions/key-vault-linux) // or the [Azure Key Vault virtual machine extension for - // Windows](https://docs.microsoft.com/azure/virtual-machines/extensions/key-vault-windows). + // Windows](https://learn.microsoft.com/azure/virtual-machines/extensions/key-vault-windows). CertificateURL *string } @@ -1419,10 +1420,10 @@ type VirtualMachineScaleSetOSProfile struct { // "P@ssword123", "Pa$$word", "pass@word1", "Password!", "Password1", // "Password22", "iloveyou!"

For resetting the password, see [How to // reset the Remote Desktop service or its login password in a Windows - // VM](https://docs.microsoft.com/troubleshoot/azure/virtual-machines/reset-rdp) + // VM](https://learn.microsoft.com/troubleshoot/azure/virtual-machines/reset-rdp) //

For resetting root password, see [Manage users, SSH, and check or // repair disks on Azure Linux VMs using the VMAccess - // Extension](https://docs.microsoft.com/troubleshoot/azure/virtual-machines/troubleshoot-ssh-connection) + // Extension](https://learn.microsoft.com/troubleshoot/azure/virtual-machines/troubleshoot-ssh-connection) AdminPassword *string // Specifies the name of the administrator account.

**Windows-only @@ -1448,12 +1449,12 @@ type VirtualMachineScaleSetOSProfile struct { // is decoded to a binary array that is saved as a file on the Virtual Machine. // The maximum length of the binary array is 65535 bytes. For using cloud-init for // your VM, see [Using cloud-init to customize a Linux VM during - // creation](https://docs.microsoft.com/azure/virtual-machines/linux/using-cloud-init) + // creation](https://learn.microsoft.com/azure/virtual-machines/linux/using-cloud-init) CustomData *string // Specifies the Linux operating system settings on the virtual machine. For a // list of supported Linux distributions, see [Linux on Azure-Endorsed - // Distributions](https://docs.microsoft.com/azure/virtual-machines/linux/endorsed-distros). + // Distributions](https://learn.microsoft.com/azure/virtual-machines/linux/endorsed-distros). LinuxConfiguration *LinuxConfiguration // Optional property which must either be set to True or omitted. @@ -1462,9 +1463,9 @@ type VirtualMachineScaleSetOSProfile struct { // Specifies set of certificates that should be installed onto the virtual // machines in the scale set. To install certificates on a virtual machine it is // recommended to use the [Azure Key Vault virtual machine extension for - // Linux](https://docs.microsoft.com/azure/virtual-machines/extensions/key-vault-linux) + // Linux](https://learn.microsoft.com/azure/virtual-machines/extensions/key-vault-linux) // or the [Azure Key Vault virtual machine extension for - // Windows](https://docs.microsoft.com/azure/virtual-machines/extensions/key-vault-windows). + // Windows](https://learn.microsoft.com/azure/virtual-machines/extensions/key-vault-windows). Secrets []*VaultSecretGroup // Specifies Windows operating system settings on the virtual machine. @@ -1531,7 +1532,7 @@ type VirtualMachineScaleSetStorageProfile struct { // Specifies the parameters that are used to add data disks to the virtual // machines in the scale set. For more information about disks, see [About disks // and VHDs for Azure virtual - // machines](https://docs.microsoft.com/azure/virtual-machines/managed-disks-overview). + // machines](https://learn.microsoft.com/azure/virtual-machines/managed-disks-overview). DataDisks []*VirtualMachineScaleSetDataDisk // Specifies the disk controller type configured for the virtual machines in the scale set. Minimum api-version: 2022-08-01 @@ -1546,7 +1547,7 @@ type VirtualMachineScaleSetStorageProfile struct { // Specifies information about the operating system disk used by the virtual // machines in the scale set. For more information about disks, see [About disks // and VHDs for Azure virtual - // machines](https://docs.microsoft.com/azure/virtual-machines/managed-disks-overview). + // machines](https://learn.microsoft.com/azure/virtual-machines/managed-disks-overview). OSDisk *VirtualMachineScaleSetOSDisk } @@ -1561,16 +1562,16 @@ type WinRMListener struct { // This is the URL of a certificate that has been uploaded to Key Vault as a // secret. For adding a secret to the Key Vault, see [Add a key or secret to the // key - // vault](https://docs.microsoft.com/azure/key-vault/key-vault-get-started/#add). + // vault](https://learn.microsoft.com/azure/key-vault/key-vault-get-started/#add). // In this case, your certificate needs to be the Base64 encoding of the following // JSON Object which is encoded in UTF-8:

{
// "data":"",
"dataType":"pfx",
// "password":""
}
To install certificates on a virtual // machine it is recommended to use the [Azure Key Vault virtual machine extension // for - // Linux](https://docs.microsoft.com/azure/virtual-machines/extensions/key-vault-linux) + // Linux](https://learn.microsoft.com/azure/virtual-machines/extensions/key-vault-linux) // or the [Azure Key Vault virtual machine extension for - // Windows](https://docs.microsoft.com/azure/virtual-machines/extensions/key-vault-windows). + // Windows](https://learn.microsoft.com/azure/virtual-machines/extensions/key-vault-windows). CertificateURL *string // Specifies the protocol of WinRM listener. Possible values are: **http,** @@ -1604,9 +1605,9 @@ type WindowsConfiguration struct { // Specifies the time zone of the virtual machine. e.g. "Pacific Standard Time". // Possible values can be - // [TimeZoneInfo.Id](https://docs.microsoft.com/dotnet/api/system.timezoneinfo.id?#System_TimeZoneInfo_Id) + // [TimeZoneInfo.Id](https://learn.microsoft.com/dotnet/api/system.timezoneinfo.id?#System_TimeZoneInfo_Id) // value from time zones returned by - // [TimeZoneInfo.GetSystemTimeZones](https://docs.microsoft.com/dotnet/api/system.timezoneinfo.getsystemtimezones). + // [TimeZoneInfo.GetSystemTimeZones](https://learn.microsoft.com/dotnet/api/system.timezoneinfo.getsystemtimezones). TimeZone *string // Specifies the Windows Remote Management listeners. This enables remote Windows diff --git a/sdk/resourcemanager/computefleet/armcomputefleet/operations_client_example_test.go b/sdk/resourcemanager/computefleet/armcomputefleet/operations_client_example_test.go index 9ba1df570e27..306f65f68a20 100644 --- a/sdk/resourcemanager/computefleet/armcomputefleet/operations_client_example_test.go +++ b/sdk/resourcemanager/computefleet/armcomputefleet/operations_client_example_test.go @@ -7,7 +7,7 @@ package armcomputefleet_test import ( "context" "github.com/Azure/azure-sdk-for-go/sdk/azidentity" - "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/computefleet/armcomputefleet" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/computefleet/armcomputefleet/v2" "log" ) diff --git a/sdk/resourcemanager/computefleet/armcomputefleet/tsp-location.yaml b/sdk/resourcemanager/computefleet/armcomputefleet/tsp-location.yaml index c8d950e137b2..1b000b9e867b 100644 --- a/sdk/resourcemanager/computefleet/armcomputefleet/tsp-location.yaml +++ b/sdk/resourcemanager/computefleet/armcomputefleet/tsp-location.yaml @@ -1,4 +1,4 @@ directory: specification/azurefleet/AzureFleet.Management -commit: c120171b3684d88562fa26ae7db5d22b7bfa95d8 +commit: 1f578543d267d08febc1bebf4e33ffe14363ddfc repo: Azure/azure-rest-api-specs additionalDirectories: diff --git a/sdk/resourcemanager/computeschedule/armcomputeschedule/CHANGELOG.md b/sdk/resourcemanager/computeschedule/armcomputeschedule/CHANGELOG.md index 05bafe390c04..b5434ac307dd 100644 --- a/sdk/resourcemanager/computeschedule/armcomputeschedule/CHANGELOG.md +++ b/sdk/resourcemanager/computeschedule/armcomputeschedule/CHANGELOG.md @@ -1,5 +1,21 @@ # Release History +## 1.1.0 (2025-04-27) +### Features Added + +- New function `*ScheduledActionsClient.VirtualMachinesExecuteCreate(context.Context, string, ExecuteCreateRequest, *ScheduledActionsClientVirtualMachinesExecuteCreateOptions) (ScheduledActionsClientVirtualMachinesExecuteCreateResponse, error)` +- New function `*ScheduledActionsClient.VirtualMachinesExecuteDelete(context.Context, string, ExecuteDeleteRequest, *ScheduledActionsClientVirtualMachinesExecuteDeleteOptions) (ScheduledActionsClientVirtualMachinesExecuteDeleteResponse, error)` +- New function `*ScheduledActionsClient.VirtualMachinesSubmitCreate(context.Context, string, SubmitCreateRequest, *ScheduledActionsClientVirtualMachinesSubmitCreateOptions) (ScheduledActionsClientVirtualMachinesSubmitCreateResponse, error)` +- New function `*ScheduledActionsClient.VirtualMachinesSubmitDelete(context.Context, string, SubmitDeleteRequest, *ScheduledActionsClientVirtualMachinesSubmitDeleteOptions) (ScheduledActionsClientVirtualMachinesSubmitDeleteResponse, error)` +- New struct `CreateResourceOperationResponse` +- New struct `DeleteResourceOperationResponse` +- New struct `ExecuteCreateRequest` +- New struct `ExecuteDeleteRequest` +- New struct `ResourceProvisionPayload` +- New struct `SubmitCreateRequest` +- New struct `SubmitDeleteRequest` + + ## 1.0.0 (2025-01-24) ### Breaking Changes diff --git a/sdk/resourcemanager/computeschedule/armcomputeschedule/autorest.md b/sdk/resourcemanager/computeschedule/armcomputeschedule/autorest.md deleted file mode 100644 index ed1d8d0e071a..000000000000 --- a/sdk/resourcemanager/computeschedule/armcomputeschedule/autorest.md +++ /dev/null @@ -1,13 +0,0 @@ -### AutoRest Configuration - -> see https://aka.ms/autorest - -``` yaml -azure-arm: true -require: -- https://github.com/Azure/azure-rest-api-specs/blob/8a4eca6b060cf70da696963245656fdc440b666b/specification/computeschedule/resource-manager/readme.md -- https://github.com/Azure/azure-rest-api-specs/blob/8a4eca6b060cf70da696963245656fdc440b666b/specification/computeschedule/resource-manager/readme.go.md -license-header: MICROSOFT_MIT_NO_VERSION -module-version: 1.0.0 -tag: package-2024-10-01 -``` \ No newline at end of file diff --git a/sdk/resourcemanager/computeschedule/armcomputeschedule/build.go b/sdk/resourcemanager/computeschedule/armcomputeschedule/build.go deleted file mode 100644 index 62d8e2521509..000000000000 --- a/sdk/resourcemanager/computeschedule/armcomputeschedule/build.go +++ /dev/null @@ -1,7 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. - -// This file enables 'go generate' to regenerate this specific SDK -//go:generate pwsh ../../../../eng/scripts/build.ps1 -skipBuild -cleanGenerated -format -tidy -generate -alwaysSetBodyParamRequired -removeUnreferencedTypes resourcemanager/computeschedule/armcomputeschedule - -package armcomputeschedule diff --git a/sdk/resourcemanager/computeschedule/armcomputeschedule/client_factory.go b/sdk/resourcemanager/computeschedule/armcomputeschedule/client_factory.go index f3b18164ab51..7bbcc1b6db88 100644 --- a/sdk/resourcemanager/computeschedule/armcomputeschedule/client_factory.go +++ b/sdk/resourcemanager/computeschedule/armcomputeschedule/client_factory.go @@ -1,10 +1,6 @@ -//go:build go1.18 -// +build go1.18 - // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. -// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. package armcomputeschedule diff --git a/sdk/resourcemanager/computeschedule/armcomputeschedule/constants.go b/sdk/resourcemanager/computeschedule/armcomputeschedule/constants.go index 373c327a661b..1721c38226dc 100644 --- a/sdk/resourcemanager/computeschedule/armcomputeschedule/constants.go +++ b/sdk/resourcemanager/computeschedule/armcomputeschedule/constants.go @@ -1,22 +1,19 @@ -//go:build go1.18 -// +build go1.18 - // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. -// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. package armcomputeschedule const ( moduleName = "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/computeschedule/armcomputeschedule" - moduleVersion = "v1.0.0" + moduleVersion = "v1.1.0" ) -// ActionType - Enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. +// ActionType - Extensible enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. type ActionType string const ( + // ActionTypeInternal - Actions are for internal-only APIs. ActionTypeInternal ActionType = "Internal" ) @@ -113,8 +110,11 @@ func PossibleOptimizationPreferenceValues() []OptimizationPreference { type Origin string const ( - OriginSystem Origin = "system" - OriginUser Origin = "user" + // OriginSystem - Indicates the operation is initiated by a system. + OriginSystem Origin = "system" + // OriginUser - Indicates the operation is initiated by a user. + OriginUser Origin = "user" + // OriginUserSystem - Indicates the operation is initiated by a user or system. OriginUserSystem Origin = "user,system" ) @@ -127,7 +127,7 @@ func PossibleOriginValues() []Origin { } } -// ResourceOperationType - Type of operation performed on the resources +// ResourceOperationType - The kind of operation types that can be performed on resources using ScheduledActions type ResourceOperationType string const ( diff --git a/sdk/resourcemanager/computeschedule/armcomputeschedule/fake/internal.go b/sdk/resourcemanager/computeschedule/armcomputeschedule/fake/internal.go index 5f75802a569e..7425b6a669e2 100644 --- a/sdk/resourcemanager/computeschedule/armcomputeschedule/fake/internal.go +++ b/sdk/resourcemanager/computeschedule/armcomputeschedule/fake/internal.go @@ -1,10 +1,6 @@ -//go:build go1.18 -// +build go1.18 - // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. -// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. package fake @@ -14,6 +10,11 @@ import ( "sync" ) +type result struct { + resp *http.Response + err error +} + type nonRetriableError struct { error } diff --git a/sdk/resourcemanager/computeschedule/armcomputeschedule/fake/operations_server.go b/sdk/resourcemanager/computeschedule/armcomputeschedule/fake/operations_server.go index 0e47f1aeeaef..83f02b372d8b 100644 --- a/sdk/resourcemanager/computeschedule/armcomputeschedule/fake/operations_server.go +++ b/sdk/resourcemanager/computeschedule/armcomputeschedule/fake/operations_server.go @@ -1,10 +1,6 @@ -//go:build go1.18 -// +build go1.18 - // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. -// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. package fake @@ -51,21 +47,40 @@ func (o *OperationsServerTransport) Do(req *http.Request) (*http.Response, error return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} } - var resp *http.Response - var err error + return o.dispatchToMethodFake(req, method) +} - switch method { - case "OperationsClient.NewListPager": - resp, err = o.dispatchNewListPager(req) - default: - err = fmt.Errorf("unhandled API %s", method) - } +func (o *OperationsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result) + defer close(resultChan) - if err != nil { - return nil, err - } + go func() { + var intercepted bool + var res result + if operationsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = operationsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "OperationsClient.NewListPager": + res.resp, res.err = o.dispatchNewListPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } - return resp, nil + } + select { + case resultChan <- res: + case <-req.Context().Done(): + } + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } } func (o *OperationsServerTransport) dispatchNewListPager(req *http.Request) (*http.Response, error) { @@ -94,3 +109,9 @@ func (o *OperationsServerTransport) dispatchNewListPager(req *http.Request) (*ht } return resp, nil } + +// set this to conditionally intercept incoming requests to OperationsServerTransport +var operationsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/sdk/resourcemanager/computeschedule/armcomputeschedule/fake/scheduledactions_server.go b/sdk/resourcemanager/computeschedule/armcomputeschedule/fake/scheduledactions_server.go index bed1392f6310..fe669e311d2f 100644 --- a/sdk/resourcemanager/computeschedule/armcomputeschedule/fake/scheduledactions_server.go +++ b/sdk/resourcemanager/computeschedule/armcomputeschedule/fake/scheduledactions_server.go @@ -1,10 +1,6 @@ -//go:build go1.18 -// +build go1.18 - // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. -// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. package fake @@ -27,10 +23,18 @@ type ScheduledActionsServer struct { // HTTP status codes to indicate success: http.StatusOK VirtualMachinesCancelOperations func(ctx context.Context, locationparameter string, requestBody armcomputeschedule.CancelOperationsRequest, options *armcomputeschedule.ScheduledActionsClientVirtualMachinesCancelOperationsOptions) (resp azfake.Responder[armcomputeschedule.ScheduledActionsClientVirtualMachinesCancelOperationsResponse], errResp azfake.ErrorResponder) + // VirtualMachinesExecuteCreate is the fake for method ScheduledActionsClient.VirtualMachinesExecuteCreate + // HTTP status codes to indicate success: http.StatusOK + VirtualMachinesExecuteCreate func(ctx context.Context, locationparameter string, requestBody armcomputeschedule.ExecuteCreateRequest, options *armcomputeschedule.ScheduledActionsClientVirtualMachinesExecuteCreateOptions) (resp azfake.Responder[armcomputeschedule.ScheduledActionsClientVirtualMachinesExecuteCreateResponse], errResp azfake.ErrorResponder) + // VirtualMachinesExecuteDeallocate is the fake for method ScheduledActionsClient.VirtualMachinesExecuteDeallocate // HTTP status codes to indicate success: http.StatusOK VirtualMachinesExecuteDeallocate func(ctx context.Context, locationparameter string, requestBody armcomputeschedule.ExecuteDeallocateRequest, options *armcomputeschedule.ScheduledActionsClientVirtualMachinesExecuteDeallocateOptions) (resp azfake.Responder[armcomputeschedule.ScheduledActionsClientVirtualMachinesExecuteDeallocateResponse], errResp azfake.ErrorResponder) + // VirtualMachinesExecuteDelete is the fake for method ScheduledActionsClient.VirtualMachinesExecuteDelete + // HTTP status codes to indicate success: http.StatusOK + VirtualMachinesExecuteDelete func(ctx context.Context, locationparameter string, requestBody armcomputeschedule.ExecuteDeleteRequest, options *armcomputeschedule.ScheduledActionsClientVirtualMachinesExecuteDeleteOptions) (resp azfake.Responder[armcomputeschedule.ScheduledActionsClientVirtualMachinesExecuteDeleteResponse], errResp azfake.ErrorResponder) + // VirtualMachinesExecuteHibernate is the fake for method ScheduledActionsClient.VirtualMachinesExecuteHibernate // HTTP status codes to indicate success: http.StatusOK VirtualMachinesExecuteHibernate func(ctx context.Context, locationparameter string, requestBody armcomputeschedule.ExecuteHibernateRequest, options *armcomputeschedule.ScheduledActionsClientVirtualMachinesExecuteHibernateOptions) (resp azfake.Responder[armcomputeschedule.ScheduledActionsClientVirtualMachinesExecuteHibernateResponse], errResp azfake.ErrorResponder) @@ -47,10 +51,18 @@ type ScheduledActionsServer struct { // HTTP status codes to indicate success: http.StatusOK VirtualMachinesGetOperationStatus func(ctx context.Context, locationparameter string, requestBody armcomputeschedule.GetOperationStatusRequest, options *armcomputeschedule.ScheduledActionsClientVirtualMachinesGetOperationStatusOptions) (resp azfake.Responder[armcomputeschedule.ScheduledActionsClientVirtualMachinesGetOperationStatusResponse], errResp azfake.ErrorResponder) + // VirtualMachinesSubmitCreate is the fake for method ScheduledActionsClient.VirtualMachinesSubmitCreate + // HTTP status codes to indicate success: http.StatusOK + VirtualMachinesSubmitCreate func(ctx context.Context, locationparameter string, requestBody armcomputeschedule.SubmitCreateRequest, options *armcomputeschedule.ScheduledActionsClientVirtualMachinesSubmitCreateOptions) (resp azfake.Responder[armcomputeschedule.ScheduledActionsClientVirtualMachinesSubmitCreateResponse], errResp azfake.ErrorResponder) + // VirtualMachinesSubmitDeallocate is the fake for method ScheduledActionsClient.VirtualMachinesSubmitDeallocate // HTTP status codes to indicate success: http.StatusOK VirtualMachinesSubmitDeallocate func(ctx context.Context, locationparameter string, requestBody armcomputeschedule.SubmitDeallocateRequest, options *armcomputeschedule.ScheduledActionsClientVirtualMachinesSubmitDeallocateOptions) (resp azfake.Responder[armcomputeschedule.ScheduledActionsClientVirtualMachinesSubmitDeallocateResponse], errResp azfake.ErrorResponder) + // VirtualMachinesSubmitDelete is the fake for method ScheduledActionsClient.VirtualMachinesSubmitDelete + // HTTP status codes to indicate success: http.StatusOK + VirtualMachinesSubmitDelete func(ctx context.Context, locationparameter string, requestBody armcomputeschedule.SubmitDeleteRequest, options *armcomputeschedule.ScheduledActionsClientVirtualMachinesSubmitDeleteOptions) (resp azfake.Responder[armcomputeschedule.ScheduledActionsClientVirtualMachinesSubmitDeleteResponse], errResp azfake.ErrorResponder) + // VirtualMachinesSubmitHibernate is the fake for method ScheduledActionsClient.VirtualMachinesSubmitHibernate // HTTP status codes to indicate success: http.StatusOK VirtualMachinesSubmitHibernate func(ctx context.Context, locationparameter string, requestBody armcomputeschedule.SubmitHibernateRequest, options *armcomputeschedule.ScheduledActionsClientVirtualMachinesSubmitHibernateOptions) (resp azfake.Responder[armcomputeschedule.ScheduledActionsClientVirtualMachinesSubmitHibernateResponse], errResp azfake.ErrorResponder) @@ -81,37 +93,64 @@ func (s *ScheduledActionsServerTransport) Do(req *http.Request) (*http.Response, return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} } - var resp *http.Response - var err error + return s.dispatchToMethodFake(req, method) +} - switch method { - case "ScheduledActionsClient.VirtualMachinesCancelOperations": - resp, err = s.dispatchVirtualMachinesCancelOperations(req) - case "ScheduledActionsClient.VirtualMachinesExecuteDeallocate": - resp, err = s.dispatchVirtualMachinesExecuteDeallocate(req) - case "ScheduledActionsClient.VirtualMachinesExecuteHibernate": - resp, err = s.dispatchVirtualMachinesExecuteHibernate(req) - case "ScheduledActionsClient.VirtualMachinesExecuteStart": - resp, err = s.dispatchVirtualMachinesExecuteStart(req) - case "ScheduledActionsClient.VirtualMachinesGetOperationErrors": - resp, err = s.dispatchVirtualMachinesGetOperationErrors(req) - case "ScheduledActionsClient.VirtualMachinesGetOperationStatus": - resp, err = s.dispatchVirtualMachinesGetOperationStatus(req) - case "ScheduledActionsClient.VirtualMachinesSubmitDeallocate": - resp, err = s.dispatchVirtualMachinesSubmitDeallocate(req) - case "ScheduledActionsClient.VirtualMachinesSubmitHibernate": - resp, err = s.dispatchVirtualMachinesSubmitHibernate(req) - case "ScheduledActionsClient.VirtualMachinesSubmitStart": - resp, err = s.dispatchVirtualMachinesSubmitStart(req) - default: - err = fmt.Errorf("unhandled API %s", method) - } +func (s *ScheduledActionsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result) + defer close(resultChan) - if err != nil { - return nil, err - } + go func() { + var intercepted bool + var res result + if scheduledActionsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = scheduledActionsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ScheduledActionsClient.VirtualMachinesCancelOperations": + res.resp, res.err = s.dispatchVirtualMachinesCancelOperations(req) + case "ScheduledActionsClient.VirtualMachinesExecuteCreate": + res.resp, res.err = s.dispatchVirtualMachinesExecuteCreate(req) + case "ScheduledActionsClient.VirtualMachinesExecuteDeallocate": + res.resp, res.err = s.dispatchVirtualMachinesExecuteDeallocate(req) + case "ScheduledActionsClient.VirtualMachinesExecuteDelete": + res.resp, res.err = s.dispatchVirtualMachinesExecuteDelete(req) + case "ScheduledActionsClient.VirtualMachinesExecuteHibernate": + res.resp, res.err = s.dispatchVirtualMachinesExecuteHibernate(req) + case "ScheduledActionsClient.VirtualMachinesExecuteStart": + res.resp, res.err = s.dispatchVirtualMachinesExecuteStart(req) + case "ScheduledActionsClient.VirtualMachinesGetOperationErrors": + res.resp, res.err = s.dispatchVirtualMachinesGetOperationErrors(req) + case "ScheduledActionsClient.VirtualMachinesGetOperationStatus": + res.resp, res.err = s.dispatchVirtualMachinesGetOperationStatus(req) + case "ScheduledActionsClient.VirtualMachinesSubmitCreate": + res.resp, res.err = s.dispatchVirtualMachinesSubmitCreate(req) + case "ScheduledActionsClient.VirtualMachinesSubmitDeallocate": + res.resp, res.err = s.dispatchVirtualMachinesSubmitDeallocate(req) + case "ScheduledActionsClient.VirtualMachinesSubmitDelete": + res.resp, res.err = s.dispatchVirtualMachinesSubmitDelete(req) + case "ScheduledActionsClient.VirtualMachinesSubmitHibernate": + res.resp, res.err = s.dispatchVirtualMachinesSubmitHibernate(req) + case "ScheduledActionsClient.VirtualMachinesSubmitStart": + res.resp, res.err = s.dispatchVirtualMachinesSubmitStart(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } - return resp, nil + } + select { + case resultChan <- res: + case <-req.Context().Done(): + } + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } } func (s *ScheduledActionsServerTransport) dispatchVirtualMachinesCancelOperations(req *http.Request) (*http.Response, error) { @@ -147,6 +186,39 @@ func (s *ScheduledActionsServerTransport) dispatchVirtualMachinesCancelOperation return resp, nil } +func (s *ScheduledActionsServerTransport) dispatchVirtualMachinesExecuteCreate(req *http.Request) (*http.Response, error) { + if s.srv.VirtualMachinesExecuteCreate == nil { + return nil, &nonRetriableError{errors.New("fake for method VirtualMachinesExecuteCreate not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ComputeSchedule/locations/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/virtualMachinesExecuteCreate` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if matches == nil || len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armcomputeschedule.ExecuteCreateRequest](req) + if err != nil { + return nil, err + } + locationparameterParam, err := url.PathUnescape(matches[regex.SubexpIndex("locationparameter")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.VirtualMachinesExecuteCreate(req.Context(), locationparameterParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).CreateResourceOperationResponse, req) + if err != nil { + return nil, err + } + return resp, nil +} + func (s *ScheduledActionsServerTransport) dispatchVirtualMachinesExecuteDeallocate(req *http.Request) (*http.Response, error) { if s.srv.VirtualMachinesExecuteDeallocate == nil { return nil, &nonRetriableError{errors.New("fake for method VirtualMachinesExecuteDeallocate not implemented")} @@ -180,6 +252,39 @@ func (s *ScheduledActionsServerTransport) dispatchVirtualMachinesExecuteDealloca return resp, nil } +func (s *ScheduledActionsServerTransport) dispatchVirtualMachinesExecuteDelete(req *http.Request) (*http.Response, error) { + if s.srv.VirtualMachinesExecuteDelete == nil { + return nil, &nonRetriableError{errors.New("fake for method VirtualMachinesExecuteDelete not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ComputeSchedule/locations/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/virtualMachinesExecuteDelete` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if matches == nil || len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armcomputeschedule.ExecuteDeleteRequest](req) + if err != nil { + return nil, err + } + locationparameterParam, err := url.PathUnescape(matches[regex.SubexpIndex("locationparameter")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.VirtualMachinesExecuteDelete(req.Context(), locationparameterParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).DeleteResourceOperationResponse, req) + if err != nil { + return nil, err + } + return resp, nil +} + func (s *ScheduledActionsServerTransport) dispatchVirtualMachinesExecuteHibernate(req *http.Request) (*http.Response, error) { if s.srv.VirtualMachinesExecuteHibernate == nil { return nil, &nonRetriableError{errors.New("fake for method VirtualMachinesExecuteHibernate not implemented")} @@ -312,6 +417,39 @@ func (s *ScheduledActionsServerTransport) dispatchVirtualMachinesGetOperationSta return resp, nil } +func (s *ScheduledActionsServerTransport) dispatchVirtualMachinesSubmitCreate(req *http.Request) (*http.Response, error) { + if s.srv.VirtualMachinesSubmitCreate == nil { + return nil, &nonRetriableError{errors.New("fake for method VirtualMachinesSubmitCreate not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ComputeSchedule/locations/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/virtualMachinesSubmitCreate` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if matches == nil || len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armcomputeschedule.SubmitCreateRequest](req) + if err != nil { + return nil, err + } + locationparameterParam, err := url.PathUnescape(matches[regex.SubexpIndex("locationparameter")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.VirtualMachinesSubmitCreate(req.Context(), locationparameterParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).CreateResourceOperationResponse, req) + if err != nil { + return nil, err + } + return resp, nil +} + func (s *ScheduledActionsServerTransport) dispatchVirtualMachinesSubmitDeallocate(req *http.Request) (*http.Response, error) { if s.srv.VirtualMachinesSubmitDeallocate == nil { return nil, &nonRetriableError{errors.New("fake for method VirtualMachinesSubmitDeallocate not implemented")} @@ -345,6 +483,39 @@ func (s *ScheduledActionsServerTransport) dispatchVirtualMachinesSubmitDeallocat return resp, nil } +func (s *ScheduledActionsServerTransport) dispatchVirtualMachinesSubmitDelete(req *http.Request) (*http.Response, error) { + if s.srv.VirtualMachinesSubmitDelete == nil { + return nil, &nonRetriableError{errors.New("fake for method VirtualMachinesSubmitDelete not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ComputeSchedule/locations/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/virtualMachinesSubmitDelete` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if matches == nil || len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armcomputeschedule.SubmitDeleteRequest](req) + if err != nil { + return nil, err + } + locationparameterParam, err := url.PathUnescape(matches[regex.SubexpIndex("locationparameter")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.VirtualMachinesSubmitDelete(req.Context(), locationparameterParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).DeleteResourceOperationResponse, req) + if err != nil { + return nil, err + } + return resp, nil +} + func (s *ScheduledActionsServerTransport) dispatchVirtualMachinesSubmitHibernate(req *http.Request) (*http.Response, error) { if s.srv.VirtualMachinesSubmitHibernate == nil { return nil, &nonRetriableError{errors.New("fake for method VirtualMachinesSubmitHibernate not implemented")} @@ -410,3 +581,9 @@ func (s *ScheduledActionsServerTransport) dispatchVirtualMachinesSubmitStart(req } return resp, nil } + +// set this to conditionally intercept incoming requests to ScheduledActionsServerTransport +var scheduledActionsServerTransportInterceptor 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/computeschedule/armcomputeschedule/fake/server_factory.go b/sdk/resourcemanager/computeschedule/armcomputeschedule/fake/server_factory.go index 98595b101731..8033269bf59a 100644 --- a/sdk/resourcemanager/computeschedule/armcomputeschedule/fake/server_factory.go +++ b/sdk/resourcemanager/computeschedule/armcomputeschedule/fake/server_factory.go @@ -1,10 +1,6 @@ -//go:build go1.18 -// +build go1.18 - // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. -// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. package fake @@ -19,7 +15,10 @@ import ( // ServerFactory is a fake server for instances of the armcomputeschedule.ClientFactory type. type ServerFactory struct { - OperationsServer OperationsServer + // OperationsServer contains the fakes for client OperationsClient + OperationsServer OperationsServer + + // ScheduledActionsServer contains the fakes for client ScheduledActionsClient ScheduledActionsServer ScheduledActionsServer } diff --git a/sdk/resourcemanager/computeschedule/armcomputeschedule/fake/time_rfc3339.go b/sdk/resourcemanager/computeschedule/armcomputeschedule/fake/time_rfc3339.go index 81f308b0d343..87ee11e83b32 100644 --- a/sdk/resourcemanager/computeschedule/armcomputeschedule/fake/time_rfc3339.go +++ b/sdk/resourcemanager/computeschedule/armcomputeschedule/fake/time_rfc3339.go @@ -1,10 +1,6 @@ -//go:build go1.18 -// +build go1.18 - // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. -// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. package fake @@ -60,6 +56,9 @@ func (t *dateTimeRFC3339) UnmarshalJSON(data []byte) error { } 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 diff --git a/sdk/resourcemanager/computeschedule/armcomputeschedule/models.go b/sdk/resourcemanager/computeschedule/armcomputeschedule/models.go index 3e78e04f6504..a3baaf3b3edc 100644 --- a/sdk/resourcemanager/computeschedule/armcomputeschedule/models.go +++ b/sdk/resourcemanager/computeschedule/armcomputeschedule/models.go @@ -1,10 +1,6 @@ -//go:build go1.18 -// +build go1.18 - // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. -// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. package armcomputeschedule @@ -25,6 +21,21 @@ type CancelOperationsResponse struct { Results []*ResourceOperation } +// CreateResourceOperationResponse - The response from a create request +type CreateResourceOperationResponse struct { + // REQUIRED; The description of the operation response + Description *string + + // REQUIRED; The location of the start request eg westus + Location *string + + // REQUIRED; The type of resources used in the create request eg virtual machines + Type *string + + // The results from the start request if no errors exist + Results []*ResourceOperation +} + // DeallocateResourceOperationResponse - The response from a deallocate request type DeallocateResourceOperationResponse struct { // REQUIRED; The description of the operation response @@ -40,6 +51,33 @@ type DeallocateResourceOperationResponse struct { Results []*ResourceOperation } +// DeleteResourceOperationResponse - The response from a delete request +type DeleteResourceOperationResponse struct { + // REQUIRED; The description of the operation response + Description *string + + // REQUIRED; The location of the start request eg westus + Location *string + + // REQUIRED; The type of resources used in the delete request eg virtual machines + Type *string + + // The results from the start request if no errors exist + Results []*ResourceOperation +} + +// ExecuteCreateRequest - The ExecuteCreateRequest request for create operations +type ExecuteCreateRequest struct { + // REQUIRED; The execution parameters for the request + ExecutionParameters *ExecutionParameters + + // REQUIRED; resource creation payload + ResourceConfigParameters *ResourceProvisionPayload + + // CorrelationId item + Correlationid *string +} + // ExecuteDeallocateRequest - The ExecuteDeallocateRequest request for executeDeallocate operations type ExecuteDeallocateRequest struct { // REQUIRED; CorrelationId item @@ -52,6 +90,21 @@ type ExecuteDeallocateRequest struct { Resources *Resources } +// ExecuteDeleteRequest - The ExecuteDeleteRequest request for delete operations +type ExecuteDeleteRequest struct { + // REQUIRED; The execution parameters for the request + ExecutionParameters *ExecutionParameters + + // REQUIRED; The resources for the request + Resources *Resources + + // CorrelationId item + Correlationid *string + + // Forced delete resource item + ForceDeletion *bool +} + // ExecuteHibernateRequest - The ExecuteHibernateRequest request for executeHibernate operations type ExecuteHibernateRequest struct { // REQUIRED; CorrelationId item @@ -132,11 +185,11 @@ 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. + // READ-ONLY; Extensible 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. + // READ-ONLY; Whether the operation applies to data-plane. This is "true" for data-plane operations and "false" for Azure + // Resource Manager/control-plane operations. IsDataAction *bool // READ-ONLY; The name of the operation, as per Resource-Based Access Control (RBAC). Examples: "Microsoft.Compute/virtualMachines/write", @@ -148,7 +201,7 @@ type Operation struct { Origin *Origin } -// OperationDisplay - Localized display information for this particular operation. +// OperationDisplay - Localized display information for and operation. type OperationDisplay struct { // READ-ONLY; The short, localized friendly description of the operation; suitable for tool tips and detailed views. Description *string @@ -214,11 +267,11 @@ type OperationErrorsResult struct { // 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 + // REQUIRED; The Operation items on this page Value []*Operation + + // The link to the next page of items + NextLink *string } // ResourceOperation - High level response from an operation on a resource @@ -284,6 +337,21 @@ type ResourceOperationError struct { ErrorDetails *string } +// ResourceProvisionPayload - Resource creation data model +type ResourceProvisionPayload struct { + // REQUIRED; Number of resources to be created + ResourceCount *int32 + + // baseProfile, Resource properties that common across all resources + BaseProfile *string + + // resourceOverrides, properties per resource that needs to be overwritted from baseProfile + ResourceOverrides []*string + + // if resourceOverrides doesn't contain "name", service will create name based of prefix and ResourceCount e.g. resourceprefix-0,resourceprefix-1.. + ResourcePrefix *string +} + // Resources - The resources needed for the user request type Resources struct { // REQUIRED; The resource ids used for the request @@ -332,6 +400,21 @@ type StartResourceOperationResponse struct { Results []*ResourceOperation } +// SubmitCreateRequest - The SubmitCreateRequest request for create operations +type SubmitCreateRequest struct { + // REQUIRED; resource creation payload + ResourceConfigParameters *ResourceProvisionPayload + + // REQUIRED; The schedule for the request + Schedule *Schedule + + // CorrelationId item + Correlationid *string + + // The execution parameters for the request + ExecutionParameters *ExecutionParameters +} + // SubmitDeallocateRequest - The deallocate request for resources type SubmitDeallocateRequest struct { // REQUIRED; CorrelationId item @@ -347,6 +430,24 @@ type SubmitDeallocateRequest struct { Schedule *Schedule } +// SubmitDeleteRequest - The SubmitDeleteRequest request for delete operations +type SubmitDeleteRequest struct { + // REQUIRED; The execution parameters for the request + ExecutionParameters *ExecutionParameters + + // REQUIRED; The resources for the request + Resources *Resources + + // REQUIRED; The schedule for the request + Schedule *Schedule + + // CorrelationId item + Correlationid *string + + // Forced delete resource item + ForceDeletion *bool +} + // SubmitHibernateRequest - This is the request for hibernate type SubmitHibernateRequest struct { // REQUIRED; CorrelationId item diff --git a/sdk/resourcemanager/computeschedule/armcomputeschedule/models_serde.go b/sdk/resourcemanager/computeschedule/armcomputeschedule/models_serde.go index 9fb0a1ac9c20..992244055061 100644 --- a/sdk/resourcemanager/computeschedule/armcomputeschedule/models_serde.go +++ b/sdk/resourcemanager/computeschedule/armcomputeschedule/models_serde.go @@ -1,10 +1,6 @@ -//go:build go1.18 -// +build go1.18 - // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. -// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. package armcomputeschedule @@ -73,6 +69,45 @@ func (c *CancelOperationsResponse) UnmarshalJSON(data []byte) error { return nil } +// MarshalJSON implements the json.Marshaller interface for type CreateResourceOperationResponse. +func (c CreateResourceOperationResponse) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "description", c.Description) + populate(objectMap, "location", c.Location) + populate(objectMap, "results", c.Results) + populate(objectMap, "type", c.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CreateResourceOperationResponse. +func (c *CreateResourceOperationResponse) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "description": + err = unpopulate(val, "Description", &c.Description) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &c.Location) + delete(rawMsg, key) + case "results": + err = unpopulate(val, "Results", &c.Results) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &c.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + // MarshalJSON implements the json.Marshaller interface for type DeallocateResourceOperationResponse. func (d DeallocateResourceOperationResponse) MarshalJSON() ([]byte, error) { objectMap := make(map[string]any) @@ -112,6 +147,80 @@ func (d *DeallocateResourceOperationResponse) UnmarshalJSON(data []byte) error { return nil } +// MarshalJSON implements the json.Marshaller interface for type DeleteResourceOperationResponse. +func (d DeleteResourceOperationResponse) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "description", d.Description) + populate(objectMap, "location", d.Location) + populate(objectMap, "results", d.Results) + populate(objectMap, "type", d.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DeleteResourceOperationResponse. +func (d *DeleteResourceOperationResponse) 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 "description": + err = unpopulate(val, "Description", &d.Description) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &d.Location) + delete(rawMsg, key) + case "results": + err = unpopulate(val, "Results", &d.Results) + 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 ExecuteCreateRequest. +func (e ExecuteCreateRequest) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "correlationid", e.Correlationid) + populate(objectMap, "executionParameters", e.ExecutionParameters) + populate(objectMap, "resourceConfigParameters", e.ResourceConfigParameters) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ExecuteCreateRequest. +func (e *ExecuteCreateRequest) 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 "correlationid": + err = unpopulate(val, "Correlationid", &e.Correlationid) + delete(rawMsg, key) + case "executionParameters": + err = unpopulate(val, "ExecutionParameters", &e.ExecutionParameters) + delete(rawMsg, key) + case "resourceConfigParameters": + err = unpopulate(val, "ResourceConfigParameters", &e.ResourceConfigParameters) + 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 ExecuteDeallocateRequest. func (e ExecuteDeallocateRequest) MarshalJSON() ([]byte, error) { objectMap := make(map[string]any) @@ -147,6 +256,45 @@ func (e *ExecuteDeallocateRequest) UnmarshalJSON(data []byte) error { return nil } +// MarshalJSON implements the json.Marshaller interface for type ExecuteDeleteRequest. +func (e ExecuteDeleteRequest) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "correlationid", e.Correlationid) + populate(objectMap, "executionParameters", e.ExecutionParameters) + populate(objectMap, "forceDeletion", e.ForceDeletion) + populate(objectMap, "resources", e.Resources) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ExecuteDeleteRequest. +func (e *ExecuteDeleteRequest) 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 "correlationid": + err = unpopulate(val, "Correlationid", &e.Correlationid) + delete(rawMsg, key) + case "executionParameters": + err = unpopulate(val, "ExecutionParameters", &e.ExecutionParameters) + delete(rawMsg, key) + case "forceDeletion": + err = unpopulate(val, "ForceDeletion", &e.ForceDeletion) + delete(rawMsg, key) + case "resources": + err = unpopulate(val, "Resources", &e.Resources) + 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 ExecuteHibernateRequest. func (e ExecuteHibernateRequest) MarshalJSON() ([]byte, error) { objectMap := make(map[string]any) @@ -751,6 +899,45 @@ func (r *ResourceOperationError) UnmarshalJSON(data []byte) error { return nil } +// MarshalJSON implements the json.Marshaller interface for type ResourceProvisionPayload. +func (r ResourceProvisionPayload) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "baseProfile", r.BaseProfile) + populate(objectMap, "resourceCount", r.ResourceCount) + populate(objectMap, "resourceOverrides", r.ResourceOverrides) + populate(objectMap, "resourcePrefix", r.ResourcePrefix) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ResourceProvisionPayload. +func (r *ResourceProvisionPayload) 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 "baseProfile": + err = unpopulate(val, "BaseProfile", &r.BaseProfile) + delete(rawMsg, key) + case "resourceCount": + err = unpopulate(val, "ResourceCount", &r.ResourceCount) + delete(rawMsg, key) + case "resourceOverrides": + err = unpopulate(val, "ResourceOverrides", &r.ResourceOverrides) + delete(rawMsg, key) + case "resourcePrefix": + err = unpopulate(val, "ResourcePrefix", &r.ResourcePrefix) + 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 Resources. func (r Resources) MarshalJSON() ([]byte, error) { objectMap := make(map[string]any) @@ -891,6 +1078,45 @@ func (s *StartResourceOperationResponse) UnmarshalJSON(data []byte) error { return nil } +// MarshalJSON implements the json.Marshaller interface for type SubmitCreateRequest. +func (s SubmitCreateRequest) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "correlationid", s.Correlationid) + populate(objectMap, "executionParameters", s.ExecutionParameters) + populate(objectMap, "resourceConfigParameters", s.ResourceConfigParameters) + populate(objectMap, "schedule", s.Schedule) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SubmitCreateRequest. +func (s *SubmitCreateRequest) 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 "correlationid": + err = unpopulate(val, "Correlationid", &s.Correlationid) + delete(rawMsg, key) + case "executionParameters": + err = unpopulate(val, "ExecutionParameters", &s.ExecutionParameters) + delete(rawMsg, key) + case "resourceConfigParameters": + err = unpopulate(val, "ResourceConfigParameters", &s.ResourceConfigParameters) + delete(rawMsg, key) + case "schedule": + err = unpopulate(val, "Schedule", &s.Schedule) + 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 SubmitDeallocateRequest. func (s SubmitDeallocateRequest) MarshalJSON() ([]byte, error) { objectMap := make(map[string]any) @@ -930,6 +1156,49 @@ func (s *SubmitDeallocateRequest) UnmarshalJSON(data []byte) error { return nil } +// MarshalJSON implements the json.Marshaller interface for type SubmitDeleteRequest. +func (s SubmitDeleteRequest) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "correlationid", s.Correlationid) + populate(objectMap, "executionParameters", s.ExecutionParameters) + populate(objectMap, "forceDeletion", s.ForceDeletion) + populate(objectMap, "resources", s.Resources) + populate(objectMap, "schedule", s.Schedule) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SubmitDeleteRequest. +func (s *SubmitDeleteRequest) 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 "correlationid": + err = unpopulate(val, "Correlationid", &s.Correlationid) + delete(rawMsg, key) + case "executionParameters": + err = unpopulate(val, "ExecutionParameters", &s.ExecutionParameters) + delete(rawMsg, key) + case "forceDeletion": + err = unpopulate(val, "ForceDeletion", &s.ForceDeletion) + delete(rawMsg, key) + case "resources": + err = unpopulate(val, "Resources", &s.Resources) + delete(rawMsg, key) + case "schedule": + err = unpopulate(val, "Schedule", &s.Schedule) + 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 SubmitHibernateRequest. func (s SubmitHibernateRequest) MarshalJSON() ([]byte, error) { objectMap := make(map[string]any) diff --git a/sdk/resourcemanager/computeschedule/armcomputeschedule/operations_client.go b/sdk/resourcemanager/computeschedule/armcomputeschedule/operations_client.go index 90c8dbfcfb1b..f6b3211656b7 100644 --- a/sdk/resourcemanager/computeschedule/armcomputeschedule/operations_client.go +++ b/sdk/resourcemanager/computeschedule/armcomputeschedule/operations_client.go @@ -1,10 +1,6 @@ -//go:build go1.18 -// +build go1.18 - // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. -// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. package armcomputeschedule @@ -39,7 +35,7 @@ func NewOperationsClient(credential azcore.TokenCredential, options *arm.ClientO // NewListPager - List the operations for the provider // -// Generated from API version 2024-10-01 +// Generated from API version 2025-05-01 // - options - OperationsClientListOptions contains the optional parameters for the OperationsClient.NewListPager method. func (client *OperationsClient) NewListPager(options *OperationsClientListOptions) *runtime.Pager[OperationsClientListResponse] { return runtime.NewPager(runtime.PagingHandler[OperationsClientListResponse]{ @@ -65,14 +61,14 @@ func (client *OperationsClient) NewListPager(options *OperationsClientListOption } // listCreateRequest creates the List request. -func (client *OperationsClient) listCreateRequest(ctx context.Context, options *OperationsClientListOptions) (*policy.Request, error) { +func (client *OperationsClient) listCreateRequest(ctx context.Context, _ *OperationsClientListOptions) (*policy.Request, error) { urlPath := "/providers/Microsoft.ComputeSchedule/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", "2024-10-01") + reqQP.Set("api-version", "2025-05-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil diff --git a/sdk/resourcemanager/computeschedule/armcomputeschedule/operations_client_example_test.go b/sdk/resourcemanager/computeschedule/armcomputeschedule/operations_client_example_test.go index 95ee2e4dcf2e..4ff11862f7b9 100644 --- a/sdk/resourcemanager/computeschedule/armcomputeschedule/operations_client_example_test.go +++ b/sdk/resourcemanager/computeschedule/armcomputeschedule/operations_client_example_test.go @@ -1,30 +1,24 @@ -//go:build go1.18 -// +build go1.18 - // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. -// DO NOT EDIT. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. package armcomputeschedule_test import ( "context" - "log" - "github.com/Azure/azure-sdk-for-go/sdk/azidentity" "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/computeschedule/armcomputeschedule" + "log" ) -// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/8a4eca6b060cf70da696963245656fdc440b666b/specification/computeschedule/resource-manager/Microsoft.ComputeSchedule/stable/2024-10-01/examples/Operations_List.json -func ExampleOperationsClient_NewListPager() { +// Generated from example definition: 2025-05-01/Operations_List_MaximumSet_Gen.json +func ExampleOperationsClient_NewListPager_operationsListMaximumSetGenGeneratedByMaximumSetRuleGeneratedByMaximumSetRuleGeneratedByMaximumSetRule() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() - clientFactory, err := armcomputeschedule.NewClientFactory("", cred, nil) + clientFactory, err := armcomputeschedule.NewClientFactory("", cred, nil) if err != nil { log.Fatalf("failed to create client: %v", err) } @@ -39,20 +33,53 @@ func ExampleOperationsClient_NewListPager() { _ = v } // If the HTTP response code is 200 as defined in example definition, your page structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. - // page.OperationListResult = armcomputeschedule.OperationListResult{ - // Value: []*armcomputeschedule.Operation{ - // { - // Name: to.Ptr("mtiwosbky"), - // ActionType: to.Ptr(armcomputeschedule.ActionTypeInternal), - // Display: &armcomputeschedule.OperationDisplay{ - // Description: to.Ptr("moyje"), - // Operation: to.Ptr("tuneyqwanedwnnbztrmq"), - // Provider: to.Ptr("vtlhmqtfhlyllnplzpdpq"), - // Resource: to.Ptr("epj"), + // page = armcomputeschedule.OperationsClientListResponse{ + // OperationListResult: armcomputeschedule.OperationListResult{ + // Value: []*armcomputeschedule.Operation{ + // { + // Name: to.Ptr("ldqzcrujeitsnm"), + // IsDataAction: to.Ptr(true), + // Display: &armcomputeschedule.OperationDisplay{ + // Provider: to.Ptr("oxdxyfefyvtxexszpvt"), + // Resource: to.Ptr("icchvmkobgsviwonpruioyd"), + // Operation: to.Ptr("ibqrspiv"), + // Description: to.Ptr("gbqvalxlkg"), + // }, + // Origin: to.Ptr(armcomputeschedule.OriginUser), + // ActionType: to.Ptr(armcomputeschedule.ActionTypeInternal), // }, - // IsDataAction: to.Ptr(true), - // Origin: to.Ptr(armcomputeschedule.OriginUser), - // }}, + // }, + // NextLink: to.Ptr("https://microsoft.com/a"), + // }, + // } + } +} + +// Generated from example definition: 2025-05-01/Operations_List_MinimumSet_Gen.json +func ExampleOperationsClient_NewListPager_operationsListMaximumSetGenGeneratedByMaximumSetRuleGeneratedByMaximumSetRuleGeneratedByMinimumSetRule() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armcomputeschedule.NewClientFactory("", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + pager := clientFactory.NewOperationsClient().NewListPager(nil) + for pager.More() { + page, err := pager.NextPage(ctx) + if err != nil { + log.Fatalf("failed to advance page: %v", err) + } + for _, v := range page.Value { + // You could use page here. We use blank identifier for just demo purposes. + _ = v + } + // If the HTTP response code is 200 as defined in example definition, your page structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // page = armcomputeschedule.OperationsClientListResponse{ + // OperationListResult: armcomputeschedule.OperationListResult{ + // }, // } } } diff --git a/sdk/resourcemanager/computeschedule/armcomputeschedule/options.go b/sdk/resourcemanager/computeschedule/armcomputeschedule/options.go index 74458d76ce84..54fd5a281dd8 100644 --- a/sdk/resourcemanager/computeschedule/armcomputeschedule/options.go +++ b/sdk/resourcemanager/computeschedule/armcomputeschedule/options.go @@ -1,10 +1,6 @@ -//go:build go1.18 -// +build go1.18 - // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. -// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. package armcomputeschedule @@ -19,12 +15,24 @@ type ScheduledActionsClientVirtualMachinesCancelOperationsOptions struct { // placeholder for future optional parameters } +// ScheduledActionsClientVirtualMachinesExecuteCreateOptions contains the optional parameters for the ScheduledActionsClient.VirtualMachinesExecuteCreate +// method. +type ScheduledActionsClientVirtualMachinesExecuteCreateOptions struct { + // placeholder for future optional parameters +} + // ScheduledActionsClientVirtualMachinesExecuteDeallocateOptions contains the optional parameters for the ScheduledActionsClient.VirtualMachinesExecuteDeallocate // method. type ScheduledActionsClientVirtualMachinesExecuteDeallocateOptions struct { // placeholder for future optional parameters } +// ScheduledActionsClientVirtualMachinesExecuteDeleteOptions contains the optional parameters for the ScheduledActionsClient.VirtualMachinesExecuteDelete +// method. +type ScheduledActionsClientVirtualMachinesExecuteDeleteOptions struct { + // placeholder for future optional parameters +} + // ScheduledActionsClientVirtualMachinesExecuteHibernateOptions contains the optional parameters for the ScheduledActionsClient.VirtualMachinesExecuteHibernate // method. type ScheduledActionsClientVirtualMachinesExecuteHibernateOptions struct { @@ -49,12 +57,24 @@ type ScheduledActionsClientVirtualMachinesGetOperationStatusOptions struct { // placeholder for future optional parameters } +// ScheduledActionsClientVirtualMachinesSubmitCreateOptions contains the optional parameters for the ScheduledActionsClient.VirtualMachinesSubmitCreate +// method. +type ScheduledActionsClientVirtualMachinesSubmitCreateOptions struct { + // placeholder for future optional parameters +} + // ScheduledActionsClientVirtualMachinesSubmitDeallocateOptions contains the optional parameters for the ScheduledActionsClient.VirtualMachinesSubmitDeallocate // method. type ScheduledActionsClientVirtualMachinesSubmitDeallocateOptions struct { // placeholder for future optional parameters } +// ScheduledActionsClientVirtualMachinesSubmitDeleteOptions contains the optional parameters for the ScheduledActionsClient.VirtualMachinesSubmitDelete +// method. +type ScheduledActionsClientVirtualMachinesSubmitDeleteOptions struct { + // placeholder for future optional parameters +} + // ScheduledActionsClientVirtualMachinesSubmitHibernateOptions contains the optional parameters for the ScheduledActionsClient.VirtualMachinesSubmitHibernate // method. type ScheduledActionsClientVirtualMachinesSubmitHibernateOptions struct { diff --git a/sdk/resourcemanager/computeschedule/armcomputeschedule/responses.go b/sdk/resourcemanager/computeschedule/armcomputeschedule/responses.go index 4f24350bc7d9..3b6285607717 100644 --- a/sdk/resourcemanager/computeschedule/armcomputeschedule/responses.go +++ b/sdk/resourcemanager/computeschedule/armcomputeschedule/responses.go @@ -1,10 +1,6 @@ -//go:build go1.18 -// +build go1.18 - // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. -// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. package armcomputeschedule @@ -20,12 +16,24 @@ type ScheduledActionsClientVirtualMachinesCancelOperationsResponse struct { CancelOperationsResponse } +// ScheduledActionsClientVirtualMachinesExecuteCreateResponse contains the response from method ScheduledActionsClient.VirtualMachinesExecuteCreate. +type ScheduledActionsClientVirtualMachinesExecuteCreateResponse struct { + // The response from a create request + CreateResourceOperationResponse +} + // ScheduledActionsClientVirtualMachinesExecuteDeallocateResponse contains the response from method ScheduledActionsClient.VirtualMachinesExecuteDeallocate. type ScheduledActionsClientVirtualMachinesExecuteDeallocateResponse struct { // The response from a deallocate request DeallocateResourceOperationResponse } +// ScheduledActionsClientVirtualMachinesExecuteDeleteResponse contains the response from method ScheduledActionsClient.VirtualMachinesExecuteDelete. +type ScheduledActionsClientVirtualMachinesExecuteDeleteResponse struct { + // The response from a delete request + DeleteResourceOperationResponse +} + // ScheduledActionsClientVirtualMachinesExecuteHibernateResponse contains the response from method ScheduledActionsClient.VirtualMachinesExecuteHibernate. type ScheduledActionsClientVirtualMachinesExecuteHibernateResponse struct { // The response from a Hibernate request @@ -50,12 +58,24 @@ type ScheduledActionsClientVirtualMachinesGetOperationStatusResponse struct { GetOperationStatusResponse } +// ScheduledActionsClientVirtualMachinesSubmitCreateResponse contains the response from method ScheduledActionsClient.VirtualMachinesSubmitCreate. +type ScheduledActionsClientVirtualMachinesSubmitCreateResponse struct { + // The response from a create request + CreateResourceOperationResponse +} + // ScheduledActionsClientVirtualMachinesSubmitDeallocateResponse contains the response from method ScheduledActionsClient.VirtualMachinesSubmitDeallocate. type ScheduledActionsClientVirtualMachinesSubmitDeallocateResponse struct { // The response from a deallocate request DeallocateResourceOperationResponse } +// ScheduledActionsClientVirtualMachinesSubmitDeleteResponse contains the response from method ScheduledActionsClient.VirtualMachinesSubmitDelete. +type ScheduledActionsClientVirtualMachinesSubmitDeleteResponse struct { + // The response from a delete request + DeleteResourceOperationResponse +} + // ScheduledActionsClientVirtualMachinesSubmitHibernateResponse contains the response from method ScheduledActionsClient.VirtualMachinesSubmitHibernate. type ScheduledActionsClientVirtualMachinesSubmitHibernateResponse struct { // The response from a Hibernate request diff --git a/sdk/resourcemanager/computeschedule/armcomputeschedule/scheduledactions_client.go b/sdk/resourcemanager/computeschedule/armcomputeschedule/scheduledactions_client.go index 10d1780d4da3..a13aa9920c3d 100644 --- a/sdk/resourcemanager/computeschedule/armcomputeschedule/scheduledactions_client.go +++ b/sdk/resourcemanager/computeschedule/armcomputeschedule/scheduledactions_client.go @@ -1,10 +1,6 @@ -//go:build go1.18 -// +build go1.18 - // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. -// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. package armcomputeschedule @@ -47,7 +43,7 @@ func NewScheduledActionsClient(subscriptionID string, credential azcore.TokenCre // request // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2024-10-01 +// Generated from API version 2025-05-01 // - locationparameter - The location name. // - requestBody - The request body // - options - ScheduledActionsClientVirtualMachinesCancelOperationsOptions contains the optional parameters for the ScheduledActionsClient.VirtualMachinesCancelOperations @@ -75,7 +71,7 @@ func (client *ScheduledActionsClient) VirtualMachinesCancelOperations(ctx contex } // virtualMachinesCancelOperationsCreateRequest creates the VirtualMachinesCancelOperations request. -func (client *ScheduledActionsClient) virtualMachinesCancelOperationsCreateRequest(ctx context.Context, locationparameter string, requestBody CancelOperationsRequest, options *ScheduledActionsClientVirtualMachinesCancelOperationsOptions) (*policy.Request, error) { +func (client *ScheduledActionsClient) virtualMachinesCancelOperationsCreateRequest(ctx context.Context, locationparameter string, requestBody CancelOperationsRequest, _ *ScheduledActionsClientVirtualMachinesCancelOperationsOptions) (*policy.Request, error) { urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.ComputeSchedule/locations/{locationparameter}/virtualMachinesCancelOperations" if client.subscriptionID == "" { return nil, errors.New("parameter client.subscriptionID cannot be empty") @@ -90,9 +86,10 @@ func (client *ScheduledActionsClient) virtualMachinesCancelOperationsCreateReque return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2024-10-01") + reqQP.Set("api-version", "2025-05-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} if err := runtime.MarshalAsJSON(req, requestBody); err != nil { return nil, err } @@ -108,11 +105,77 @@ func (client *ScheduledActionsClient) virtualMachinesCancelOperationsHandleRespo return result, nil } +// VirtualMachinesExecuteCreate - VirtualMachinesExecuteCreate: Execute create operation for a batch of virtual machines, +// this operation is triggered as soon as Computeschedule receives it. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2025-05-01 +// - locationparameter - The location name. +// - requestBody - The request body +// - options - ScheduledActionsClientVirtualMachinesExecuteCreateOptions contains the optional parameters for the ScheduledActionsClient.VirtualMachinesExecuteCreate +// method. +func (client *ScheduledActionsClient) VirtualMachinesExecuteCreate(ctx context.Context, locationparameter string, requestBody ExecuteCreateRequest, options *ScheduledActionsClientVirtualMachinesExecuteCreateOptions) (ScheduledActionsClientVirtualMachinesExecuteCreateResponse, error) { + var err error + const operationName = "ScheduledActionsClient.VirtualMachinesExecuteCreate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.virtualMachinesExecuteCreateCreateRequest(ctx, locationparameter, requestBody, options) + if err != nil { + return ScheduledActionsClientVirtualMachinesExecuteCreateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ScheduledActionsClientVirtualMachinesExecuteCreateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ScheduledActionsClientVirtualMachinesExecuteCreateResponse{}, err + } + resp, err := client.virtualMachinesExecuteCreateHandleResponse(httpResp) + return resp, err +} + +// virtualMachinesExecuteCreateCreateRequest creates the VirtualMachinesExecuteCreate request. +func (client *ScheduledActionsClient) virtualMachinesExecuteCreateCreateRequest(ctx context.Context, locationparameter string, requestBody ExecuteCreateRequest, _ *ScheduledActionsClientVirtualMachinesExecuteCreateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.ComputeSchedule/locations/{locationparameter}/virtualMachinesExecuteCreate" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if locationparameter == "" { + return nil, errors.New("parameter locationparameter cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{locationparameter}", url.PathEscape(locationparameter)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2025-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, requestBody); err != nil { + return nil, err + } + return req, nil +} + +// virtualMachinesExecuteCreateHandleResponse handles the VirtualMachinesExecuteCreate response. +func (client *ScheduledActionsClient) virtualMachinesExecuteCreateHandleResponse(resp *http.Response) (ScheduledActionsClientVirtualMachinesExecuteCreateResponse, error) { + result := ScheduledActionsClientVirtualMachinesExecuteCreateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.CreateResourceOperationResponse); err != nil { + return ScheduledActionsClientVirtualMachinesExecuteCreateResponse{}, err + } + return result, nil +} + // VirtualMachinesExecuteDeallocate - VirtualMachinesExecuteDeallocate: Execute deallocate operation for a batch of virtual // machines, this operation is triggered as soon as Computeschedule receives it. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2024-10-01 +// Generated from API version 2025-05-01 // - locationparameter - The location name. // - requestBody - The request body // - options - ScheduledActionsClientVirtualMachinesExecuteDeallocateOptions contains the optional parameters for the ScheduledActionsClient.VirtualMachinesExecuteDeallocate @@ -140,7 +203,7 @@ func (client *ScheduledActionsClient) VirtualMachinesExecuteDeallocate(ctx conte } // virtualMachinesExecuteDeallocateCreateRequest creates the VirtualMachinesExecuteDeallocate request. -func (client *ScheduledActionsClient) virtualMachinesExecuteDeallocateCreateRequest(ctx context.Context, locationparameter string, requestBody ExecuteDeallocateRequest, options *ScheduledActionsClientVirtualMachinesExecuteDeallocateOptions) (*policy.Request, error) { +func (client *ScheduledActionsClient) virtualMachinesExecuteDeallocateCreateRequest(ctx context.Context, locationparameter string, requestBody ExecuteDeallocateRequest, _ *ScheduledActionsClientVirtualMachinesExecuteDeallocateOptions) (*policy.Request, error) { urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.ComputeSchedule/locations/{locationparameter}/virtualMachinesExecuteDeallocate" if client.subscriptionID == "" { return nil, errors.New("parameter client.subscriptionID cannot be empty") @@ -155,9 +218,10 @@ func (client *ScheduledActionsClient) virtualMachinesExecuteDeallocateCreateRequ return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2024-10-01") + reqQP.Set("api-version", "2025-05-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} if err := runtime.MarshalAsJSON(req, requestBody); err != nil { return nil, err } @@ -173,11 +237,77 @@ func (client *ScheduledActionsClient) virtualMachinesExecuteDeallocateHandleResp return result, nil } +// VirtualMachinesExecuteDelete - VirtualMachinesExecuteDelete: Execute delete operation for a batch of virtual machines, +// this operation is triggered as soon as Computeschedule receives it. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2025-05-01 +// - locationparameter - The location name. +// - requestBody - The request body +// - options - ScheduledActionsClientVirtualMachinesExecuteDeleteOptions contains the optional parameters for the ScheduledActionsClient.VirtualMachinesExecuteDelete +// method. +func (client *ScheduledActionsClient) VirtualMachinesExecuteDelete(ctx context.Context, locationparameter string, requestBody ExecuteDeleteRequest, options *ScheduledActionsClientVirtualMachinesExecuteDeleteOptions) (ScheduledActionsClientVirtualMachinesExecuteDeleteResponse, error) { + var err error + const operationName = "ScheduledActionsClient.VirtualMachinesExecuteDelete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.virtualMachinesExecuteDeleteCreateRequest(ctx, locationparameter, requestBody, options) + if err != nil { + return ScheduledActionsClientVirtualMachinesExecuteDeleteResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ScheduledActionsClientVirtualMachinesExecuteDeleteResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ScheduledActionsClientVirtualMachinesExecuteDeleteResponse{}, err + } + resp, err := client.virtualMachinesExecuteDeleteHandleResponse(httpResp) + return resp, err +} + +// virtualMachinesExecuteDeleteCreateRequest creates the VirtualMachinesExecuteDelete request. +func (client *ScheduledActionsClient) virtualMachinesExecuteDeleteCreateRequest(ctx context.Context, locationparameter string, requestBody ExecuteDeleteRequest, _ *ScheduledActionsClientVirtualMachinesExecuteDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.ComputeSchedule/locations/{locationparameter}/virtualMachinesExecuteDelete" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if locationparameter == "" { + return nil, errors.New("parameter locationparameter cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{locationparameter}", url.PathEscape(locationparameter)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2025-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, requestBody); err != nil { + return nil, err + } + return req, nil +} + +// virtualMachinesExecuteDeleteHandleResponse handles the VirtualMachinesExecuteDelete response. +func (client *ScheduledActionsClient) virtualMachinesExecuteDeleteHandleResponse(resp *http.Response) (ScheduledActionsClientVirtualMachinesExecuteDeleteResponse, error) { + result := ScheduledActionsClientVirtualMachinesExecuteDeleteResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.DeleteResourceOperationResponse); err != nil { + return ScheduledActionsClientVirtualMachinesExecuteDeleteResponse{}, err + } + return result, nil +} + // VirtualMachinesExecuteHibernate - VirtualMachinesExecuteHibernate: Execute hibernate operation for a batch of virtual machines, // this operation is triggered as soon as Computeschedule receives it. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2024-10-01 +// Generated from API version 2025-05-01 // - locationparameter - The location name. // - requestBody - The request body // - options - ScheduledActionsClientVirtualMachinesExecuteHibernateOptions contains the optional parameters for the ScheduledActionsClient.VirtualMachinesExecuteHibernate @@ -205,7 +335,7 @@ func (client *ScheduledActionsClient) VirtualMachinesExecuteHibernate(ctx contex } // virtualMachinesExecuteHibernateCreateRequest creates the VirtualMachinesExecuteHibernate request. -func (client *ScheduledActionsClient) virtualMachinesExecuteHibernateCreateRequest(ctx context.Context, locationparameter string, requestBody ExecuteHibernateRequest, options *ScheduledActionsClientVirtualMachinesExecuteHibernateOptions) (*policy.Request, error) { +func (client *ScheduledActionsClient) virtualMachinesExecuteHibernateCreateRequest(ctx context.Context, locationparameter string, requestBody ExecuteHibernateRequest, _ *ScheduledActionsClientVirtualMachinesExecuteHibernateOptions) (*policy.Request, error) { urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.ComputeSchedule/locations/{locationparameter}/virtualMachinesExecuteHibernate" if client.subscriptionID == "" { return nil, errors.New("parameter client.subscriptionID cannot be empty") @@ -220,9 +350,10 @@ func (client *ScheduledActionsClient) virtualMachinesExecuteHibernateCreateReque return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2024-10-01") + reqQP.Set("api-version", "2025-05-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} if err := runtime.MarshalAsJSON(req, requestBody); err != nil { return nil, err } @@ -242,7 +373,7 @@ func (client *ScheduledActionsClient) virtualMachinesExecuteHibernateHandleRespo // operation is triggered as soon as Computeschedule receives it. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2024-10-01 +// Generated from API version 2025-05-01 // - locationparameter - The location name. // - requestBody - The request body // - options - ScheduledActionsClientVirtualMachinesExecuteStartOptions contains the optional parameters for the ScheduledActionsClient.VirtualMachinesExecuteStart @@ -270,7 +401,7 @@ func (client *ScheduledActionsClient) VirtualMachinesExecuteStart(ctx context.Co } // virtualMachinesExecuteStartCreateRequest creates the VirtualMachinesExecuteStart request. -func (client *ScheduledActionsClient) virtualMachinesExecuteStartCreateRequest(ctx context.Context, locationparameter string, requestBody ExecuteStartRequest, options *ScheduledActionsClientVirtualMachinesExecuteStartOptions) (*policy.Request, error) { +func (client *ScheduledActionsClient) virtualMachinesExecuteStartCreateRequest(ctx context.Context, locationparameter string, requestBody ExecuteStartRequest, _ *ScheduledActionsClientVirtualMachinesExecuteStartOptions) (*policy.Request, error) { urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.ComputeSchedule/locations/{locationparameter}/virtualMachinesExecuteStart" if client.subscriptionID == "" { return nil, errors.New("parameter client.subscriptionID cannot be empty") @@ -285,9 +416,10 @@ func (client *ScheduledActionsClient) virtualMachinesExecuteStartCreateRequest(c return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2024-10-01") + reqQP.Set("api-version", "2025-05-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} if err := runtime.MarshalAsJSON(req, requestBody); err != nil { return nil, err } @@ -307,7 +439,7 @@ func (client *ScheduledActionsClient) virtualMachinesExecuteStartHandleResponse( // errors encountered, additional logs) if they exist. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2024-10-01 +// Generated from API version 2025-05-01 // - locationparameter - The location name. // - requestBody - The request body // - options - ScheduledActionsClientVirtualMachinesGetOperationErrorsOptions contains the optional parameters for the ScheduledActionsClient.VirtualMachinesGetOperationErrors @@ -335,7 +467,7 @@ func (client *ScheduledActionsClient) VirtualMachinesGetOperationErrors(ctx cont } // virtualMachinesGetOperationErrorsCreateRequest creates the VirtualMachinesGetOperationErrors request. -func (client *ScheduledActionsClient) virtualMachinesGetOperationErrorsCreateRequest(ctx context.Context, locationparameter string, requestBody GetOperationErrorsRequest, options *ScheduledActionsClientVirtualMachinesGetOperationErrorsOptions) (*policy.Request, error) { +func (client *ScheduledActionsClient) virtualMachinesGetOperationErrorsCreateRequest(ctx context.Context, locationparameter string, requestBody GetOperationErrorsRequest, _ *ScheduledActionsClientVirtualMachinesGetOperationErrorsOptions) (*policy.Request, error) { urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.ComputeSchedule/locations/{locationparameter}/virtualMachinesGetOperationErrors" if client.subscriptionID == "" { return nil, errors.New("parameter client.subscriptionID cannot be empty") @@ -350,9 +482,10 @@ func (client *ScheduledActionsClient) virtualMachinesGetOperationErrorsCreateReq return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2024-10-01") + reqQP.Set("api-version", "2025-05-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} if err := runtime.MarshalAsJSON(req, requestBody); err != nil { return nil, err } @@ -372,7 +505,7 @@ func (client *ScheduledActionsClient) virtualMachinesGetOperationErrorsHandleRes // on virtual machines // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2024-10-01 +// Generated from API version 2025-05-01 // - locationparameter - The location name. // - requestBody - The request body // - options - ScheduledActionsClientVirtualMachinesGetOperationStatusOptions contains the optional parameters for the ScheduledActionsClient.VirtualMachinesGetOperationStatus @@ -400,7 +533,7 @@ func (client *ScheduledActionsClient) VirtualMachinesGetOperationStatus(ctx cont } // virtualMachinesGetOperationStatusCreateRequest creates the VirtualMachinesGetOperationStatus request. -func (client *ScheduledActionsClient) virtualMachinesGetOperationStatusCreateRequest(ctx context.Context, locationparameter string, requestBody GetOperationStatusRequest, options *ScheduledActionsClientVirtualMachinesGetOperationStatusOptions) (*policy.Request, error) { +func (client *ScheduledActionsClient) virtualMachinesGetOperationStatusCreateRequest(ctx context.Context, locationparameter string, requestBody GetOperationStatusRequest, _ *ScheduledActionsClientVirtualMachinesGetOperationStatusOptions) (*policy.Request, error) { urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.ComputeSchedule/locations/{locationparameter}/virtualMachinesGetOperationStatus" if client.subscriptionID == "" { return nil, errors.New("parameter client.subscriptionID cannot be empty") @@ -415,9 +548,10 @@ func (client *ScheduledActionsClient) virtualMachinesGetOperationStatusCreateReq return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2024-10-01") + reqQP.Set("api-version", "2025-05-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} if err := runtime.MarshalAsJSON(req, requestBody); err != nil { return nil, err } @@ -433,11 +567,77 @@ func (client *ScheduledActionsClient) virtualMachinesGetOperationStatusHandleRes return result, nil } +// VirtualMachinesSubmitCreate - VirtualMachinesSubmitCreate: submit create operation for a batch of virtual machines, at +// datetime in future. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2025-05-01 +// - locationparameter - The location name. +// - requestBody - The request body +// - options - ScheduledActionsClientVirtualMachinesSubmitCreateOptions contains the optional parameters for the ScheduledActionsClient.VirtualMachinesSubmitCreate +// method. +func (client *ScheduledActionsClient) VirtualMachinesSubmitCreate(ctx context.Context, locationparameter string, requestBody SubmitCreateRequest, options *ScheduledActionsClientVirtualMachinesSubmitCreateOptions) (ScheduledActionsClientVirtualMachinesSubmitCreateResponse, error) { + var err error + const operationName = "ScheduledActionsClient.VirtualMachinesSubmitCreate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.virtualMachinesSubmitCreateCreateRequest(ctx, locationparameter, requestBody, options) + if err != nil { + return ScheduledActionsClientVirtualMachinesSubmitCreateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ScheduledActionsClientVirtualMachinesSubmitCreateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ScheduledActionsClientVirtualMachinesSubmitCreateResponse{}, err + } + resp, err := client.virtualMachinesSubmitCreateHandleResponse(httpResp) + return resp, err +} + +// virtualMachinesSubmitCreateCreateRequest creates the VirtualMachinesSubmitCreate request. +func (client *ScheduledActionsClient) virtualMachinesSubmitCreateCreateRequest(ctx context.Context, locationparameter string, requestBody SubmitCreateRequest, _ *ScheduledActionsClientVirtualMachinesSubmitCreateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.ComputeSchedule/locations/{locationparameter}/virtualMachinesSubmitCreate" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if locationparameter == "" { + return nil, errors.New("parameter locationparameter cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{locationparameter}", url.PathEscape(locationparameter)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2025-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, requestBody); err != nil { + return nil, err + } + return req, nil +} + +// virtualMachinesSubmitCreateHandleResponse handles the VirtualMachinesSubmitCreate response. +func (client *ScheduledActionsClient) virtualMachinesSubmitCreateHandleResponse(resp *http.Response) (ScheduledActionsClientVirtualMachinesSubmitCreateResponse, error) { + result := ScheduledActionsClientVirtualMachinesSubmitCreateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.CreateResourceOperationResponse); err != nil { + return ScheduledActionsClientVirtualMachinesSubmitCreateResponse{}, err + } + return result, nil +} + // VirtualMachinesSubmitDeallocate - VirtualMachinesSubmitDeallocate: Schedule deallocate operation for a batch of virtual // machines at datetime in future. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2024-10-01 +// Generated from API version 2025-05-01 // - locationparameter - The location name. // - requestBody - The request body // - options - ScheduledActionsClientVirtualMachinesSubmitDeallocateOptions contains the optional parameters for the ScheduledActionsClient.VirtualMachinesSubmitDeallocate @@ -465,7 +665,7 @@ func (client *ScheduledActionsClient) VirtualMachinesSubmitDeallocate(ctx contex } // virtualMachinesSubmitDeallocateCreateRequest creates the VirtualMachinesSubmitDeallocate request. -func (client *ScheduledActionsClient) virtualMachinesSubmitDeallocateCreateRequest(ctx context.Context, locationparameter string, requestBody SubmitDeallocateRequest, options *ScheduledActionsClientVirtualMachinesSubmitDeallocateOptions) (*policy.Request, error) { +func (client *ScheduledActionsClient) virtualMachinesSubmitDeallocateCreateRequest(ctx context.Context, locationparameter string, requestBody SubmitDeallocateRequest, _ *ScheduledActionsClientVirtualMachinesSubmitDeallocateOptions) (*policy.Request, error) { urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.ComputeSchedule/locations/{locationparameter}/virtualMachinesSubmitDeallocate" if client.subscriptionID == "" { return nil, errors.New("parameter client.subscriptionID cannot be empty") @@ -480,9 +680,10 @@ func (client *ScheduledActionsClient) virtualMachinesSubmitDeallocateCreateReque return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2024-10-01") + reqQP.Set("api-version", "2025-05-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} if err := runtime.MarshalAsJSON(req, requestBody); err != nil { return nil, err } @@ -498,11 +699,77 @@ func (client *ScheduledActionsClient) virtualMachinesSubmitDeallocateHandleRespo return result, nil } +// VirtualMachinesSubmitDelete - VirtualMachinesSubmitDelete: submit delete operation for a batch of virtual machines, at +// datetime in future. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2025-05-01 +// - locationparameter - The location name. +// - requestBody - The request body +// - options - ScheduledActionsClientVirtualMachinesSubmitDeleteOptions contains the optional parameters for the ScheduledActionsClient.VirtualMachinesSubmitDelete +// method. +func (client *ScheduledActionsClient) VirtualMachinesSubmitDelete(ctx context.Context, locationparameter string, requestBody SubmitDeleteRequest, options *ScheduledActionsClientVirtualMachinesSubmitDeleteOptions) (ScheduledActionsClientVirtualMachinesSubmitDeleteResponse, error) { + var err error + const operationName = "ScheduledActionsClient.VirtualMachinesSubmitDelete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.virtualMachinesSubmitDeleteCreateRequest(ctx, locationparameter, requestBody, options) + if err != nil { + return ScheduledActionsClientVirtualMachinesSubmitDeleteResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ScheduledActionsClientVirtualMachinesSubmitDeleteResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ScheduledActionsClientVirtualMachinesSubmitDeleteResponse{}, err + } + resp, err := client.virtualMachinesSubmitDeleteHandleResponse(httpResp) + return resp, err +} + +// virtualMachinesSubmitDeleteCreateRequest creates the VirtualMachinesSubmitDelete request. +func (client *ScheduledActionsClient) virtualMachinesSubmitDeleteCreateRequest(ctx context.Context, locationparameter string, requestBody SubmitDeleteRequest, _ *ScheduledActionsClientVirtualMachinesSubmitDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.ComputeSchedule/locations/{locationparameter}/virtualMachinesSubmitDelete" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if locationparameter == "" { + return nil, errors.New("parameter locationparameter cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{locationparameter}", url.PathEscape(locationparameter)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2025-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, requestBody); err != nil { + return nil, err + } + return req, nil +} + +// virtualMachinesSubmitDeleteHandleResponse handles the VirtualMachinesSubmitDelete response. +func (client *ScheduledActionsClient) virtualMachinesSubmitDeleteHandleResponse(resp *http.Response) (ScheduledActionsClientVirtualMachinesSubmitDeleteResponse, error) { + result := ScheduledActionsClientVirtualMachinesSubmitDeleteResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.DeleteResourceOperationResponse); err != nil { + return ScheduledActionsClientVirtualMachinesSubmitDeleteResponse{}, err + } + return result, nil +} + // VirtualMachinesSubmitHibernate - VirtualMachinesSubmitHibernate: Schedule hibernate operation for a batch of virtual machines // at datetime in future. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2024-10-01 +// Generated from API version 2025-05-01 // - locationparameter - The location name. // - requestBody - The request body // - options - ScheduledActionsClientVirtualMachinesSubmitHibernateOptions contains the optional parameters for the ScheduledActionsClient.VirtualMachinesSubmitHibernate @@ -530,7 +797,7 @@ func (client *ScheduledActionsClient) VirtualMachinesSubmitHibernate(ctx context } // virtualMachinesSubmitHibernateCreateRequest creates the VirtualMachinesSubmitHibernate request. -func (client *ScheduledActionsClient) virtualMachinesSubmitHibernateCreateRequest(ctx context.Context, locationparameter string, requestBody SubmitHibernateRequest, options *ScheduledActionsClientVirtualMachinesSubmitHibernateOptions) (*policy.Request, error) { +func (client *ScheduledActionsClient) virtualMachinesSubmitHibernateCreateRequest(ctx context.Context, locationparameter string, requestBody SubmitHibernateRequest, _ *ScheduledActionsClientVirtualMachinesSubmitHibernateOptions) (*policy.Request, error) { urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.ComputeSchedule/locations/{locationparameter}/virtualMachinesSubmitHibernate" if client.subscriptionID == "" { return nil, errors.New("parameter client.subscriptionID cannot be empty") @@ -545,9 +812,10 @@ func (client *ScheduledActionsClient) virtualMachinesSubmitHibernateCreateReques return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2024-10-01") + reqQP.Set("api-version", "2025-05-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} if err := runtime.MarshalAsJSON(req, requestBody); err != nil { return nil, err } @@ -567,7 +835,7 @@ func (client *ScheduledActionsClient) virtualMachinesSubmitHibernateHandleRespon // in future. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2024-10-01 +// Generated from API version 2025-05-01 // - locationparameter - The location name. // - requestBody - The request body // - options - ScheduledActionsClientVirtualMachinesSubmitStartOptions contains the optional parameters for the ScheduledActionsClient.VirtualMachinesSubmitStart @@ -595,7 +863,7 @@ func (client *ScheduledActionsClient) VirtualMachinesSubmitStart(ctx context.Con } // virtualMachinesSubmitStartCreateRequest creates the VirtualMachinesSubmitStart request. -func (client *ScheduledActionsClient) virtualMachinesSubmitStartCreateRequest(ctx context.Context, locationparameter string, requestBody SubmitStartRequest, options *ScheduledActionsClientVirtualMachinesSubmitStartOptions) (*policy.Request, error) { +func (client *ScheduledActionsClient) virtualMachinesSubmitStartCreateRequest(ctx context.Context, locationparameter string, requestBody SubmitStartRequest, _ *ScheduledActionsClientVirtualMachinesSubmitStartOptions) (*policy.Request, error) { urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.ComputeSchedule/locations/{locationparameter}/virtualMachinesSubmitStart" if client.subscriptionID == "" { return nil, errors.New("parameter client.subscriptionID cannot be empty") @@ -610,9 +878,10 @@ func (client *ScheduledActionsClient) virtualMachinesSubmitStartCreateRequest(ct return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2024-10-01") + reqQP.Set("api-version", "2025-05-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} if err := runtime.MarshalAsJSON(req, requestBody); err != nil { return nil, err } diff --git a/sdk/resourcemanager/computeschedule/armcomputeschedule/scheduledactions_client_example_test.go b/sdk/resourcemanager/computeschedule/armcomputeschedule/scheduledactions_client_example_test.go index b9fd4877476e..be9b5e81f3ff 100644 --- a/sdk/resourcemanager/computeschedule/armcomputeschedule/scheduledactions_client_example_test.go +++ b/sdk/resourcemanager/computeschedule/armcomputeschedule/scheduledactions_client_example_test.go @@ -1,40 +1,34 @@ -//go:build go1.18 -// +build go1.18 - // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. -// DO NOT EDIT. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. package armcomputeschedule_test import ( "context" - "log" - - "time" - "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" "github.com/Azure/azure-sdk-for-go/sdk/azidentity" "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/computeschedule/armcomputeschedule" + "log" + "time" ) -// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/8a4eca6b060cf70da696963245656fdc440b666b/specification/computeschedule/resource-manager/Microsoft.ComputeSchedule/stable/2024-10-01/examples/ScheduledActions_VirtualMachinesCancelOperations.json -func ExampleScheduledActionsClient_VirtualMachinesCancelOperations() { +// Generated from example definition: 2025-05-01/ScheduledActions_VirtualMachinesCancelOperations_MaximumSet_Gen.json +func ExampleScheduledActionsClient_VirtualMachinesCancelOperations_scheduledActionsVirtualMachinesCancelOperationsMaximumSetGenGeneratedByMaximumSetRuleGeneratedByMaximumSetRuleGeneratedByMaximumSetRule() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() - clientFactory, err := armcomputeschedule.NewClientFactory("", cred, nil) + clientFactory, err := armcomputeschedule.NewClientFactory("0505D8E4-D41A-48FB-9CA5-4AF8D93BE75F", cred, nil) if err != nil { log.Fatalf("failed to create client: %v", err) } - res, err := clientFactory.NewScheduledActionsClient().VirtualMachinesCancelOperations(ctx, "eastus2euap", armcomputeschedule.CancelOperationsRequest{ - Correlationid: to.Ptr("23480d2f-1dca-4610-afb4-gg25eec1f34r"), + res, err := clientFactory.NewScheduledActionsClient().VirtualMachinesCancelOperations(ctx, "hwrogamrxmqmbhyksvvbpge", armcomputeschedule.CancelOperationsRequest{ OperationIDs: []*string{ - to.Ptr("23480d2f-1dca-4610-afb4-dd25eec1f34r")}, + to.Ptr("rcudibq"), + }, + Correlationid: to.Ptr("lacjacfbxixdmg"), }, nil) if err != nil { log.Fatalf("failed to finish the request: %v", err) @@ -42,59 +36,200 @@ func ExampleScheduledActionsClient_VirtualMachinesCancelOperations() { // You could use response here. We use blank identifier for just demo purposes. _ = res // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. - // res.CancelOperationsResponse = armcomputeschedule.CancelOperationsResponse{ - // Results: []*armcomputeschedule.ResourceOperation{ - // { - // ErrorCode: to.Ptr("null"), - // ErrorDetails: to.Ptr("null"), - // Operation: &armcomputeschedule.ResourceOperationDetails{ - // OperationID: to.Ptr("23480d2f-1dca-4610-afb4-dd25eec1f34r"), - // CompletedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2024-11-01T17:52:53.668Z"); return t}()), - // Deadline: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2024-11-01T17:52:53.667Z"); return t}()), - // DeadlineType: to.Ptr(armcomputeschedule.DeadlineTypeInitiateAt), - // OpType: to.Ptr(armcomputeschedule.ResourceOperationTypeDeallocate), + // res = armcomputeschedule.ScheduledActionsClientVirtualMachinesCancelOperationsResponse{ + // CancelOperationsResponse: &armcomputeschedule.CancelOperationsResponse{ + // Results: []*armcomputeschedule.ResourceOperation{ + // { // ResourceID: to.Ptr("/subscriptions/YourSubscriptionId/resourceGroups/YourResourceGroupName/providers/Microsoft.Compute/virtualMachines/testResource3"), - // ResourceOperationError: &armcomputeschedule.ResourceOperationError{ - // ErrorCode: to.Ptr("null"), - // ErrorDetails: to.Ptr("null"), + // ErrorCode: to.Ptr("ynukyltendgmn"), + // ErrorDetails: to.Ptr("tifeuh"), + // Operation: &armcomputeschedule.ResourceOperationDetails{ + // OperationID: to.Ptr("vppyaxq"), + // ResourceID: to.Ptr("/subscriptions/YourSubscriptionId/resourceGroups/YourResourceGroupName/providers/Microsoft.Compute/virtualMachines/testResource3"), + // OpType: to.Ptr(armcomputeschedule.ResourceOperationTypeUnknown), + // SubscriptionID: to.Ptr("vofvsus"), + // Deadline: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2025-04-15T19:47:03.591Z"); return t}()), + // DeadlineType: to.Ptr(armcomputeschedule.DeadlineTypeUnknown), + // State: to.Ptr(armcomputeschedule.OperationStateUnknown), + // Timezone: to.Ptr("nwugsooykqggcokphgdj"), + // TimeZone: to.Ptr("qkxnxnumvfqmsmpyccv"), + // ResourceOperationError: &armcomputeschedule.ResourceOperationError{ + // ErrorCode: to.Ptr("fagfsojftlff"), + // ErrorDetails: to.Ptr("rtihrkjasrjkllqccuysjrg"), + // }, + // CompletedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2025-04-15T19:47:03.591Z"); return t}()), + // RetryPolicy: &armcomputeschedule.RetryPolicy{ + // RetryCount: to.Ptr[int32](25), + // RetryWindowInMinutes: to.Ptr[int32](4), + // }, // }, - // RetryPolicy: &armcomputeschedule.RetryPolicy{ - // RetryCount: to.Ptr[int32](4), - // RetryWindowInMinutes: to.Ptr[int32](27), + // }, + // }, + // }, + // } +} + +// Generated from example definition: 2025-05-01/ScheduledActions_VirtualMachinesCancelOperations_MinimumSet_Gen.json +func ExampleScheduledActionsClient_VirtualMachinesCancelOperations_scheduledActionsVirtualMachinesCancelOperationsMaximumSetGenGeneratedByMaximumSetRuleGeneratedByMaximumSetRuleGeneratedByMinimumSetRule() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armcomputeschedule.NewClientFactory("0505D8E4-D41A-48FB-9CA5-4AF8D93BE75F", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + res, err := clientFactory.NewScheduledActionsClient().VirtualMachinesCancelOperations(ctx, "pitwczrefdkzfrpphvbqrvbavgnfxl", armcomputeschedule.CancelOperationsRequest{ + OperationIDs: []*string{ + to.Ptr("rcudibq"), + }, + Correlationid: to.Ptr("lacjacfbxixdmg"), + }, nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + // You could use response here. We use blank identifier for just demo purposes. + _ = res + // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // res = armcomputeschedule.ScheduledActionsClientVirtualMachinesCancelOperationsResponse{ + // CancelOperationsResponse: &armcomputeschedule.CancelOperationsResponse{ + // Results: []*armcomputeschedule.ResourceOperation{ + // { + // }, + // }, + // }, + // } +} + +// Generated from example definition: 2025-05-01/ScheduledActions_VirtualMachinesExecuteCreate_MaximumSet_Gen.json +func ExampleScheduledActionsClient_VirtualMachinesExecuteCreate_scheduledActionsVirtualMachinesExecuteCreateMaximumSetGenGeneratedByMaximumSetRuleGeneratedByMaximumSetRuleGeneratedByMaximumSetRule() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armcomputeschedule.NewClientFactory("0505D8E4-D41A-48FB-9CA5-4AF8D93BE75F", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + res, err := clientFactory.NewScheduledActionsClient().VirtualMachinesExecuteCreate(ctx, "nxbiupqfkijjq", armcomputeschedule.ExecuteCreateRequest{ + ResourceConfigParameters: &armcomputeschedule.ResourceProvisionPayload{ + BaseProfile: to.Ptr("tfgrulcuneopmbdjydzofmhpa"), + ResourceOverrides: []*string{ + to.Ptr("hsqtjgsobjaffl"), + }, + ResourceCount: to.Ptr[int32](28), + ResourcePrefix: to.Ptr("rqlxavviucrxfjj"), + }, + ExecutionParameters: &armcomputeschedule.ExecutionParameters{ + OptimizationPreference: to.Ptr(armcomputeschedule.OptimizationPreferenceCost), + RetryPolicy: &armcomputeschedule.RetryPolicy{ + RetryCount: to.Ptr[int32](25), + RetryWindowInMinutes: to.Ptr[int32](4), + }, + }, + Correlationid: to.Ptr("erpswvxajdpqgxfpgmzy"), + }, nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + // You could use response here. We use blank identifier for just demo purposes. + _ = res + // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // res = armcomputeschedule.ScheduledActionsClientVirtualMachinesExecuteCreateResponse{ + // CreateResourceOperationResponse: &armcomputeschedule.CreateResourceOperationResponse{ + // Type: to.Ptr("avmbqoatro"), + // Location: to.Ptr("hhioerbsucdqayxk"), + // Results: []*armcomputeschedule.ResourceOperation{ + // { + // ResourceID: to.Ptr("/subscriptions/YourSubscriptionId/resourceGroups/YourResourceGroupName/providers/Microsoft.Compute/virtualMachines/testResource3"), + // ErrorCode: to.Ptr("ynukyltendgmn"), + // ErrorDetails: to.Ptr("tifeuh"), + // Operation: &armcomputeschedule.ResourceOperationDetails{ + // OperationID: to.Ptr("vppyaxq"), + // ResourceID: to.Ptr("/subscriptions/YourSubscriptionId/resourceGroups/YourResourceGroupName/providers/Microsoft.Compute/virtualMachines/testResource3"), + // OpType: to.Ptr(armcomputeschedule.ResourceOperationTypeUnknown), + // SubscriptionID: to.Ptr("vofvsus"), + // Deadline: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2025-04-15T19:47:03.591Z"); return t}()), + // DeadlineType: to.Ptr(armcomputeschedule.DeadlineTypeUnknown), + // State: to.Ptr(armcomputeschedule.OperationStateUnknown), + // Timezone: to.Ptr("nwugsooykqggcokphgdj"), + // TimeZone: to.Ptr("qkxnxnumvfqmsmpyccv"), + // ResourceOperationError: &armcomputeschedule.ResourceOperationError{ + // ErrorCode: to.Ptr("fagfsojftlff"), + // ErrorDetails: to.Ptr("rtihrkjasrjkllqccuysjrg"), + // }, + // CompletedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2025-04-15T19:47:03.591Z"); return t}()), + // RetryPolicy: &armcomputeschedule.RetryPolicy{ + // RetryCount: to.Ptr[int32](25), + // RetryWindowInMinutes: to.Ptr[int32](4), + // }, // }, - // State: to.Ptr(armcomputeschedule.OperationStateCancelled), - // SubscriptionID: to.Ptr("D8E30CC0-2763-4FCC-84A8-3C5659281032"), - // TimeZone: to.Ptr("UTC"), - // Timezone: to.Ptr("UTC"), // }, - // ResourceID: to.Ptr("/subscriptions/YourSubscriptionId/resourceGroups/YourResourceGroupName/providers/Microsoft.Compute/virtualMachines/testResource3"), - // }}, + // }, + // Description: to.Ptr("plfajalcmjcxmfuvsbnnoabdqxclto"), + // }, // } } -// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/8a4eca6b060cf70da696963245656fdc440b666b/specification/computeschedule/resource-manager/Microsoft.ComputeSchedule/stable/2024-10-01/examples/ScheduledActions_VirtualMachinesExecuteDeallocate.json -func ExampleScheduledActionsClient_VirtualMachinesExecuteDeallocate() { +// Generated from example definition: 2025-05-01/ScheduledActions_VirtualMachinesExecuteCreate_MinimumSet_Gen.json +func ExampleScheduledActionsClient_VirtualMachinesExecuteCreate_scheduledActionsVirtualMachinesExecuteCreateMaximumSetGenGeneratedByMaximumSetRuleGeneratedByMaximumSetRuleGeneratedByMinimumSetRule() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() - clientFactory, err := armcomputeschedule.NewClientFactory("", cred, nil) + clientFactory, err := armcomputeschedule.NewClientFactory("0505D8E4-D41A-48FB-9CA5-4AF8D93BE75F", cred, nil) if err != nil { log.Fatalf("failed to create client: %v", err) } - res, err := clientFactory.NewScheduledActionsClient().VirtualMachinesExecuteDeallocate(ctx, "eastus2euap", armcomputeschedule.ExecuteDeallocateRequest{ - Correlationid: to.Ptr("23480d2f-1dca-4610-afb4-dd25eec1f34r"), + res, err := clientFactory.NewScheduledActionsClient().VirtualMachinesExecuteCreate(ctx, "aiqyytlqsikciuxzocihxb", armcomputeschedule.ExecuteCreateRequest{ + ResourceConfigParameters: &armcomputeschedule.ResourceProvisionPayload{ + ResourceCount: to.Ptr[int32](28), + }, + ExecutionParameters: &armcomputeschedule.ExecutionParameters{}, + }, nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + // You could use response here. We use blank identifier for just demo purposes. + _ = res + // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // res = armcomputeschedule.ScheduledActionsClientVirtualMachinesExecuteCreateResponse{ + // CreateResourceOperationResponse: &armcomputeschedule.CreateResourceOperationResponse{ + // Type: to.Ptr("avmbqoatro"), + // Location: to.Ptr("hhioerbsucdqayxk"), + // Description: to.Ptr("plfajalcmjcxmfuvsbnnoabdqxclto"), + // }, + // } +} + +// Generated from example definition: 2025-05-01/ScheduledActions_VirtualMachinesExecuteDeallocate_MaximumSet_Gen.json +func ExampleScheduledActionsClient_VirtualMachinesExecuteDeallocate_scheduledActionsVirtualMachinesExecuteDeallocateMaximumSetGenGeneratedByMaximumSetRuleGeneratedByMaximumSetRuleGeneratedByMaximumSetRule() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armcomputeschedule.NewClientFactory("0505D8E4-D41A-48FB-9CA5-4AF8D93BE75F", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + res, err := clientFactory.NewScheduledActionsClient().VirtualMachinesExecuteDeallocate(ctx, "ykpowbmjexmsv", armcomputeschedule.ExecuteDeallocateRequest{ ExecutionParameters: &armcomputeschedule.ExecutionParameters{ + OptimizationPreference: to.Ptr(armcomputeschedule.OptimizationPreferenceCost), RetryPolicy: &armcomputeschedule.RetryPolicy{ - RetryCount: to.Ptr[int32](4), - RetryWindowInMinutes: to.Ptr[int32](27), + RetryCount: to.Ptr[int32](25), + RetryWindowInMinutes: to.Ptr[int32](4), }, }, Resources: &armcomputeschedule.Resources{ IDs: []*string{ - to.Ptr("/subscriptions/YourSubscriptionId/resourceGroups/YourResourceGroupName/providers/Microsoft.Compute/virtualMachines/testResource3")}, + to.Ptr("/subscriptions/YourSubscriptionId/resourceGroups/YourResourceGroupName/providers/Microsoft.Compute/virtualMachines/testResource3"), + }, }, + Correlationid: to.Ptr("dsszhmrdsczkv"), }, nil) if err != nil { log.Fatalf("failed to finish the request: %v", err) @@ -102,62 +237,103 @@ func ExampleScheduledActionsClient_VirtualMachinesExecuteDeallocate() { // You could use response here. We use blank identifier for just demo purposes. _ = res // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. - // res.DeallocateResourceOperationResponse = armcomputeschedule.DeallocateResourceOperationResponse{ - // Type: to.Ptr("VirtualMachine"), - // Description: to.Ptr("Deallocate Resource Request"), - // Location: to.Ptr("eastus2euap"), - // Results: []*armcomputeschedule.ResourceOperation{ - // { - // ErrorCode: to.Ptr("null"), - // ErrorDetails: to.Ptr("null"), - // Operation: &armcomputeschedule.ResourceOperationDetails{ - // OperationID: to.Ptr("23480d2f-1dca-4610-afb4-dd25eec1f34r"), - // CompletedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2024-11-01T17:52:53.668Z"); return t}()), - // Deadline: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2024-11-01T17:52:53.667Z"); return t}()), - // DeadlineType: to.Ptr(armcomputeschedule.DeadlineTypeInitiateAt), - // OpType: to.Ptr(armcomputeschedule.ResourceOperationTypeDeallocate), + // res = armcomputeschedule.ScheduledActionsClientVirtualMachinesExecuteDeallocateResponse{ + // DeallocateResourceOperationResponse: &armcomputeschedule.DeallocateResourceOperationResponse{ + // Type: to.Ptr("fpnhqvrtbqizlylnwy"), + // Location: to.Ptr("hhioerbsucdqayxk"), + // Results: []*armcomputeschedule.ResourceOperation{ + // { // ResourceID: to.Ptr("/subscriptions/YourSubscriptionId/resourceGroups/YourResourceGroupName/providers/Microsoft.Compute/virtualMachines/testResource3"), - // ResourceOperationError: &armcomputeschedule.ResourceOperationError{ - // ErrorCode: to.Ptr("null"), - // ErrorDetails: to.Ptr("null"), + // ErrorCode: to.Ptr("ynukyltendgmn"), + // ErrorDetails: to.Ptr("tifeuh"), + // Operation: &armcomputeschedule.ResourceOperationDetails{ + // OperationID: to.Ptr("vppyaxq"), + // ResourceID: to.Ptr("/subscriptions/YourSubscriptionId/resourceGroups/YourResourceGroupName/providers/Microsoft.Compute/virtualMachines/testResource3"), + // OpType: to.Ptr(armcomputeschedule.ResourceOperationTypeUnknown), + // SubscriptionID: to.Ptr("vofvsus"), + // Deadline: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2025-04-15T19:47:03.591Z"); return t}()), + // DeadlineType: to.Ptr(armcomputeschedule.DeadlineTypeUnknown), + // State: to.Ptr(armcomputeschedule.OperationStateUnknown), + // Timezone: to.Ptr("nwugsooykqggcokphgdj"), + // TimeZone: to.Ptr("qkxnxnumvfqmsmpyccv"), + // ResourceOperationError: &armcomputeschedule.ResourceOperationError{ + // ErrorCode: to.Ptr("fagfsojftlff"), + // ErrorDetails: to.Ptr("rtihrkjasrjkllqccuysjrg"), + // }, + // CompletedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2025-04-15T19:47:03.591Z"); return t}()), + // RetryPolicy: &armcomputeschedule.RetryPolicy{ + // RetryCount: to.Ptr[int32](25), + // RetryWindowInMinutes: to.Ptr[int32](4), + // }, // }, - // RetryPolicy: &armcomputeschedule.RetryPolicy{ - // RetryCount: to.Ptr[int32](4), - // RetryWindowInMinutes: to.Ptr[int32](27), - // }, - // State: to.Ptr(armcomputeschedule.OperationStateSucceeded), - // SubscriptionID: to.Ptr("D8E30CC0-2763-4FCC-84A8-3C5659281032"), - // TimeZone: to.Ptr("UTC"), - // Timezone: to.Ptr("UTC"), // }, - // ResourceID: to.Ptr("/subscriptions/YourSubscriptionId/resourceGroups/YourResourceGroupName/providers/Microsoft.Compute/virtualMachines/testResource3"), - // }}, + // }, + // Description: to.Ptr("zknbxgebvymhzzmsbrlaqreub"), + // }, + // } +} + +// Generated from example definition: 2025-05-01/ScheduledActions_VirtualMachinesExecuteDeallocate_MinimumSet_Gen.json +func ExampleScheduledActionsClient_VirtualMachinesExecuteDeallocate_scheduledActionsVirtualMachinesExecuteDeallocateMaximumSetGenGeneratedByMaximumSetRuleGeneratedByMaximumSetRuleGeneratedByMinimumSetRule() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armcomputeschedule.NewClientFactory("0505D8E4-D41A-48FB-9CA5-4AF8D93BE75F", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + res, err := clientFactory.NewScheduledActionsClient().VirtualMachinesExecuteDeallocate(ctx, "bfldnxffvllwvqa", armcomputeschedule.ExecuteDeallocateRequest{ + ExecutionParameters: &armcomputeschedule.ExecutionParameters{}, + Resources: &armcomputeschedule.Resources{ + IDs: []*string{ + to.Ptr("/subscriptions/YourSubscriptionId/resourceGroups/YourResourceGroupName/providers/Microsoft.Compute/virtualMachines/testResource3"), + }, + }, + Correlationid: to.Ptr("dsszhmrdsczkv"), + }, nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + // You could use response here. We use blank identifier for just demo purposes. + _ = res + // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // res = armcomputeschedule.ScheduledActionsClientVirtualMachinesExecuteDeallocateResponse{ + // DeallocateResourceOperationResponse: &armcomputeschedule.DeallocateResourceOperationResponse{ + // Type: to.Ptr("fpnhqvrtbqizlylnwy"), + // Location: to.Ptr("hhioerbsucdqayxk"), + // Description: to.Ptr("zknbxgebvymhzzmsbrlaqreub"), + // }, // } } -// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/8a4eca6b060cf70da696963245656fdc440b666b/specification/computeschedule/resource-manager/Microsoft.ComputeSchedule/stable/2024-10-01/examples/ScheduledActions_VirtualMachinesExecuteHibernate.json -func ExampleScheduledActionsClient_VirtualMachinesExecuteHibernate() { +// Generated from example definition: 2025-05-01/ScheduledActions_VirtualMachinesExecuteDelete_MaximumSet_Gen.json +func ExampleScheduledActionsClient_VirtualMachinesExecuteDelete_scheduledActionsVirtualMachinesExecuteDeleteMaximumSetGenGeneratedByMaximumSetRuleGeneratedByMaximumSetRuleGeneratedByMaximumSetRule() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() - clientFactory, err := armcomputeschedule.NewClientFactory("", cred, nil) + clientFactory, err := armcomputeschedule.NewClientFactory("0505D8E4-D41A-48FB-9CA5-4AF8D93BE75F", cred, nil) if err != nil { log.Fatalf("failed to create client: %v", err) } - res, err := clientFactory.NewScheduledActionsClient().VirtualMachinesExecuteHibernate(ctx, "eastus2euap", armcomputeschedule.ExecuteHibernateRequest{ - Correlationid: to.Ptr("23480d2f-1dca-4610-afb4-dd25eec1f34r"), + res, err := clientFactory.NewScheduledActionsClient().VirtualMachinesExecuteDelete(ctx, "yrngwxkxxxbifqyc", armcomputeschedule.ExecuteDeleteRequest{ ExecutionParameters: &armcomputeschedule.ExecutionParameters{ + OptimizationPreference: to.Ptr(armcomputeschedule.OptimizationPreferenceCost), RetryPolicy: &armcomputeschedule.RetryPolicy{ - RetryCount: to.Ptr[int32](5), - RetryWindowInMinutes: to.Ptr[int32](27), + RetryCount: to.Ptr[int32](25), + RetryWindowInMinutes: to.Ptr[int32](4), }, }, Resources: &armcomputeschedule.Resources{ IDs: []*string{ - to.Ptr("/subscriptions/YourSubscriptionId/resourceGroups/YourResourceGroupName/providers/Microsoft.Compute/virtualMachines/testResource3")}, + to.Ptr("/subscriptions/YourSubscriptionId/resourceGroups/YourResourceGroupName/providers/Microsoft.Compute/virtualMachines/testResource3"), + }, }, + Correlationid: to.Ptr("lgxsiioaybtjexssjzw"), + ForceDeletion: to.Ptr(true), }, nil) if err != nil { log.Fatalf("failed to finish the request: %v", err) @@ -165,62 +341,204 @@ func ExampleScheduledActionsClient_VirtualMachinesExecuteHibernate() { // You could use response here. We use blank identifier for just demo purposes. _ = res // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. - // res.HibernateResourceOperationResponse = armcomputeschedule.HibernateResourceOperationResponse{ - // Type: to.Ptr("VirtualMachine"), - // Description: to.Ptr("Hibernate Resource Request"), - // Location: to.Ptr("eastus2euap"), - // Results: []*armcomputeschedule.ResourceOperation{ - // { - // ErrorCode: to.Ptr("null"), - // ErrorDetails: to.Ptr("null"), - // Operation: &armcomputeschedule.ResourceOperationDetails{ - // OperationID: to.Ptr("23480d2f-1dca-4610-afb4-dd25eec1f34r"), - // CompletedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2024-11-01T17:52:53.668Z"); return t}()), - // Deadline: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2024-11-01T17:52:53.667Z"); return t}()), - // DeadlineType: to.Ptr(armcomputeschedule.DeadlineTypeInitiateAt), - // OpType: to.Ptr(armcomputeschedule.ResourceOperationTypeHibernate), + // res = armcomputeschedule.ScheduledActionsClientVirtualMachinesExecuteDeleteResponse{ + // DeleteResourceOperationResponse: &armcomputeschedule.DeleteResourceOperationResponse{ + // Type: to.Ptr("tauhekvwziataptcsyqtfpq"), + // Location: to.Ptr("hhioerbsucdqayxk"), + // Results: []*armcomputeschedule.ResourceOperation{ + // { // ResourceID: to.Ptr("/subscriptions/YourSubscriptionId/resourceGroups/YourResourceGroupName/providers/Microsoft.Compute/virtualMachines/testResource3"), - // ResourceOperationError: &armcomputeschedule.ResourceOperationError{ - // ErrorCode: to.Ptr("null"), - // ErrorDetails: to.Ptr("null"), + // ErrorCode: to.Ptr("ynukyltendgmn"), + // ErrorDetails: to.Ptr("tifeuh"), + // Operation: &armcomputeschedule.ResourceOperationDetails{ + // OperationID: to.Ptr("vppyaxq"), + // ResourceID: to.Ptr("/subscriptions/YourSubscriptionId/resourceGroups/YourResourceGroupName/providers/Microsoft.Compute/virtualMachines/testResource3"), + // OpType: to.Ptr(armcomputeschedule.ResourceOperationTypeUnknown), + // SubscriptionID: to.Ptr("vofvsus"), + // Deadline: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2025-04-15T19:47:03.591Z"); return t}()), + // DeadlineType: to.Ptr(armcomputeschedule.DeadlineTypeUnknown), + // State: to.Ptr(armcomputeschedule.OperationStateUnknown), + // Timezone: to.Ptr("nwugsooykqggcokphgdj"), + // TimeZone: to.Ptr("qkxnxnumvfqmsmpyccv"), + // ResourceOperationError: &armcomputeschedule.ResourceOperationError{ + // ErrorCode: to.Ptr("fagfsojftlff"), + // ErrorDetails: to.Ptr("rtihrkjasrjkllqccuysjrg"), + // }, + // CompletedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2025-04-15T19:47:03.591Z"); return t}()), + // RetryPolicy: &armcomputeschedule.RetryPolicy{ + // RetryCount: to.Ptr[int32](25), + // RetryWindowInMinutes: to.Ptr[int32](4), + // }, // }, - // RetryPolicy: &armcomputeschedule.RetryPolicy{ - // RetryCount: to.Ptr[int32](5), - // RetryWindowInMinutes: to.Ptr[int32](27), + // }, + // }, + // Description: to.Ptr("fxgbwqglaskyb"), + // }, + // } +} + +// Generated from example definition: 2025-05-01/ScheduledActions_VirtualMachinesExecuteDelete_MinimumSet_Gen.json +func ExampleScheduledActionsClient_VirtualMachinesExecuteDelete_scheduledActionsVirtualMachinesExecuteDeleteMaximumSetGenGeneratedByMaximumSetRuleGeneratedByMaximumSetRuleGeneratedByMinimumSetRule() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armcomputeschedule.NewClientFactory("0505D8E4-D41A-48FB-9CA5-4AF8D93BE75F", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + res, err := clientFactory.NewScheduledActionsClient().VirtualMachinesExecuteDelete(ctx, "urzqnogieubgnjsyadipeyqegdomtm", armcomputeschedule.ExecuteDeleteRequest{ + ExecutionParameters: &armcomputeschedule.ExecutionParameters{}, + Resources: &armcomputeschedule.Resources{ + IDs: []*string{ + to.Ptr("/subscriptions/YourSubscriptionId/resourceGroups/YourResourceGroupName/providers/Microsoft.Compute/virtualMachines/testResource3"), + }, + }, + }, nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + // You could use response here. We use blank identifier for just demo purposes. + _ = res + // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // res = armcomputeschedule.ScheduledActionsClientVirtualMachinesExecuteDeleteResponse{ + // DeleteResourceOperationResponse: &armcomputeschedule.DeleteResourceOperationResponse{ + // Type: to.Ptr("tauhekvwziataptcsyqtfpq"), + // Location: to.Ptr("hhioerbsucdqayxk"), + // Description: to.Ptr("fxgbwqglaskyb"), + // }, + // } +} + +// Generated from example definition: 2025-05-01/ScheduledActions_VirtualMachinesExecuteHibernate_MaximumSet_Gen.json +func ExampleScheduledActionsClient_VirtualMachinesExecuteHibernate_scheduledActionsVirtualMachinesExecuteHibernateMaximumSetGenGeneratedByMaximumSetRuleGeneratedByMaximumSetRuleGeneratedByMaximumSetRule() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armcomputeschedule.NewClientFactory("0505D8E4-D41A-48FB-9CA5-4AF8D93BE75F", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + res, err := clientFactory.NewScheduledActionsClient().VirtualMachinesExecuteHibernate(ctx, "aojgnzdqrphhygchir", armcomputeschedule.ExecuteHibernateRequest{ + ExecutionParameters: &armcomputeschedule.ExecutionParameters{ + OptimizationPreference: to.Ptr(armcomputeschedule.OptimizationPreferenceCost), + RetryPolicy: &armcomputeschedule.RetryPolicy{ + RetryCount: to.Ptr[int32](25), + RetryWindowInMinutes: to.Ptr[int32](4), + }, + }, + Resources: &armcomputeschedule.Resources{ + IDs: []*string{ + to.Ptr("/subscriptions/YourSubscriptionId/resourceGroups/YourResourceGroupName/providers/Microsoft.Compute/virtualMachines/testResource3"), + }, + }, + Correlationid: to.Ptr("jmdiz"), + }, nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + // You could use response here. We use blank identifier for just demo purposes. + _ = res + // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // res = armcomputeschedule.ScheduledActionsClientVirtualMachinesExecuteHibernateResponse{ + // HibernateResourceOperationResponse: &armcomputeschedule.HibernateResourceOperationResponse{ + // Type: to.Ptr("yrmuumqaqiyotst"), + // Location: to.Ptr("hhioerbsucdqayxk"), + // Results: []*armcomputeschedule.ResourceOperation{ + // { + // ResourceID: to.Ptr("/subscriptions/YourSubscriptionId/resourceGroups/YourResourceGroupName/providers/Microsoft.Compute/virtualMachines/testResource3"), + // ErrorCode: to.Ptr("ynukyltendgmn"), + // ErrorDetails: to.Ptr("tifeuh"), + // Operation: &armcomputeschedule.ResourceOperationDetails{ + // OperationID: to.Ptr("vppyaxq"), + // ResourceID: to.Ptr("/subscriptions/YourSubscriptionId/resourceGroups/YourResourceGroupName/providers/Microsoft.Compute/virtualMachines/testResource3"), + // OpType: to.Ptr(armcomputeschedule.ResourceOperationTypeUnknown), + // SubscriptionID: to.Ptr("vofvsus"), + // Deadline: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2025-04-15T19:47:03.591Z"); return t}()), + // DeadlineType: to.Ptr(armcomputeschedule.DeadlineTypeUnknown), + // State: to.Ptr(armcomputeschedule.OperationStateUnknown), + // Timezone: to.Ptr("nwugsooykqggcokphgdj"), + // TimeZone: to.Ptr("qkxnxnumvfqmsmpyccv"), + // ResourceOperationError: &armcomputeschedule.ResourceOperationError{ + // ErrorCode: to.Ptr("fagfsojftlff"), + // ErrorDetails: to.Ptr("rtihrkjasrjkllqccuysjrg"), + // }, + // CompletedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2025-04-15T19:47:03.591Z"); return t}()), + // RetryPolicy: &armcomputeschedule.RetryPolicy{ + // RetryCount: to.Ptr[int32](25), + // RetryWindowInMinutes: to.Ptr[int32](4), + // }, // }, - // State: to.Ptr(armcomputeschedule.OperationStateSucceeded), - // SubscriptionID: to.Ptr("D8E30CC0-2763-4FCC-84A8-3C5659281032"), - // TimeZone: to.Ptr("UTC"), - // Timezone: to.Ptr("UTC"), // }, - // ResourceID: to.Ptr("/subscriptions/YourSubscriptionId/resourceGroups/YourResourceGroupName/providers/Microsoft.Compute/virtualMachines/testResource3"), - // }}, + // }, + // Description: to.Ptr("ogyqdzdslyvxslrykb"), + // }, // } } -// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/8a4eca6b060cf70da696963245656fdc440b666b/specification/computeschedule/resource-manager/Microsoft.ComputeSchedule/stable/2024-10-01/examples/ScheduledActions_VirtualMachinesExecuteStart.json -func ExampleScheduledActionsClient_VirtualMachinesExecuteStart() { +// Generated from example definition: 2025-05-01/ScheduledActions_VirtualMachinesExecuteHibernate_MinimumSet_Gen.json +func ExampleScheduledActionsClient_VirtualMachinesExecuteHibernate_scheduledActionsVirtualMachinesExecuteHibernateMaximumSetGenGeneratedByMaximumSetRuleGeneratedByMaximumSetRuleGeneratedByMinimumSetRule() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() - clientFactory, err := armcomputeschedule.NewClientFactory("", cred, nil) + clientFactory, err := armcomputeschedule.NewClientFactory("0505D8E4-D41A-48FB-9CA5-4AF8D93BE75F", cred, nil) if err != nil { log.Fatalf("failed to create client: %v", err) } - res, err := clientFactory.NewScheduledActionsClient().VirtualMachinesExecuteStart(ctx, "eastus2euap", armcomputeschedule.ExecuteStartRequest{ - Correlationid: to.Ptr("23480d2f-1dca-4610-afb4-dd25eec1f34r"), + res, err := clientFactory.NewScheduledActionsClient().VirtualMachinesExecuteHibernate(ctx, "gmflbqliyjrhmrjvqrxrgocbxzjr", armcomputeschedule.ExecuteHibernateRequest{ + ExecutionParameters: &armcomputeschedule.ExecutionParameters{}, + Resources: &armcomputeschedule.Resources{ + IDs: []*string{ + to.Ptr("/subscriptions/YourSubscriptionId/resourceGroups/YourResourceGroupName/providers/Microsoft.Compute/virtualMachines/testResource3"), + }, + }, + Correlationid: to.Ptr("jmdiz"), + }, nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + // You could use response here. We use blank identifier for just demo purposes. + _ = res + // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // res = armcomputeschedule.ScheduledActionsClientVirtualMachinesExecuteHibernateResponse{ + // HibernateResourceOperationResponse: &armcomputeschedule.HibernateResourceOperationResponse{ + // Type: to.Ptr("yrmuumqaqiyotst"), + // Location: to.Ptr("hhioerbsucdqayxk"), + // Description: to.Ptr("ogyqdzdslyvxslrykb"), + // }, + // } +} + +// Generated from example definition: 2025-05-01/ScheduledActions_VirtualMachinesExecuteStart_MaximumSet_Gen.json +func ExampleScheduledActionsClient_VirtualMachinesExecuteStart_scheduledActionsVirtualMachinesExecuteStartMaximumSetGenGeneratedByMaximumSetRuleGeneratedByMaximumSetRuleGeneratedByMaximumSetRule() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armcomputeschedule.NewClientFactory("0505D8E4-D41A-48FB-9CA5-4AF8D93BE75F", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + res, err := clientFactory.NewScheduledActionsClient().VirtualMachinesExecuteStart(ctx, "jwybvpf", armcomputeschedule.ExecuteStartRequest{ ExecutionParameters: &armcomputeschedule.ExecutionParameters{ + OptimizationPreference: to.Ptr(armcomputeschedule.OptimizationPreferenceCost), RetryPolicy: &armcomputeschedule.RetryPolicy{ - RetryCount: to.Ptr[int32](2), - RetryWindowInMinutes: to.Ptr[int32](27), + RetryCount: to.Ptr[int32](25), + RetryWindowInMinutes: to.Ptr[int32](4), }, }, Resources: &armcomputeschedule.Resources{ IDs: []*string{ - to.Ptr("/subscriptions/YourSubscriptionId/resourceGroups/YourResourceGroupName/providers/Microsoft.Compute/virtualMachines/testResource3")}, + to.Ptr("/subscriptions/YourSubscriptionId/resourceGroups/YourResourceGroupName/providers/Microsoft.Compute/virtualMachines/testResource3"), + }, }, + Correlationid: to.Ptr("vwpcrwowcfgjuwnxzvvdma"), }, nil) if err != nil { log.Fatalf("failed to finish the request: %v", err) @@ -228,53 +546,140 @@ func ExampleScheduledActionsClient_VirtualMachinesExecuteStart() { // You could use response here. We use blank identifier for just demo purposes. _ = res // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. - // res.StartResourceOperationResponse = armcomputeschedule.StartResourceOperationResponse{ - // Type: to.Ptr("virtualMachine"), - // Description: to.Ptr("Start Resource Request"), - // Location: to.Ptr("eastus2euap"), - // Results: []*armcomputeschedule.ResourceOperation{ - // { - // ErrorCode: to.Ptr("null"), - // ErrorDetails: to.Ptr("null"), - // Operation: &armcomputeschedule.ResourceOperationDetails{ - // OperationID: to.Ptr("23480d2f-1dca-4610-afb4-dd25eec1f34r"), - // CompletedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2024-11-01T17:52:53.668Z"); return t}()), - // Deadline: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2024-11-01T17:52:53.667Z"); return t}()), - // DeadlineType: to.Ptr(armcomputeschedule.DeadlineTypeInitiateAt), - // OpType: to.Ptr(armcomputeschedule.ResourceOperationTypeStart), + // res = armcomputeschedule.ScheduledActionsClientVirtualMachinesExecuteStartResponse{ + // StartResourceOperationResponse: &armcomputeschedule.StartResourceOperationResponse{ + // Type: to.Ptr("lcikdomhndewkiqpf"), + // Location: to.Ptr("hhioerbsucdqayxk"), + // Results: []*armcomputeschedule.ResourceOperation{ + // { // ResourceID: to.Ptr("/subscriptions/YourSubscriptionId/resourceGroups/YourResourceGroupName/providers/Microsoft.Compute/virtualMachines/testResource3"), - // ResourceOperationError: &armcomputeschedule.ResourceOperationError{ - // ErrorCode: to.Ptr("null"), - // ErrorDetails: to.Ptr("null"), + // ErrorCode: to.Ptr("ynukyltendgmn"), + // ErrorDetails: to.Ptr("tifeuh"), + // Operation: &armcomputeschedule.ResourceOperationDetails{ + // OperationID: to.Ptr("vppyaxq"), + // ResourceID: to.Ptr("/subscriptions/YourSubscriptionId/resourceGroups/YourResourceGroupName/providers/Microsoft.Compute/virtualMachines/testResource3"), + // OpType: to.Ptr(armcomputeschedule.ResourceOperationTypeUnknown), + // SubscriptionID: to.Ptr("vofvsus"), + // Deadline: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2025-04-15T19:47:03.591Z"); return t}()), + // DeadlineType: to.Ptr(armcomputeschedule.DeadlineTypeUnknown), + // State: to.Ptr(armcomputeschedule.OperationStateUnknown), + // Timezone: to.Ptr("nwugsooykqggcokphgdj"), + // TimeZone: to.Ptr("qkxnxnumvfqmsmpyccv"), + // ResourceOperationError: &armcomputeschedule.ResourceOperationError{ + // ErrorCode: to.Ptr("fagfsojftlff"), + // ErrorDetails: to.Ptr("rtihrkjasrjkllqccuysjrg"), + // }, + // CompletedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2025-04-15T19:47:03.591Z"); return t}()), + // RetryPolicy: &armcomputeschedule.RetryPolicy{ + // RetryCount: to.Ptr[int32](25), + // RetryWindowInMinutes: to.Ptr[int32](4), + // }, // }, - // RetryPolicy: &armcomputeschedule.RetryPolicy{ - // RetryCount: to.Ptr[int32](2), - // RetryWindowInMinutes: to.Ptr[int32](27), + // }, + // }, + // Description: to.Ptr("mqfxdgracoxwwpoegjryov"), + // }, + // } +} + +// Generated from example definition: 2025-05-01/ScheduledActions_VirtualMachinesExecuteStart_MinimumSet_Gen.json +func ExampleScheduledActionsClient_VirtualMachinesExecuteStart_scheduledActionsVirtualMachinesExecuteStartMaximumSetGenGeneratedByMaximumSetRuleGeneratedByMaximumSetRuleGeneratedByMinimumSetRule() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armcomputeschedule.NewClientFactory("0505D8E4-D41A-48FB-9CA5-4AF8D93BE75F", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + res, err := clientFactory.NewScheduledActionsClient().VirtualMachinesExecuteStart(ctx, "ksfzuak", armcomputeschedule.ExecuteStartRequest{ + ExecutionParameters: &armcomputeschedule.ExecutionParameters{}, + Resources: &armcomputeschedule.Resources{ + IDs: []*string{ + to.Ptr("/subscriptions/YourSubscriptionId/resourceGroups/YourResourceGroupName/providers/Microsoft.Compute/virtualMachines/testResource3"), + }, + }, + Correlationid: to.Ptr("vwpcrwowcfgjuwnxzvvdma"), + }, nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + // You could use response here. We use blank identifier for just demo purposes. + _ = res + // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // res = armcomputeschedule.ScheduledActionsClientVirtualMachinesExecuteStartResponse{ + // StartResourceOperationResponse: &armcomputeschedule.StartResourceOperationResponse{ + // Type: to.Ptr("lcikdomhndewkiqpf"), + // Location: to.Ptr("hhioerbsucdqayxk"), + // Description: to.Ptr("mqfxdgracoxwwpoegjryov"), + // }, + // } +} + +// Generated from example definition: 2025-05-01/ScheduledActions_VirtualMachinesGetOperationErrors_MaximumSet_Gen.json +func ExampleScheduledActionsClient_VirtualMachinesGetOperationErrors_scheduledActionsVirtualMachinesGetOperationErrorsMaximumSetGenGeneratedByMaximumSetRuleGeneratedByMaximumSetRuleGeneratedByMaximumSetRule() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armcomputeschedule.NewClientFactory("0505D8E4-D41A-48FB-9CA5-4AF8D93BE75F", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + res, err := clientFactory.NewScheduledActionsClient().VirtualMachinesGetOperationErrors(ctx, "paluwjjcxtjeozpoxrnstls", armcomputeschedule.GetOperationErrorsRequest{ + OperationIDs: []*string{ + to.Ptr("ksufjznokhsbowdupyt"), + }, + }, nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + // You could use response here. We use blank identifier for just demo purposes. + _ = res + // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // res = armcomputeschedule.ScheduledActionsClientVirtualMachinesGetOperationErrorsResponse{ + // GetOperationErrorsResponse: &armcomputeschedule.GetOperationErrorsResponse{ + // Results: []*armcomputeschedule.OperationErrorsResult{ + // { + // OperationID: to.Ptr("emftjglfbsxaboxqzxlpbjian"), + // CreationTime: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2025-04-15T19:47:04.130Z"); return t}()), + // ActivationTime: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2025-04-15T19:47:04.130Z"); return t}()), + // CompletedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2025-04-15T19:47:04.130Z"); return t}()), + // OperationErrors: []*armcomputeschedule.OperationErrorDetails{ + // { + // ErrorCode: to.Ptr("awrovoihpnqsotznapyrrb"), + // ErrorDetails: to.Ptr("af"), + // Timestamp: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2025-04-15T19:47:04.131Z"); return t}()), + // TimeStamp: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2025-04-15T19:47:04.131Z"); return t}()), + // AzureOperationName: to.Ptr("ipsoybbslitmwsfkygfjhb"), + // CrpOperationID: to.Ptr("cqkmbfb"), + // }, // }, - // State: to.Ptr(armcomputeschedule.OperationStateSucceeded), - // SubscriptionID: to.Ptr("D8E30CC0-2763-4FCC-84A8-3C5659281032"), - // TimeZone: to.Ptr("UTC"), - // Timezone: to.Ptr("UTC"), + // RequestErrorCode: to.Ptr("vzixjphgeygyhzpbbkgzcjol"), + // RequestErrorDetails: to.Ptr("ficjafazcvbmlbnqhffwtevkla"), // }, - // ResourceID: to.Ptr("/subscriptions/YourSubscriptionId/resourceGroups/YourResourceGroupName/providers/Microsoft.Compute/virtualMachines/testResource3"), - // }}, + // }, + // }, // } } -// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/8a4eca6b060cf70da696963245656fdc440b666b/specification/computeschedule/resource-manager/Microsoft.ComputeSchedule/stable/2024-10-01/examples/ScheduledActions_VirtualMachinesGetOperationErrors.json -func ExampleScheduledActionsClient_VirtualMachinesGetOperationErrors() { +// Generated from example definition: 2025-05-01/ScheduledActions_VirtualMachinesGetOperationErrors_MinimumSet_Gen.json +func ExampleScheduledActionsClient_VirtualMachinesGetOperationErrors_scheduledActionsVirtualMachinesGetOperationErrorsMaximumSetGenGeneratedByMaximumSetRuleGeneratedByMaximumSetRuleGeneratedByMinimumSetRule() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() - clientFactory, err := armcomputeschedule.NewClientFactory("", cred, nil) + clientFactory, err := armcomputeschedule.NewClientFactory("0505D8E4-D41A-48FB-9CA5-4AF8D93BE75F", cred, nil) if err != nil { log.Fatalf("failed to create client: %v", err) } - res, err := clientFactory.NewScheduledActionsClient().VirtualMachinesGetOperationErrors(ctx, "eastus2euap", armcomputeschedule.GetOperationErrorsRequest{ + res, err := clientFactory.NewScheduledActionsClient().VirtualMachinesGetOperationErrors(ctx, "nqwtkslhoamsmxucgbljcz", armcomputeschedule.GetOperationErrorsRequest{ OperationIDs: []*string{ - to.Ptr("23480d2f-1dca-4610-afb4-dd25eec1f34r")}, + to.Ptr("ksufjznokhsbowdupyt"), + }, }, nil) if err != nil { log.Fatalf("failed to finish the request: %v", err) @@ -282,43 +687,32 @@ func ExampleScheduledActionsClient_VirtualMachinesGetOperationErrors() { // You could use response here. We use blank identifier for just demo purposes. _ = res // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. - // res.GetOperationErrorsResponse = armcomputeschedule.GetOperationErrorsResponse{ - // Results: []*armcomputeschedule.OperationErrorsResult{ - // { - // OperationID: to.Ptr("23480d2f-1dca-4610-afb4-dd25eec1f34r"), - // ActivationTime: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2024-11-01T17:52:53.999Z"); return t}()), - // CompletedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2024-11-01T17:52:53.999Z"); return t}()), - // CreationTime: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2024-11-01T17:52:53.999Z"); return t}()), - // OperationErrors: []*armcomputeschedule.OperationErrorDetails{ - // { - // AzureOperationName: to.Ptr("23480d2f-1dca-4610-afb4-dd25eec1f34r"), - // CrpOperationID: to.Ptr("23480d2f-1dca-4610-afb4-dd25eec1f34r"), - // ErrorCode: to.Ptr("null"), - // ErrorDetails: to.Ptr("null"), - // TimeStamp: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2024-11-27T16:55:03.357Z"); return t}()), - // Timestamp: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2024-11-01T17:52:53.999Z"); return t}()), - // }}, - // RequestErrorCode: to.Ptr("null"), - // RequestErrorDetails: to.Ptr("null"), - // }}, + // res = armcomputeschedule.ScheduledActionsClientVirtualMachinesGetOperationErrorsResponse{ + // GetOperationErrorsResponse: &armcomputeschedule.GetOperationErrorsResponse{ + // Results: []*armcomputeschedule.OperationErrorsResult{ + // { + // }, + // }, + // }, // } } -// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/8a4eca6b060cf70da696963245656fdc440b666b/specification/computeschedule/resource-manager/Microsoft.ComputeSchedule/stable/2024-10-01/examples/ScheduledActions_VirtualMachinesGetOperationStatus.json -func ExampleScheduledActionsClient_VirtualMachinesGetOperationStatus() { +// Generated from example definition: 2025-05-01/ScheduledActions_VirtualMachinesGetOperationStatus_MaximumSet_Gen.json +func ExampleScheduledActionsClient_VirtualMachinesGetOperationStatus_scheduledActionsVirtualMachinesGetOperationStatusMaximumSetGenGeneratedByMaximumSetRuleGeneratedByMaximumSetRuleGeneratedByMaximumSetRule() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() - clientFactory, err := armcomputeschedule.NewClientFactory("", cred, nil) + clientFactory, err := armcomputeschedule.NewClientFactory("0505D8E4-D41A-48FB-9CA5-4AF8D93BE75F", cred, nil) if err != nil { log.Fatalf("failed to create client: %v", err) } - res, err := clientFactory.NewScheduledActionsClient().VirtualMachinesGetOperationStatus(ctx, "eastus2euap", armcomputeschedule.GetOperationStatusRequest{ - Correlationid: to.Ptr("35780d2f-1dca-4610-afb4-dd25eec1f34r"), + res, err := clientFactory.NewScheduledActionsClient().VirtualMachinesGetOperationStatus(ctx, "xzbxygykutmvmxpfowdai", armcomputeschedule.GetOperationStatusRequest{ OperationIDs: []*string{ - to.Ptr("23480d2f-1dca-4610-afb4-dd25eec1f34r")}, + to.Ptr("hswzfrierpxdgcuu"), + }, + Correlationid: to.Ptr("jtlszorevrftvfhnqoxlwpiwcbmj"), }, nil) if err != nil { log.Fatalf("failed to finish the request: %v", err) @@ -326,64 +720,216 @@ func ExampleScheduledActionsClient_VirtualMachinesGetOperationStatus() { // You could use response here. We use blank identifier for just demo purposes. _ = res // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. - // res.GetOperationStatusResponse = armcomputeschedule.GetOperationStatusResponse{ - // Results: []*armcomputeschedule.ResourceOperation{ - // { - // ErrorCode: to.Ptr("null"), - // ErrorDetails: to.Ptr("null"), - // Operation: &armcomputeschedule.ResourceOperationDetails{ - // OperationID: to.Ptr("23480d2f-1dca-4610-afb4-dd25eec1f34r"), - // CompletedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2024-11-01T17:52:53.668Z"); return t}()), - // Deadline: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2024-11-01T17:52:53.667Z"); return t}()), - // DeadlineType: to.Ptr(armcomputeschedule.DeadlineTypeInitiateAt), - // OpType: to.Ptr(armcomputeschedule.ResourceOperationTypeDeallocate), + // res = armcomputeschedule.ScheduledActionsClientVirtualMachinesGetOperationStatusResponse{ + // GetOperationStatusResponse: &armcomputeschedule.GetOperationStatusResponse{ + // Results: []*armcomputeschedule.ResourceOperation{ + // { // ResourceID: to.Ptr("/subscriptions/YourSubscriptionId/resourceGroups/YourResourceGroupName/providers/Microsoft.Compute/virtualMachines/testResource3"), - // ResourceOperationError: &armcomputeschedule.ResourceOperationError{ - // ErrorCode: to.Ptr("null"), - // ErrorDetails: to.Ptr("null"), + // ErrorCode: to.Ptr("ynukyltendgmn"), + // ErrorDetails: to.Ptr("tifeuh"), + // Operation: &armcomputeschedule.ResourceOperationDetails{ + // OperationID: to.Ptr("vppyaxq"), + // ResourceID: to.Ptr("/subscriptions/YourSubscriptionId/resourceGroups/YourResourceGroupName/providers/Microsoft.Compute/virtualMachines/testResource3"), + // OpType: to.Ptr(armcomputeschedule.ResourceOperationTypeUnknown), + // SubscriptionID: to.Ptr("vofvsus"), + // Deadline: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2025-04-15T19:47:03.591Z"); return t}()), + // DeadlineType: to.Ptr(armcomputeschedule.DeadlineTypeUnknown), + // State: to.Ptr(armcomputeschedule.OperationStateUnknown), + // Timezone: to.Ptr("nwugsooykqggcokphgdj"), + // TimeZone: to.Ptr("qkxnxnumvfqmsmpyccv"), + // ResourceOperationError: &armcomputeschedule.ResourceOperationError{ + // ErrorCode: to.Ptr("fagfsojftlff"), + // ErrorDetails: to.Ptr("rtihrkjasrjkllqccuysjrg"), + // }, + // CompletedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2025-04-15T19:47:03.591Z"); return t}()), + // RetryPolicy: &armcomputeschedule.RetryPolicy{ + // RetryCount: to.Ptr[int32](25), + // RetryWindowInMinutes: to.Ptr[int32](4), + // }, // }, - // RetryPolicy: &armcomputeschedule.RetryPolicy{ - // RetryCount: to.Ptr[int32](4), - // RetryWindowInMinutes: to.Ptr[int32](27), + // }, + // }, + // }, + // } +} + +// Generated from example definition: 2025-05-01/ScheduledActions_VirtualMachinesGetOperationStatus_MinimumSet_Gen.json +func ExampleScheduledActionsClient_VirtualMachinesGetOperationStatus_scheduledActionsVirtualMachinesGetOperationStatusMaximumSetGenGeneratedByMaximumSetRuleGeneratedByMaximumSetRuleGeneratedByMinimumSetRule() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armcomputeschedule.NewClientFactory("0505D8E4-D41A-48FB-9CA5-4AF8D93BE75F", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + res, err := clientFactory.NewScheduledActionsClient().VirtualMachinesGetOperationStatus(ctx, "egz", armcomputeschedule.GetOperationStatusRequest{ + OperationIDs: []*string{ + to.Ptr("hswzfrierpxdgcuu"), + }, + Correlationid: to.Ptr("jtlszorevrftvfhnqoxlwpiwcbmj"), + }, nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + // You could use response here. We use blank identifier for just demo purposes. + _ = res + // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // res = armcomputeschedule.ScheduledActionsClientVirtualMachinesGetOperationStatusResponse{ + // GetOperationStatusResponse: &armcomputeschedule.GetOperationStatusResponse{ + // Results: []*armcomputeschedule.ResourceOperation{ + // { + // }, + // }, + // }, + // } +} + +// Generated from example definition: 2025-05-01/ScheduledActions_VirtualMachinesSubmitCreate_MaximumSet_Gen.json +func ExampleScheduledActionsClient_VirtualMachinesSubmitCreate_scheduledActionsVirtualMachinesSubmitCreateGeneratedByMaximumSetRule() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armcomputeschedule.NewClientFactory("0505D8E4-D41A-48FB-9CA5-4AF8D93BE75F", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + res, err := clientFactory.NewScheduledActionsClient().VirtualMachinesSubmitCreate(ctx, "msbmrhcjsqsydsq", armcomputeschedule.SubmitCreateRequest{ + Schedule: &armcomputeschedule.Schedule{ + Deadline: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2025-04-15T19:47:04.403Z"); return t }()), + DeadLine: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2025-04-15T19:47:04.403Z"); return t }()), + Timezone: to.Ptr("qacufsmctpgjozovlsihrzoctatcsj"), + TimeZone: to.Ptr("upnmayfebiadztdktxzq"), + DeadlineType: to.Ptr(armcomputeschedule.DeadlineTypeUnknown), + }, + ResourceConfigParameters: &armcomputeschedule.ResourceProvisionPayload{ + BaseProfile: to.Ptr("tfgrulcuneopmbdjydzofmhpa"), + ResourceOverrides: []*string{ + to.Ptr("hsqtjgsobjaffl"), + }, + ResourceCount: to.Ptr[int32](28), + ResourcePrefix: to.Ptr("rqlxavviucrxfjj"), + }, + ExecutionParameters: &armcomputeschedule.ExecutionParameters{ + OptimizationPreference: to.Ptr(armcomputeschedule.OptimizationPreferenceCost), + RetryPolicy: &armcomputeschedule.RetryPolicy{ + RetryCount: to.Ptr[int32](25), + RetryWindowInMinutes: to.Ptr[int32](4), + }, + }, + Correlationid: to.Ptr("muxopzmvkxlowegf"), + }, nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + // You could use response here. We use blank identifier for just demo purposes. + _ = res + // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // res = armcomputeschedule.ScheduledActionsClientVirtualMachinesSubmitCreateResponse{ + // CreateResourceOperationResponse: &armcomputeschedule.CreateResourceOperationResponse{ + // Type: to.Ptr("avmbqoatro"), + // Location: to.Ptr("hhioerbsucdqayxk"), + // Results: []*armcomputeschedule.ResourceOperation{ + // { + // ResourceID: to.Ptr("/subscriptions/YourSubscriptionId/resourceGroups/YourResourceGroupName/providers/Microsoft.Compute/virtualMachines/testResource3"), + // ErrorCode: to.Ptr("ynukyltendgmn"), + // ErrorDetails: to.Ptr("tifeuh"), + // Operation: &armcomputeschedule.ResourceOperationDetails{ + // OperationID: to.Ptr("vppyaxq"), + // ResourceID: to.Ptr("/subscriptions/YourSubscriptionId/resourceGroups/YourResourceGroupName/providers/Microsoft.Compute/virtualMachines/testResource3"), + // OpType: to.Ptr(armcomputeschedule.ResourceOperationTypeUnknown), + // SubscriptionID: to.Ptr("vofvsus"), + // Deadline: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2025-04-15T19:47:03.591Z"); return t}()), + // DeadlineType: to.Ptr(armcomputeschedule.DeadlineTypeUnknown), + // State: to.Ptr(armcomputeschedule.OperationStateUnknown), + // Timezone: to.Ptr("nwugsooykqggcokphgdj"), + // TimeZone: to.Ptr("qkxnxnumvfqmsmpyccv"), + // ResourceOperationError: &armcomputeschedule.ResourceOperationError{ + // ErrorCode: to.Ptr("fagfsojftlff"), + // ErrorDetails: to.Ptr("rtihrkjasrjkllqccuysjrg"), + // }, + // CompletedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2025-04-15T19:47:03.591Z"); return t}()), + // RetryPolicy: &armcomputeschedule.RetryPolicy{ + // RetryCount: to.Ptr[int32](25), + // RetryWindowInMinutes: to.Ptr[int32](4), + // }, // }, - // State: to.Ptr(armcomputeschedule.OperationStateSucceeded), - // SubscriptionID: to.Ptr("D8E30CC0-2763-4FCC-84A8-3C5659281032"), - // TimeZone: to.Ptr("UTC"), - // Timezone: to.Ptr("UTC"), // }, - // ResourceID: to.Ptr("/subscriptions/YourSubscriptionId/resourceGroups/YourResourceGroupName/providers/Microsoft.Compute/virtualMachines/testResource3"), - // }}, + // }, + // Description: to.Ptr("plfajalcmjcxmfuvsbnnoabdqxclto"), + // }, // } } -// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/8a4eca6b060cf70da696963245656fdc440b666b/specification/computeschedule/resource-manager/Microsoft.ComputeSchedule/stable/2024-10-01/examples/ScheduledActions_VirtualMachinesSubmitDeallocate.json -func ExampleScheduledActionsClient_VirtualMachinesSubmitDeallocate() { +// Generated from example definition: 2025-05-01/ScheduledActions_VirtualMachinesSubmitCreate_MinimumSet_Gen.json +func ExampleScheduledActionsClient_VirtualMachinesSubmitCreate_scheduledActionsVirtualMachinesSubmitCreateGeneratedByMinimumSetRule() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() - clientFactory, err := armcomputeschedule.NewClientFactory("", cred, nil) + clientFactory, err := armcomputeschedule.NewClientFactory("0505D8E4-D41A-48FB-9CA5-4AF8D93BE75F", cred, nil) if err != nil { log.Fatalf("failed to create client: %v", err) } - res, err := clientFactory.NewScheduledActionsClient().VirtualMachinesSubmitDeallocate(ctx, "eastus2euap", armcomputeschedule.SubmitDeallocateRequest{ - Correlationid: to.Ptr("23480d2f-1dca-4610-afb4-dd25eec1f34r"), + res, err := clientFactory.NewScheduledActionsClient().VirtualMachinesSubmitCreate(ctx, "hrktusuzoncwpnwohurwlmxfbndt", armcomputeschedule.SubmitCreateRequest{ + Schedule: &armcomputeschedule.Schedule{ + DeadlineType: to.Ptr(armcomputeschedule.DeadlineTypeUnknown), + }, + ResourceConfigParameters: &armcomputeschedule.ResourceProvisionPayload{ + ResourceCount: to.Ptr[int32](28), + }, + }, nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + // You could use response here. We use blank identifier for just demo purposes. + _ = res + // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // res = armcomputeschedule.ScheduledActionsClientVirtualMachinesSubmitCreateResponse{ + // CreateResourceOperationResponse: &armcomputeschedule.CreateResourceOperationResponse{ + // Type: to.Ptr("avmbqoatro"), + // Location: to.Ptr("hhioerbsucdqayxk"), + // Description: to.Ptr("plfajalcmjcxmfuvsbnnoabdqxclto"), + // }, + // } +} + +// Generated from example definition: 2025-05-01/ScheduledActions_VirtualMachinesSubmitDeallocate_MaximumSet_Gen.json +func ExampleScheduledActionsClient_VirtualMachinesSubmitDeallocate_scheduledActionsVirtualMachinesSubmitDeallocateMaximumSetGenGeneratedByMaximumSetRuleGeneratedByMaximumSetRuleGeneratedByMaximumSetRule() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armcomputeschedule.NewClientFactory("0505D8E4-D41A-48FB-9CA5-4AF8D93BE75F", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + res, err := clientFactory.NewScheduledActionsClient().VirtualMachinesSubmitDeallocate(ctx, "mqlftjjfnzubxpricsgstgjojaoah", armcomputeschedule.SubmitDeallocateRequest{ + Schedule: &armcomputeschedule.Schedule{ + Deadline: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2025-04-15T19:47:04.403Z"); return t }()), + DeadLine: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2025-04-15T19:47:04.403Z"); return t }()), + Timezone: to.Ptr("qacufsmctpgjozovlsihrzoctatcsj"), + TimeZone: to.Ptr("upnmayfebiadztdktxzq"), + DeadlineType: to.Ptr(armcomputeschedule.DeadlineTypeUnknown), + }, ExecutionParameters: &armcomputeschedule.ExecutionParameters{ + OptimizationPreference: to.Ptr(armcomputeschedule.OptimizationPreferenceCost), RetryPolicy: &armcomputeschedule.RetryPolicy{ - RetryCount: to.Ptr[int32](4), - RetryWindowInMinutes: to.Ptr[int32](27), + RetryCount: to.Ptr[int32](25), + RetryWindowInMinutes: to.Ptr[int32](4), }, }, Resources: &armcomputeschedule.Resources{ IDs: []*string{ - to.Ptr("/subscriptions/YourSubscriptionId/resourceGroups/YourResourceGroupName/providers/Microsoft.Compute/virtualMachines/testResource3")}, - }, - Schedule: &armcomputeschedule.Schedule{ - Deadline: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2024-11-01T17:52:54.215Z"); return t }()), - DeadlineType: to.Ptr(armcomputeschedule.DeadlineTypeInitiateAt), - Timezone: to.Ptr("UTC"), + to.Ptr("/subscriptions/YourSubscriptionId/resourceGroups/YourResourceGroupName/providers/Microsoft.Compute/virtualMachines/testResource3"), + }, }, + Correlationid: to.Ptr("evmwonebfzxenjdpucgcwdjdya"), }, nil) if err != nil { log.Fatalf("failed to finish the request: %v", err) @@ -391,67 +937,113 @@ func ExampleScheduledActionsClient_VirtualMachinesSubmitDeallocate() { // You could use response here. We use blank identifier for just demo purposes. _ = res // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. - // res.DeallocateResourceOperationResponse = armcomputeschedule.DeallocateResourceOperationResponse{ - // Type: to.Ptr("virtualMachine"), - // Description: to.Ptr("Deallocate Resource Request"), - // Location: to.Ptr("eastus2euap"), - // Results: []*armcomputeschedule.ResourceOperation{ - // { - // ErrorCode: to.Ptr("null"), - // ErrorDetails: to.Ptr("null"), - // Operation: &armcomputeschedule.ResourceOperationDetails{ - // OperationID: to.Ptr("23480d2f-1dca-4610-afb4-dd25eec1f34r"), - // CompletedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2024-11-01T17:52:53.668Z"); return t}()), - // Deadline: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2024-11-01T17:52:53.667Z"); return t}()), - // DeadlineType: to.Ptr(armcomputeschedule.DeadlineTypeInitiateAt), - // OpType: to.Ptr(armcomputeschedule.ResourceOperationTypeDeallocate), + // res = armcomputeschedule.ScheduledActionsClientVirtualMachinesSubmitDeallocateResponse{ + // DeallocateResourceOperationResponse: &armcomputeschedule.DeallocateResourceOperationResponse{ + // Type: to.Ptr("fpnhqvrtbqizlylnwy"), + // Location: to.Ptr("hhioerbsucdqayxk"), + // Results: []*armcomputeschedule.ResourceOperation{ + // { // ResourceID: to.Ptr("/subscriptions/YourSubscriptionId/resourceGroups/YourResourceGroupName/providers/Microsoft.Compute/virtualMachines/testResource3"), - // ResourceOperationError: &armcomputeschedule.ResourceOperationError{ - // ErrorCode: to.Ptr("null"), - // ErrorDetails: to.Ptr("null"), + // ErrorCode: to.Ptr("ynukyltendgmn"), + // ErrorDetails: to.Ptr("tifeuh"), + // Operation: &armcomputeschedule.ResourceOperationDetails{ + // OperationID: to.Ptr("vppyaxq"), + // ResourceID: to.Ptr("/subscriptions/YourSubscriptionId/resourceGroups/YourResourceGroupName/providers/Microsoft.Compute/virtualMachines/testResource3"), + // OpType: to.Ptr(armcomputeschedule.ResourceOperationTypeUnknown), + // SubscriptionID: to.Ptr("vofvsus"), + // Deadline: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2025-04-15T19:47:03.591Z"); return t}()), + // DeadlineType: to.Ptr(armcomputeschedule.DeadlineTypeUnknown), + // State: to.Ptr(armcomputeschedule.OperationStateUnknown), + // Timezone: to.Ptr("nwugsooykqggcokphgdj"), + // TimeZone: to.Ptr("qkxnxnumvfqmsmpyccv"), + // ResourceOperationError: &armcomputeschedule.ResourceOperationError{ + // ErrorCode: to.Ptr("fagfsojftlff"), + // ErrorDetails: to.Ptr("rtihrkjasrjkllqccuysjrg"), + // }, + // CompletedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2025-04-15T19:47:03.591Z"); return t}()), + // RetryPolicy: &armcomputeschedule.RetryPolicy{ + // RetryCount: to.Ptr[int32](25), + // RetryWindowInMinutes: to.Ptr[int32](4), + // }, // }, - // RetryPolicy: &armcomputeschedule.RetryPolicy{ - // RetryCount: to.Ptr[int32](4), - // RetryWindowInMinutes: to.Ptr[int32](27), - // }, - // State: to.Ptr(armcomputeschedule.OperationStateSucceeded), - // SubscriptionID: to.Ptr("D8E30CC0-2763-4FCC-84A8-3C5659281032"), - // TimeZone: to.Ptr("UTC"), - // Timezone: to.Ptr("UTC"), // }, - // ResourceID: to.Ptr("/subscriptions/YourSubscriptionId/resourceGroups/YourResourceGroupName/providers/Microsoft.Compute/virtualMachines/testResource3"), - // }}, + // }, + // Description: to.Ptr("zknbxgebvymhzzmsbrlaqreub"), + // }, // } } -// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/8a4eca6b060cf70da696963245656fdc440b666b/specification/computeschedule/resource-manager/Microsoft.ComputeSchedule/stable/2024-10-01/examples/ScheduledActions_VirtualMachinesSubmitHibernate.json -func ExampleScheduledActionsClient_VirtualMachinesSubmitHibernate() { +// Generated from example definition: 2025-05-01/ScheduledActions_VirtualMachinesSubmitDeallocate_MinimumSet_Gen.json +func ExampleScheduledActionsClient_VirtualMachinesSubmitDeallocate_scheduledActionsVirtualMachinesSubmitDeallocateMaximumSetGenGeneratedByMaximumSetRuleGeneratedByMaximumSetRuleGeneratedByMinimumSetRule() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() - clientFactory, err := armcomputeschedule.NewClientFactory("", cred, nil) + clientFactory, err := armcomputeschedule.NewClientFactory("0505D8E4-D41A-48FB-9CA5-4AF8D93BE75F", cred, nil) if err != nil { log.Fatalf("failed to create client: %v", err) } - res, err := clientFactory.NewScheduledActionsClient().VirtualMachinesSubmitHibernate(ctx, "eastus2euap", armcomputeschedule.SubmitHibernateRequest{ - Correlationid: to.Ptr("23480d2f-1dca-4610-afb4-dd25eec1f34r"), + res, err := clientFactory.NewScheduledActionsClient().VirtualMachinesSubmitDeallocate(ctx, "xrcabowpojl", armcomputeschedule.SubmitDeallocateRequest{ + Schedule: &armcomputeschedule.Schedule{ + DeadlineType: to.Ptr(armcomputeschedule.DeadlineTypeUnknown), + }, + ExecutionParameters: &armcomputeschedule.ExecutionParameters{}, + Resources: &armcomputeschedule.Resources{ + IDs: []*string{ + to.Ptr("/subscriptions/YourSubscriptionId/resourceGroups/YourResourceGroupName/providers/Microsoft.Compute/virtualMachines/testResource3"), + }, + }, + Correlationid: to.Ptr("evmwonebfzxenjdpucgcwdjdya"), + }, nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + // You could use response here. We use blank identifier for just demo purposes. + _ = res + // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // res = armcomputeschedule.ScheduledActionsClientVirtualMachinesSubmitDeallocateResponse{ + // DeallocateResourceOperationResponse: &armcomputeschedule.DeallocateResourceOperationResponse{ + // Type: to.Ptr("fpnhqvrtbqizlylnwy"), + // Location: to.Ptr("hhioerbsucdqayxk"), + // Description: to.Ptr("zknbxgebvymhzzmsbrlaqreub"), + // }, + // } +} + +// Generated from example definition: 2025-05-01/ScheduledActions_VirtualMachinesSubmitDelete_MaximumSet_Gen.json +func ExampleScheduledActionsClient_VirtualMachinesSubmitDelete_scheduledActionsVirtualMachinesSubmitDeleteGeneratedByMaximumSetRule() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armcomputeschedule.NewClientFactory("0505D8E4-D41A-48FB-9CA5-4AF8D93BE75F", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + res, err := clientFactory.NewScheduledActionsClient().VirtualMachinesSubmitDelete(ctx, "ppjqysfqumddvzzs", armcomputeschedule.SubmitDeleteRequest{ + Schedule: &armcomputeschedule.Schedule{ + Deadline: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2025-04-15T19:47:04.403Z"); return t }()), + DeadLine: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2025-04-15T19:47:04.403Z"); return t }()), + Timezone: to.Ptr("qacufsmctpgjozovlsihrzoctatcsj"), + TimeZone: to.Ptr("upnmayfebiadztdktxzq"), + DeadlineType: to.Ptr(armcomputeschedule.DeadlineTypeUnknown), + }, ExecutionParameters: &armcomputeschedule.ExecutionParameters{ + OptimizationPreference: to.Ptr(armcomputeschedule.OptimizationPreferenceCost), RetryPolicy: &armcomputeschedule.RetryPolicy{ - RetryCount: to.Ptr[int32](2), - RetryWindowInMinutes: to.Ptr[int32](27), + RetryCount: to.Ptr[int32](25), + RetryWindowInMinutes: to.Ptr[int32](4), }, }, Resources: &armcomputeschedule.Resources{ IDs: []*string{ - to.Ptr("/subscriptions/YourSubscriptionId/resourceGroups/YourResourceGroupName/providers/Microsoft.Compute/virtualMachines/testResource3")}, - }, - Schedule: &armcomputeschedule.Schedule{ - Deadline: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2024-11-01T17:52:54.215Z"); return t }()), - DeadlineType: to.Ptr(armcomputeschedule.DeadlineTypeInitiateAt), - Timezone: to.Ptr("UTC"), + to.Ptr("/subscriptions/YourSubscriptionId/resourceGroups/YourResourceGroupName/providers/Microsoft.Compute/virtualMachines/testResource3"), + }, }, + Correlationid: to.Ptr("e"), + ForceDeletion: to.Ptr(true), }, nil) if err != nil { log.Fatalf("failed to finish the request: %v", err) @@ -459,67 +1051,176 @@ func ExampleScheduledActionsClient_VirtualMachinesSubmitHibernate() { // You could use response here. We use blank identifier for just demo purposes. _ = res // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. - // res.HibernateResourceOperationResponse = armcomputeschedule.HibernateResourceOperationResponse{ - // Type: to.Ptr("virtualMachine"), - // Description: to.Ptr("Hibernate Resource Request"), - // Location: to.Ptr("eastus2euap"), - // Results: []*armcomputeschedule.ResourceOperation{ - // { - // ErrorCode: to.Ptr("null"), - // ErrorDetails: to.Ptr("null"), - // Operation: &armcomputeschedule.ResourceOperationDetails{ - // OperationID: to.Ptr("23480d2f-1dca-4610-afb4-dd25eec1f34r"), - // CompletedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2024-11-01T17:52:53.668Z"); return t}()), - // Deadline: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2024-11-01T17:52:53.667Z"); return t}()), - // DeadlineType: to.Ptr(armcomputeschedule.DeadlineTypeInitiateAt), - // OpType: to.Ptr(armcomputeschedule.ResourceOperationTypeHibernate), + // res = armcomputeschedule.ScheduledActionsClientVirtualMachinesSubmitDeleteResponse{ + // DeleteResourceOperationResponse: &armcomputeschedule.DeleteResourceOperationResponse{ + // Type: to.Ptr("tauhekvwziataptcsyqtfpq"), + // Location: to.Ptr("hhioerbsucdqayxk"), + // Results: []*armcomputeschedule.ResourceOperation{ + // { // ResourceID: to.Ptr("/subscriptions/YourSubscriptionId/resourceGroups/YourResourceGroupName/providers/Microsoft.Compute/virtualMachines/testResource3"), - // ResourceOperationError: &armcomputeschedule.ResourceOperationError{ - // ErrorCode: to.Ptr("null"), - // ErrorDetails: to.Ptr("null"), - // }, - // RetryPolicy: &armcomputeschedule.RetryPolicy{ - // RetryCount: to.Ptr[int32](2), - // RetryWindowInMinutes: to.Ptr[int32](27), + // ErrorCode: to.Ptr("ynukyltendgmn"), + // ErrorDetails: to.Ptr("tifeuh"), + // Operation: &armcomputeschedule.ResourceOperationDetails{ + // OperationID: to.Ptr("vppyaxq"), + // ResourceID: to.Ptr("/subscriptions/YourSubscriptionId/resourceGroups/YourResourceGroupName/providers/Microsoft.Compute/virtualMachines/testResource3"), + // OpType: to.Ptr(armcomputeschedule.ResourceOperationTypeUnknown), + // SubscriptionID: to.Ptr("vofvsus"), + // Deadline: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2025-04-15T19:47:03.591Z"); return t}()), + // DeadlineType: to.Ptr(armcomputeschedule.DeadlineTypeUnknown), + // State: to.Ptr(armcomputeschedule.OperationStateUnknown), + // Timezone: to.Ptr("nwugsooykqggcokphgdj"), + // TimeZone: to.Ptr("qkxnxnumvfqmsmpyccv"), + // ResourceOperationError: &armcomputeschedule.ResourceOperationError{ + // ErrorCode: to.Ptr("fagfsojftlff"), + // ErrorDetails: to.Ptr("rtihrkjasrjkllqccuysjrg"), + // }, + // CompletedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2025-04-15T19:47:03.591Z"); return t}()), + // RetryPolicy: &armcomputeschedule.RetryPolicy{ + // RetryCount: to.Ptr[int32](25), + // RetryWindowInMinutes: to.Ptr[int32](4), + // }, // }, - // State: to.Ptr(armcomputeschedule.OperationStateSucceeded), - // SubscriptionID: to.Ptr("D8E30CC0-2763-4FCC-84A8-3C5659281032"), - // TimeZone: to.Ptr("UTC"), - // Timezone: to.Ptr("UTC"), // }, - // ResourceID: to.Ptr("/subscriptions/YourSubscriptionId/resourceGroups/YourResourceGroupName/providers/Microsoft.Compute/virtualMachines/testResource3"), - // }}, + // }, + // Description: to.Ptr("fxgbwqglaskyb"), + // }, // } } -// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/8a4eca6b060cf70da696963245656fdc440b666b/specification/computeschedule/resource-manager/Microsoft.ComputeSchedule/stable/2024-10-01/examples/ScheduledActions_VirtualMachinesSubmitStart.json -func ExampleScheduledActionsClient_VirtualMachinesSubmitStart() { +// Generated from example definition: 2025-05-01/ScheduledActions_VirtualMachinesSubmitDelete_MinimumSet_Gen.json +func ExampleScheduledActionsClient_VirtualMachinesSubmitDelete_scheduledActionsVirtualMachinesSubmitDeleteGeneratedByMinimumSetRule() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() - clientFactory, err := armcomputeschedule.NewClientFactory("", cred, nil) + clientFactory, err := armcomputeschedule.NewClientFactory("0505D8E4-D41A-48FB-9CA5-4AF8D93BE75F", cred, nil) if err != nil { log.Fatalf("failed to create client: %v", err) } - res, err := clientFactory.NewScheduledActionsClient().VirtualMachinesSubmitStart(ctx, "eastus2euap", armcomputeschedule.SubmitStartRequest{ - Correlationid: to.Ptr("23480d2f-1dca-4610-afb4-dd25eec1f34r"), + res, err := clientFactory.NewScheduledActionsClient().VirtualMachinesSubmitDelete(ctx, "xsllpkyjquhhumdidsl", armcomputeschedule.SubmitDeleteRequest{ + Schedule: &armcomputeschedule.Schedule{ + DeadlineType: to.Ptr(armcomputeschedule.DeadlineTypeUnknown), + }, + ExecutionParameters: &armcomputeschedule.ExecutionParameters{}, + Resources: &armcomputeschedule.Resources{ + IDs: []*string{ + to.Ptr("/subscriptions/YourSubscriptionId/resourceGroups/YourResourceGroupName/providers/Microsoft.Compute/virtualMachines/testResource3"), + }, + }, + }, nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + // You could use response here. We use blank identifier for just demo purposes. + _ = res + // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // res = armcomputeschedule.ScheduledActionsClientVirtualMachinesSubmitDeleteResponse{ + // DeleteResourceOperationResponse: &armcomputeschedule.DeleteResourceOperationResponse{ + // Type: to.Ptr("tauhekvwziataptcsyqtfpq"), + // Location: to.Ptr("hhioerbsucdqayxk"), + // Description: to.Ptr("fxgbwqglaskyb"), + // }, + // } +} + +// Generated from example definition: 2025-05-01/ScheduledActions_VirtualMachinesSubmitHibernate_MaximumSet_Gen.json +func ExampleScheduledActionsClient_VirtualMachinesSubmitHibernate_scheduledActionsVirtualMachinesSubmitHibernateMaximumSetGenGeneratedByMaximumSetRuleGeneratedByMaximumSetRuleGeneratedByMaximumSetRule() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armcomputeschedule.NewClientFactory("0505D8E4-D41A-48FB-9CA5-4AF8D93BE75F", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + res, err := clientFactory.NewScheduledActionsClient().VirtualMachinesSubmitHibernate(ctx, "hiceqzwkjmijxdfw", armcomputeschedule.SubmitHibernateRequest{ + Schedule: &armcomputeschedule.Schedule{ + Deadline: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2025-04-15T19:47:04.403Z"); return t }()), + DeadLine: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2025-04-15T19:47:04.403Z"); return t }()), + Timezone: to.Ptr("qacufsmctpgjozovlsihrzoctatcsj"), + TimeZone: to.Ptr("upnmayfebiadztdktxzq"), + DeadlineType: to.Ptr(armcomputeschedule.DeadlineTypeUnknown), + }, ExecutionParameters: &armcomputeschedule.ExecutionParameters{ + OptimizationPreference: to.Ptr(armcomputeschedule.OptimizationPreferenceCost), RetryPolicy: &armcomputeschedule.RetryPolicy{ - RetryCount: to.Ptr[int32](5), - RetryWindowInMinutes: to.Ptr[int32](27), + RetryCount: to.Ptr[int32](25), + RetryWindowInMinutes: to.Ptr[int32](4), }, }, Resources: &armcomputeschedule.Resources{ IDs: []*string{ - to.Ptr("/subscriptions/YourSubscriptionId/resourceGroups/YourResourceGroupName/providers/Microsoft.Compute/virtualMachines/testResource3")}, + to.Ptr("/subscriptions/YourSubscriptionId/resourceGroups/YourResourceGroupName/providers/Microsoft.Compute/virtualMachines/testResource3"), + }, }, + Correlationid: to.Ptr("htqivutynuoslvbp"), + }, nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + // You could use response here. We use blank identifier for just demo purposes. + _ = res + // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // res = armcomputeschedule.ScheduledActionsClientVirtualMachinesSubmitHibernateResponse{ + // HibernateResourceOperationResponse: &armcomputeschedule.HibernateResourceOperationResponse{ + // Type: to.Ptr("yrmuumqaqiyotst"), + // Location: to.Ptr("hhioerbsucdqayxk"), + // Results: []*armcomputeschedule.ResourceOperation{ + // { + // ResourceID: to.Ptr("/subscriptions/YourSubscriptionId/resourceGroups/YourResourceGroupName/providers/Microsoft.Compute/virtualMachines/testResource3"), + // ErrorCode: to.Ptr("ynukyltendgmn"), + // ErrorDetails: to.Ptr("tifeuh"), + // Operation: &armcomputeschedule.ResourceOperationDetails{ + // OperationID: to.Ptr("vppyaxq"), + // ResourceID: to.Ptr("/subscriptions/YourSubscriptionId/resourceGroups/YourResourceGroupName/providers/Microsoft.Compute/virtualMachines/testResource3"), + // OpType: to.Ptr(armcomputeschedule.ResourceOperationTypeUnknown), + // SubscriptionID: to.Ptr("vofvsus"), + // Deadline: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2025-04-15T19:47:03.591Z"); return t}()), + // DeadlineType: to.Ptr(armcomputeschedule.DeadlineTypeUnknown), + // State: to.Ptr(armcomputeschedule.OperationStateUnknown), + // Timezone: to.Ptr("nwugsooykqggcokphgdj"), + // TimeZone: to.Ptr("qkxnxnumvfqmsmpyccv"), + // ResourceOperationError: &armcomputeschedule.ResourceOperationError{ + // ErrorCode: to.Ptr("fagfsojftlff"), + // ErrorDetails: to.Ptr("rtihrkjasrjkllqccuysjrg"), + // }, + // CompletedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2025-04-15T19:47:03.591Z"); return t}()), + // RetryPolicy: &armcomputeschedule.RetryPolicy{ + // RetryCount: to.Ptr[int32](25), + // RetryWindowInMinutes: to.Ptr[int32](4), + // }, + // }, + // }, + // }, + // Description: to.Ptr("ogyqdzdslyvxslrykb"), + // }, + // } +} + +// Generated from example definition: 2025-05-01/ScheduledActions_VirtualMachinesSubmitHibernate_MinimumSet_Gen.json +func ExampleScheduledActionsClient_VirtualMachinesSubmitHibernate_scheduledActionsVirtualMachinesSubmitHibernateMaximumSetGenGeneratedByMaximumSetRuleGeneratedByMaximumSetRuleGeneratedByMinimumSetRule() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armcomputeschedule.NewClientFactory("0505D8E4-D41A-48FB-9CA5-4AF8D93BE75F", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + res, err := clientFactory.NewScheduledActionsClient().VirtualMachinesSubmitHibernate(ctx, "jsbmestfaqxxejcgrs", armcomputeschedule.SubmitHibernateRequest{ Schedule: &armcomputeschedule.Schedule{ - Deadline: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2024-11-01T17:52:54.215Z"); return t }()), - DeadlineType: to.Ptr(armcomputeschedule.DeadlineTypeInitiateAt), - Timezone: to.Ptr("UTC"), + DeadlineType: to.Ptr(armcomputeschedule.DeadlineTypeUnknown), + }, + ExecutionParameters: &armcomputeschedule.ExecutionParameters{}, + Resources: &armcomputeschedule.Resources{ + IDs: []*string{ + to.Ptr("/subscriptions/YourSubscriptionId/resourceGroups/YourResourceGroupName/providers/Microsoft.Compute/virtualMachines/testResource3"), + }, }, + Correlationid: to.Ptr("htqivutynuoslvbp"), }, nil) if err != nil { log.Fatalf("failed to finish the request: %v", err) @@ -527,35 +1228,124 @@ func ExampleScheduledActionsClient_VirtualMachinesSubmitStart() { // You could use response here. We use blank identifier for just demo purposes. _ = res // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. - // res.StartResourceOperationResponse = armcomputeschedule.StartResourceOperationResponse{ - // Type: to.Ptr("virtualMachine"), - // Description: to.Ptr("Start Resource Request"), - // Location: to.Ptr("eastus2euap"), - // Results: []*armcomputeschedule.ResourceOperation{ - // { - // ErrorCode: to.Ptr("null"), - // ErrorDetails: to.Ptr("null"), - // Operation: &armcomputeschedule.ResourceOperationDetails{ - // OperationID: to.Ptr("23480d2f-1dca-4610-afb4-dd25eec1f34r"), - // CompletedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2024-11-01T17:52:53.668Z"); return t}()), - // Deadline: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2024-11-01T17:52:53.667Z"); return t}()), - // DeadlineType: to.Ptr(armcomputeschedule.DeadlineTypeInitiateAt), - // OpType: to.Ptr(armcomputeschedule.ResourceOperationTypeStart), + // res = armcomputeschedule.ScheduledActionsClientVirtualMachinesSubmitHibernateResponse{ + // HibernateResourceOperationResponse: &armcomputeschedule.HibernateResourceOperationResponse{ + // Type: to.Ptr("yrmuumqaqiyotst"), + // Location: to.Ptr("hhioerbsucdqayxk"), + // Description: to.Ptr("ogyqdzdslyvxslrykb"), + // }, + // } +} + +// Generated from example definition: 2025-05-01/ScheduledActions_VirtualMachinesSubmitStart_MaximumSet_Gen.json +func ExampleScheduledActionsClient_VirtualMachinesSubmitStart_scheduledActionsVirtualMachinesSubmitStartMaximumSetGenGeneratedByMaximumSetRuleGeneratedByMaximumSetRuleGeneratedByMaximumSetRule() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armcomputeschedule.NewClientFactory("0505D8E4-D41A-48FB-9CA5-4AF8D93BE75F", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + res, err := clientFactory.NewScheduledActionsClient().VirtualMachinesSubmitStart(ctx, "klvdoznxekrxhuvgeels", armcomputeschedule.SubmitStartRequest{ + Schedule: &armcomputeschedule.Schedule{ + Deadline: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2025-04-15T19:47:04.403Z"); return t }()), + DeadLine: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2025-04-15T19:47:04.403Z"); return t }()), + Timezone: to.Ptr("qacufsmctpgjozovlsihrzoctatcsj"), + TimeZone: to.Ptr("upnmayfebiadztdktxzq"), + DeadlineType: to.Ptr(armcomputeschedule.DeadlineTypeUnknown), + }, + ExecutionParameters: &armcomputeschedule.ExecutionParameters{ + OptimizationPreference: to.Ptr(armcomputeschedule.OptimizationPreferenceCost), + RetryPolicy: &armcomputeschedule.RetryPolicy{ + RetryCount: to.Ptr[int32](25), + RetryWindowInMinutes: to.Ptr[int32](4), + }, + }, + Resources: &armcomputeschedule.Resources{ + IDs: []*string{ + to.Ptr("/subscriptions/YourSubscriptionId/resourceGroups/YourResourceGroupName/providers/Microsoft.Compute/virtualMachines/testResource3"), + }, + }, + Correlationid: to.Ptr("bvmpxvbd"), + }, nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + // You could use response here. We use blank identifier for just demo purposes. + _ = res + // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // res = armcomputeschedule.ScheduledActionsClientVirtualMachinesSubmitStartResponse{ + // StartResourceOperationResponse: &armcomputeschedule.StartResourceOperationResponse{ + // Type: to.Ptr("lcikdomhndewkiqpf"), + // Location: to.Ptr("hhioerbsucdqayxk"), + // Results: []*armcomputeschedule.ResourceOperation{ + // { // ResourceID: to.Ptr("/subscriptions/YourSubscriptionId/resourceGroups/YourResourceGroupName/providers/Microsoft.Compute/virtualMachines/testResource3"), - // ResourceOperationError: &armcomputeschedule.ResourceOperationError{ - // ErrorCode: to.Ptr("null"), - // ErrorDetails: to.Ptr("null"), - // }, - // RetryPolicy: &armcomputeschedule.RetryPolicy{ - // RetryCount: to.Ptr[int32](5), - // RetryWindowInMinutes: to.Ptr[int32](27), + // ErrorCode: to.Ptr("ynukyltendgmn"), + // ErrorDetails: to.Ptr("tifeuh"), + // Operation: &armcomputeschedule.ResourceOperationDetails{ + // OperationID: to.Ptr("vppyaxq"), + // ResourceID: to.Ptr("/subscriptions/YourSubscriptionId/resourceGroups/YourResourceGroupName/providers/Microsoft.Compute/virtualMachines/testResource3"), + // OpType: to.Ptr(armcomputeschedule.ResourceOperationTypeUnknown), + // SubscriptionID: to.Ptr("vofvsus"), + // Deadline: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2025-04-15T19:47:03.591Z"); return t}()), + // DeadlineType: to.Ptr(armcomputeschedule.DeadlineTypeUnknown), + // State: to.Ptr(armcomputeschedule.OperationStateUnknown), + // Timezone: to.Ptr("nwugsooykqggcokphgdj"), + // TimeZone: to.Ptr("qkxnxnumvfqmsmpyccv"), + // ResourceOperationError: &armcomputeschedule.ResourceOperationError{ + // ErrorCode: to.Ptr("fagfsojftlff"), + // ErrorDetails: to.Ptr("rtihrkjasrjkllqccuysjrg"), + // }, + // CompletedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2025-04-15T19:47:03.591Z"); return t}()), + // RetryPolicy: &armcomputeschedule.RetryPolicy{ + // RetryCount: to.Ptr[int32](25), + // RetryWindowInMinutes: to.Ptr[int32](4), + // }, // }, - // State: to.Ptr(armcomputeschedule.OperationStateSucceeded), - // SubscriptionID: to.Ptr("D8E30CC0-2763-4FCC-84A8-3C5659281032"), - // TimeZone: to.Ptr("UTC"), - // Timezone: to.Ptr("UTC"), // }, - // ResourceID: to.Ptr("/subscriptions/YourSubscriptionId/resourceGroups/YourResourceGroupName/providers/Microsoft.Compute/virtualMachines/testResource3"), - // }}, + // }, + // Description: to.Ptr("mqfxdgracoxwwpoegjryov"), + // }, + // } +} + +// Generated from example definition: 2025-05-01/ScheduledActions_VirtualMachinesSubmitStart_MinimumSet_Gen.json +func ExampleScheduledActionsClient_VirtualMachinesSubmitStart_scheduledActionsVirtualMachinesSubmitStartMaximumSetGenGeneratedByMaximumSetRuleGeneratedByMaximumSetRuleGeneratedByMinimumSetRule() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armcomputeschedule.NewClientFactory("0505D8E4-D41A-48FB-9CA5-4AF8D93BE75F", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + res, err := clientFactory.NewScheduledActionsClient().VirtualMachinesSubmitStart(ctx, "rbsdwsfprygqqwqhwapovusm", armcomputeschedule.SubmitStartRequest{ + Schedule: &armcomputeschedule.Schedule{ + DeadlineType: to.Ptr(armcomputeschedule.DeadlineTypeUnknown), + }, + ExecutionParameters: &armcomputeschedule.ExecutionParameters{}, + Resources: &armcomputeschedule.Resources{ + IDs: []*string{ + to.Ptr("/subscriptions/YourSubscriptionId/resourceGroups/YourResourceGroupName/providers/Microsoft.Compute/virtualMachines/testResource3"), + }, + }, + Correlationid: to.Ptr("bvmpxvbd"), + }, nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + // You could use response here. We use blank identifier for just demo purposes. + _ = res + // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // res = armcomputeschedule.ScheduledActionsClientVirtualMachinesSubmitStartResponse{ + // StartResourceOperationResponse: &armcomputeschedule.StartResourceOperationResponse{ + // Type: to.Ptr("lcikdomhndewkiqpf"), + // Location: to.Ptr("hhioerbsucdqayxk"), + // Description: to.Ptr("mqfxdgracoxwwpoegjryov"), + // }, // } } diff --git a/sdk/resourcemanager/computeschedule/armcomputeschedule/time_rfc3339.go b/sdk/resourcemanager/computeschedule/armcomputeschedule/time_rfc3339.go index c69bdcbe0925..2dbbfdf7d0e9 100644 --- a/sdk/resourcemanager/computeschedule/armcomputeschedule/time_rfc3339.go +++ b/sdk/resourcemanager/computeschedule/armcomputeschedule/time_rfc3339.go @@ -1,10 +1,6 @@ -//go:build go1.18 -// +build go1.18 - // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. -// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. package armcomputeschedule @@ -60,6 +56,9 @@ func (t *dateTimeRFC3339) UnmarshalJSON(data []byte) error { } 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 diff --git a/sdk/resourcemanager/computeschedule/armcomputeschedule/tsp-location.yaml b/sdk/resourcemanager/computeschedule/armcomputeschedule/tsp-location.yaml new file mode 100644 index 000000000000..46827aab7e44 --- /dev/null +++ b/sdk/resourcemanager/computeschedule/armcomputeschedule/tsp-location.yaml @@ -0,0 +1,4 @@ +directory: specification/computeschedule/ComputeSchedule.Management +commit: 1f578543d267d08febc1bebf4e33ffe14363ddfc +repo: Azure/azure-rest-api-specs +additionalDirectories: diff --git a/sdk/resourcemanager/containerservicefleet/armcontainerservicefleet/CHANGELOG.md b/sdk/resourcemanager/containerservicefleet/armcontainerservicefleet/CHANGELOG.md index 4d1b80d8680a..69bef50c1a96 100644 --- a/sdk/resourcemanager/containerservicefleet/armcontainerservicefleet/CHANGELOG.md +++ b/sdk/resourcemanager/containerservicefleet/armcontainerservicefleet/CHANGELOG.md @@ -1,5 +1,50 @@ # Release History +## 2.0.0 (2025-04-27) +### Breaking Changes + +- Type of `ErrorAdditionalInfo.Info` has been changed from `any` to `*ErrorAdditionalInfoInfo` +- `ManagedServiceIdentityTypeSystemAssignedUserAssigned` from enum `ManagedServiceIdentityType` has been removed +- Function `*FleetMembersClient.BeginUpdate` has been removed +- Function `*FleetsClient.BeginCreateOrUpdate` has been removed +- Function `*FleetsClient.BeginUpdate` has been removed + +### Features Added + +- New value `ManagedServiceIdentityTypeSystemAndUserAssigned` added to enum type `ManagedServiceIdentityType` +- New value `NodeImageSelectionTypeCustom` added to enum type `NodeImageSelectionType` +- New enum type `AutoUpgradeLastTriggerStatus` with values `AutoUpgradeLastTriggerStatusFailed`, `AutoUpgradeLastTriggerStatusSucceeded` +- New enum type `AutoUpgradeNodeImageSelectionType` with values `AutoUpgradeNodeImageSelectionTypeConsistent`, `AutoUpgradeNodeImageSelectionTypeLatest` +- New enum type `AutoUpgradeProfileProvisioningState` with values `AutoUpgradeProfileProvisioningStateCanceled`, `AutoUpgradeProfileProvisioningStateFailed`, `AutoUpgradeProfileProvisioningStateSucceeded` +- New enum type `UpgradeChannel` with values `UpgradeChannelNodeImage`, `UpgradeChannelRapid`, `UpgradeChannelStable` +- New function `NewAutoUpgradeProfileOperationsClient(string, azcore.TokenCredential, *arm.ClientOptions) (*AutoUpgradeProfileOperationsClient, error)` +- New function `*AutoUpgradeProfileOperationsClient.BeginGenerateUpdateRun(context.Context, string, string, string, *AutoUpgradeProfileOperationsClientBeginGenerateUpdateRunOptions) (*runtime.Poller[AutoUpgradeProfileOperationsClientGenerateUpdateRunResponse], error)` +- New function `NewAutoUpgradeProfilesClient(string, azcore.TokenCredential, *arm.ClientOptions) (*AutoUpgradeProfilesClient, error)` +- New function `*AutoUpgradeProfilesClient.BeginCreateOrUpdate(context.Context, string, string, string, AutoUpgradeProfile, *AutoUpgradeProfilesClientBeginCreateOrUpdateOptions) (*runtime.Poller[AutoUpgradeProfilesClientCreateOrUpdateResponse], error)` +- New function `*AutoUpgradeProfilesClient.BeginDelete(context.Context, string, string, string, *AutoUpgradeProfilesClientBeginDeleteOptions) (*runtime.Poller[AutoUpgradeProfilesClientDeleteResponse], error)` +- New function `*AutoUpgradeProfilesClient.Get(context.Context, string, string, string, *AutoUpgradeProfilesClientGetOptions) (AutoUpgradeProfilesClientGetResponse, error)` +- New function `*AutoUpgradeProfilesClient.NewListByFleetPager(string, string, *AutoUpgradeProfilesClientListByFleetOptions) *runtime.Pager[AutoUpgradeProfilesClientListByFleetResponse]` +- New function `*ClientFactory.NewAutoUpgradeProfileOperationsClient() *AutoUpgradeProfileOperationsClient` +- New function `*ClientFactory.NewAutoUpgradeProfilesClient() *AutoUpgradeProfilesClient` +- New function `*FleetMembersClient.BeginUpdateAsync(context.Context, string, string, string, FleetMemberUpdate, *FleetMembersClientBeginUpdateAsyncOptions) (*runtime.Poller[FleetMembersClientUpdateAsyncResponse], error)` +- New function `*FleetsClient.BeginCreate(context.Context, string, string, Fleet, *FleetsClientBeginCreateOptions) (*runtime.Poller[FleetsClientCreateResponse], error)` +- New function `*FleetsClient.BeginUpdateAsync(context.Context, string, string, FleetPatch, *FleetsClientBeginUpdateAsyncOptions) (*runtime.Poller[FleetsClientUpdateAsyncResponse], error)` +- New struct `AutoUpgradeNodeImageSelection` +- New struct `AutoUpgradeProfile` +- New struct `AutoUpgradeProfileListResult` +- New struct `AutoUpgradeProfileProperties` +- New struct `AutoUpgradeProfileStatus` +- New struct `ErrorAdditionalInfoInfo` +- New struct `FleetMemberStatus` +- New struct `FleetStatus` +- New struct `GenerateResponse` +- New field `EnableVnetIntegration`, `SubnetID` in struct `APIServerAccessProfile` +- New field `Status` in struct `FleetMemberProperties` +- New field `Status` in struct `FleetProperties` +- New field `CustomNodeImageVersions` in struct `NodeImageSelection` +- New field `AutoUpgradeProfileID` in struct `UpdateRunProperties` + + ## 2.0.0 (2025-04-15) ### Breaking Changes diff --git a/sdk/resourcemanager/containerservicefleet/armcontainerservicefleet/autoupgradeprofiles_client_example_test.go b/sdk/resourcemanager/containerservicefleet/armcontainerservicefleet/autoupgradeprofiles_client_example_test.go index bb13d12cf285..bd6ef68c8543 100644 --- a/sdk/resourcemanager/containerservicefleet/armcontainerservicefleet/autoupgradeprofiles_client_example_test.go +++ b/sdk/resourcemanager/containerservicefleet/armcontainerservicefleet/autoupgradeprofiles_client_example_test.go @@ -83,9 +83,9 @@ func ExampleAutoUpgradeProfilesClient_BeginCreateOrUpdate_createAnAutoUpgradePro LastTriggerError: &armcontainerservicefleet.ErrorDetail{}, }, }, - }, &armcontainerservicefleet.AutoUpgradeProfilesClientBeginCreateOrUpdateOptions{ - IfMatch: to.Ptr("teikqmg"), - IfNoneMatch: to.Ptr("ghfmmyrekxincsxklbldnvhqd")}) + }, &AutoUpgradeProfilesClientBeginCreateOrUpdateOptions{ + ifMatch: to.Ptr("teikqmg"), + ifNoneMatch: to.Ptr("ghfmmyrekxincsxklbldnvhqd")}) if err != nil { log.Fatalf("failed to finish the request: %v", err) } @@ -176,8 +176,8 @@ func ExampleAutoUpgradeProfilesClient_BeginDelete_deleteAnAutoUpgradeProfileReso if err != nil { log.Fatalf("failed to create client: %v", err) } - poller, err := clientFactory.NewAutoUpgradeProfilesClient().BeginDelete(ctx, "rgfleets", "fleet1", "autoupgradeprofile1", &armcontainerservicefleet.AutoUpgradeProfilesClientBeginDeleteOptions{ - IfMatch: to.Ptr("qmdsmmawj")}) + poller, err := clientFactory.NewAutoUpgradeProfilesClient().BeginDelete(ctx, "rgfleets", "fleet1", "autoupgradeprofile1", &AutoUpgradeProfilesClientBeginDeleteOptions{ + ifMatch: to.Ptr("qmdsmmawj")}) if err != nil { log.Fatalf("failed to finish the request: %v", err) } diff --git a/sdk/resourcemanager/containerservicefleet/armcontainerservicefleet/fleetmembers_client_example_test.go b/sdk/resourcemanager/containerservicefleet/armcontainerservicefleet/fleetmembers_client_example_test.go index 9434dbbfa8cc..aa5ce71989c7 100644 --- a/sdk/resourcemanager/containerservicefleet/armcontainerservicefleet/fleetmembers_client_example_test.go +++ b/sdk/resourcemanager/containerservicefleet/armcontainerservicefleet/fleetmembers_client_example_test.go @@ -83,9 +83,9 @@ func ExampleFleetMembersClient_BeginCreate_createsAFleetMemberResourceWithALongR ClusterResourceID: to.Ptr("/subscriptions/subid1/resourcegroups/rg1/providers/Microsoft.ContainerService/managedClusters/cluster-1"), Group: to.Ptr("fleet1"), }, - }, &armcontainerservicefleet.FleetMembersClientBeginCreateOptions{ - IfMatch: to.Ptr("amkttadbw"), - IfNoneMatch: to.Ptr("zoljoccbcg")}) + }, &FleetMembersClientBeginCreateOptions{ + ifMatch: to.Ptr("amkttadbw"), + ifNoneMatch: to.Ptr("zoljoccbcg")}) if err != nil { log.Fatalf("failed to finish the request: %v", err) } @@ -156,8 +156,8 @@ func ExampleFleetMembersClient_BeginDelete_deletesAFleetMemberResourceAsynchrono if err != nil { log.Fatalf("failed to create client: %v", err) } - poller, err := clientFactory.NewFleetMembersClient().BeginDelete(ctx, "rgfleets", "fleet1", "fleet1", &armcontainerservicefleet.FleetMembersClientBeginDeleteOptions{ - IfMatch: to.Ptr("klroqfozx")}) + poller, err := clientFactory.NewFleetMembersClient().BeginDelete(ctx, "rgfleets", "fleet1", "fleet1", &FleetMembersClientBeginDeleteOptions{ + ifMatch: to.Ptr("klroqfozx")}) if err != nil { log.Fatalf("failed to finish the request: %v", err) } @@ -438,8 +438,8 @@ func ExampleFleetMembersClient_BeginUpdateAsync_updatesAFleetMemberResourceSynch Properties: &armcontainerservicefleet.FleetMemberUpdateProperties{ Group: to.Ptr("staging"), }, - }, &armcontainerservicefleet.FleetMembersClientBeginUpdateAsyncOptions{ - IfMatch: to.Ptr("bjyjzzxvbs")}) + }, &FleetMembersClientBeginUpdateAsyncOptions{ + ifMatch: to.Ptr("bjyjzzxvbs")}) if err != nil { log.Fatalf("failed to finish the request: %v", err) } diff --git a/sdk/resourcemanager/containerservicefleet/armcontainerservicefleet/fleets_client_example_test.go b/sdk/resourcemanager/containerservicefleet/armcontainerservicefleet/fleets_client_example_test.go index 0ce40d9f3ecb..f25992a0a897 100644 --- a/sdk/resourcemanager/containerservicefleet/armcontainerservicefleet/fleets_client_example_test.go +++ b/sdk/resourcemanager/containerservicefleet/armcontainerservicefleet/fleets_client_example_test.go @@ -124,9 +124,9 @@ func ExampleFleetsClient_BeginCreate_createsAFleetResourceWithALongRunningOperat "key126": {}, }, }, - }, &armcontainerservicefleet.FleetsClientBeginCreateOptions{ - IfMatch: to.Ptr("jzlrwaylijhsnzp"), - IfNoneMatch: to.Ptr("cqpzdjshmggwolagomzxfy")}) + }, &FleetsClientBeginCreateOptions{ + ifMatch: to.Ptr("jzlrwaylijhsnzp"), + ifNoneMatch: to.Ptr("cqpzdjshmggwolagomzxfy")}) if err != nil { log.Fatalf("failed to finish the request: %v", err) } @@ -224,8 +224,8 @@ func ExampleFleetsClient_BeginDelete_deletesAFleetResourceAsynchronouslyWithALon if err != nil { log.Fatalf("failed to create client: %v", err) } - poller, err := clientFactory.NewFleetsClient().BeginDelete(ctx, "rgfleets", "fleet1", &armcontainerservicefleet.FleetsClientBeginDeleteOptions{ - IfMatch: to.Ptr("crsgokrdxddjsvqxpplerummnmzav")}) + poller, err := clientFactory.NewFleetsClient().BeginDelete(ctx, "rgfleets", "fleet1", &FleetsClientBeginDeleteOptions{ + ifMatch: to.Ptr("crsgokrdxddjsvqxpplerummnmzav")}) if err != nil { log.Fatalf("failed to finish the request: %v", err) } @@ -738,8 +738,8 @@ func ExampleFleetsClient_BeginUpdateAsync_updateAFleet() { "tier": to.Ptr("secure"), "env": to.Ptr("prod"), }, - }, &armcontainerservicefleet.FleetsClientBeginUpdateAsyncOptions{ - IfMatch: to.Ptr("dfjkwelr7384")}) + }, &FleetsClientBeginUpdateAsyncOptions{ + ifMatch: to.Ptr("dfjkwelr7384")}) if err != nil { log.Fatalf("failed to finish the request: %v", err) } @@ -811,8 +811,8 @@ func ExampleFleetsClient_BeginUpdateAsync_updateAFleetGeneratedByMaximumSetRule( "key126": {}, }, }, - }, &armcontainerservicefleet.FleetsClientBeginUpdateAsyncOptions{ - IfMatch: to.Ptr("lgoeir")}) + }, &FleetsClientBeginUpdateAsyncOptions{ + ifMatch: to.Ptr("lgoeir")}) if err != nil { log.Fatalf("failed to finish the request: %v", err) } diff --git a/sdk/resourcemanager/containerservicefleet/armcontainerservicefleet/fleetupdatestrategies_client_example_test.go b/sdk/resourcemanager/containerservicefleet/armcontainerservicefleet/fleetupdatestrategies_client_example_test.go index cbb34c1734c8..08d3428f2166 100644 --- a/sdk/resourcemanager/containerservicefleet/armcontainerservicefleet/fleetupdatestrategies_client_example_test.go +++ b/sdk/resourcemanager/containerservicefleet/armcontainerservicefleet/fleetupdatestrategies_client_example_test.go @@ -39,9 +39,9 @@ func ExampleFleetUpdateStrategiesClient_BeginCreateOrUpdate_createAFleetUpdateSt }, }, }, - }, &armcontainerservicefleet.FleetUpdateStrategiesClientBeginCreateOrUpdateOptions{ - IfMatch: to.Ptr("bttptpmhheves"), - IfNoneMatch: to.Ptr("tlx")}) + }, &FleetUpdateStrategiesClientBeginCreateOrUpdateOptions{ + ifMatch: to.Ptr("bttptpmhheves"), + ifNoneMatch: to.Ptr("tlx")}) if err != nil { log.Fatalf("failed to finish the request: %v", err) } @@ -169,8 +169,8 @@ func ExampleFleetUpdateStrategiesClient_BeginDelete_deleteAFleetUpdateStrategyRe if err != nil { log.Fatalf("failed to create client: %v", err) } - poller, err := clientFactory.NewFleetUpdateStrategiesClient().BeginDelete(ctx, "rgfleets", "fleet1", "fleet1", &armcontainerservicefleet.FleetUpdateStrategiesClientBeginDeleteOptions{ - IfMatch: to.Ptr("saqprswlk")}) + poller, err := clientFactory.NewFleetUpdateStrategiesClient().BeginDelete(ctx, "rgfleets", "fleet1", "fleet1", &FleetUpdateStrategiesClientBeginDeleteOptions{ + ifMatch: to.Ptr("saqprswlk")}) if err != nil { log.Fatalf("failed to finish the request: %v", err) } diff --git a/sdk/resourcemanager/containerservicefleet/armcontainerservicefleet/tsp-location.yaml b/sdk/resourcemanager/containerservicefleet/armcontainerservicefleet/tsp-location.yaml index dae484bc2983..192b7afe8668 100644 --- a/sdk/resourcemanager/containerservicefleet/armcontainerservicefleet/tsp-location.yaml +++ b/sdk/resourcemanager/containerservicefleet/armcontainerservicefleet/tsp-location.yaml @@ -1,4 +1,4 @@ directory: specification/containerservice/Fleet.Management -commit: 734445e0b59147a65865cd88b5674ddb5e62f9ba +commit: 1f578543d267d08febc1bebf4e33ffe14363ddfc repo: Azure/azure-rest-api-specs -additionalDirectories: \ No newline at end of file +additionalDirectories: diff --git a/sdk/resourcemanager/containerservicefleet/armcontainerservicefleet/updateruns_client_example_test.go b/sdk/resourcemanager/containerservicefleet/armcontainerservicefleet/updateruns_client_example_test.go index b584d729cb54..f69ce8e5dda6 100644 --- a/sdk/resourcemanager/containerservicefleet/armcontainerservicefleet/updateruns_client_example_test.go +++ b/sdk/resourcemanager/containerservicefleet/armcontainerservicefleet/updateruns_client_example_test.go @@ -188,9 +188,9 @@ func ExampleUpdateRunsClient_BeginCreateOrUpdate_createAnUpdateRunGeneratedByMax }, AutoUpgradeProfileID: to.Ptr("/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rgfleets/providers/Microsoft.ContainerService/fleets/fleet1/autoUpgradeProfiles/aup1"), }, - }, &armcontainerservicefleet.UpdateRunsClientBeginCreateOrUpdateOptions{ - IfMatch: to.Ptr("wyolpuaxgybeygcbz"), - IfNoneMatch: to.Ptr("rwrhonlormgshamadufoo")}) + }, &UpdateRunsClientBeginCreateOrUpdateOptions{ + ifMatch: to.Ptr("wyolpuaxgybeygcbz"), + ifNoneMatch: to.Ptr("rwrhonlormgshamadufoo")}) if err != nil { log.Fatalf("failed to finish the request: %v", err) } @@ -413,8 +413,8 @@ func ExampleUpdateRunsClient_BeginDelete_deleteAnUpdateRunResourceGeneratedByMax if err != nil { log.Fatalf("failed to create client: %v", err) } - poller, err := clientFactory.NewUpdateRunsClient().BeginDelete(ctx, "rgfleets", "fleet1", "fleet1", &armcontainerservicefleet.UpdateRunsClientBeginDeleteOptions{ - IfMatch: to.Ptr("xnbwucfeufeagpa")}) + poller, err := clientFactory.NewUpdateRunsClient().BeginDelete(ctx, "rgfleets", "fleet1", "fleet1", &UpdateRunsClientBeginDeleteOptions{ + ifMatch: to.Ptr("xnbwucfeufeagpa")}) if err != nil { log.Fatalf("failed to finish the request: %v", err) } @@ -1185,8 +1185,8 @@ func ExampleUpdateRunsClient_BeginSkip_skipsOneOrMoreMemberGroupStageAfterStageW Name: to.Ptr("stage1"), }, }, - }, &armcontainerservicefleet.UpdateRunsClientBeginSkipOptions{ - IfMatch: to.Ptr("rncfubdzrhcihvpqflbsjvoau")}) + }, &UpdateRunsClientBeginSkipOptions{ + ifMatch: to.Ptr("rncfubdzrhcihvpqflbsjvoau")}) if err != nil { log.Fatalf("failed to finish the request: %v", err) } @@ -1487,8 +1487,8 @@ func ExampleUpdateRunsClient_BeginStart_startsAnUpdateRunGeneratedByMaximumSetRu if err != nil { log.Fatalf("failed to create client: %v", err) } - poller, err := clientFactory.NewUpdateRunsClient().BeginStart(ctx, "rgfleets", "fleet1", "fleet1", &armcontainerservicefleet.UpdateRunsClientBeginStartOptions{ - IfMatch: to.Ptr("bvhjlqeindkmljbbiypbqiaqgtkhlu")}) + poller, err := clientFactory.NewUpdateRunsClient().BeginStart(ctx, "rgfleets", "fleet1", "fleet1", &UpdateRunsClientBeginStartOptions{ + ifMatch: to.Ptr("bvhjlqeindkmljbbiypbqiaqgtkhlu")}) if err != nil { log.Fatalf("failed to finish the request: %v", err) } @@ -1789,8 +1789,8 @@ func ExampleUpdateRunsClient_BeginStop_stopsAnUpdateRunGeneratedByMaximumSetRule if err != nil { log.Fatalf("failed to create client: %v", err) } - poller, err := clientFactory.NewUpdateRunsClient().BeginStop(ctx, "rgfleets", "fleet1", "fleet1", &armcontainerservicefleet.UpdateRunsClientBeginStopOptions{ - IfMatch: to.Ptr("jb")}) + poller, err := clientFactory.NewUpdateRunsClient().BeginStop(ctx, "rgfleets", "fleet1", "fleet1", &UpdateRunsClientBeginStopOptions{ + ifMatch: to.Ptr("jb")}) if err != nil { log.Fatalf("failed to finish the request: %v", err) } diff --git a/sdk/resourcemanager/contoso/armcontoso/CHANGELOG.md b/sdk/resourcemanager/contoso/armcontoso/CHANGELOG.md new file mode 100644 index 000000000000..a204406944fd --- /dev/null +++ b/sdk/resourcemanager/contoso/armcontoso/CHANGELOG.md @@ -0,0 +1,8 @@ +# Release History + +## 0.1.0 (2025-04-27) +### Other Changes + +The package of `github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/contoso/armcontoso` 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/contoso/armcontoso/LICENSE.txt b/sdk/resourcemanager/contoso/armcontoso/LICENSE.txt new file mode 100644 index 000000000000..dc0c2ffb3dc1 --- /dev/null +++ b/sdk/resourcemanager/contoso/armcontoso/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/contoso/armcontoso/README.md b/sdk/resourcemanager/contoso/armcontoso/README.md new file mode 100644 index 000000000000..de0732ba86be --- /dev/null +++ b/sdk/resourcemanager/contoso/armcontoso/README.md @@ -0,0 +1,90 @@ +# Azure Contoso Module for Go + +The `armcontoso` module provides operations for working with Azure Contoso. + +[Source code](https://github.com/Azure/azure-sdk-for-go/tree/main/sdk/resourcemanager/contoso/armcontoso) + +# 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 Contoso module: + +```sh +go get github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/contoso/armcontoso +``` + +## Authorization + +When creating a client, you will need to provide a credential for authenticating with Azure Contoso. 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 Contoso 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 := armcontoso.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 := armcontoso.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.NewEmployeesClient() +``` + +## 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 `Contoso` 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/contoso/armcontoso/ci.yml b/sdk/resourcemanager/contoso/armcontoso/ci.yml new file mode 100644 index 000000000000..5288ced2c71e --- /dev/null +++ b/sdk/resourcemanager/contoso/armcontoso/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/contoso/armcontoso/ + +pr: + branches: + include: + - main + - feature/* + - hotfix/* + - release/* + paths: + include: + - sdk/resourcemanager/contoso/armcontoso/ + +extends: + template: /eng/pipelines/templates/jobs/archetype-sdk-client.yml + parameters: + ServiceDirectory: 'resourcemanager/contoso/armcontoso' diff --git a/sdk/resourcemanager/contoso/armcontoso/client_factory.go b/sdk/resourcemanager/contoso/armcontoso/client_factory.go new file mode 100644 index 000000000000..0a0944ec82c6 --- /dev/null +++ b/sdk/resourcemanager/contoso/armcontoso/client_factory.go @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcontoso + +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 +} + +// NewEmployeesClient creates a new instance of EmployeesClient. +func (c *ClientFactory) NewEmployeesClient() *EmployeesClient { + return &EmployeesClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewOperationsClient creates a new instance of OperationsClient. +func (c *ClientFactory) NewOperationsClient() *OperationsClient { + return &OperationsClient{ + internal: c.internal, + } +} diff --git a/sdk/resourcemanager/contoso/armcontoso/constants.go b/sdk/resourcemanager/contoso/armcontoso/constants.go new file mode 100644 index 000000000000..35ca72f6b867 --- /dev/null +++ b/sdk/resourcemanager/contoso/armcontoso/constants.go @@ -0,0 +1,104 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcontoso + +const ( + moduleName = "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/contoso/armcontoso" + moduleVersion = "v0.1.0" +) + +// ActionType - Extensible enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. +type ActionType string + +const ( + // ActionTypeInternal - Actions are for internal-only APIs. + ActionTypeInternal ActionType = "Internal" +) + +// PossibleActionTypeValues returns the possible values for the ActionType const type. +func PossibleActionTypeValues() []ActionType { + return []ActionType{ + ActionTypeInternal, + } +} + +// CreatedByType - The kind of entity that created the resource. +type CreatedByType string + +const ( + // CreatedByTypeApplication - The entity was created by an application. + CreatedByTypeApplication CreatedByType = "Application" + // CreatedByTypeKey - The entity was created by a key. + CreatedByTypeKey CreatedByType = "Key" + // CreatedByTypeManagedIdentity - The entity was created by a managed identity. + CreatedByTypeManagedIdentity CreatedByType = "ManagedIdentity" + // CreatedByTypeUser - The entity was created by a user. + CreatedByTypeUser CreatedByType = "User" +) + +// PossibleCreatedByTypeValues returns the possible values for the CreatedByType const type. +func PossibleCreatedByTypeValues() []CreatedByType { + return []CreatedByType{ + CreatedByTypeApplication, + CreatedByTypeKey, + CreatedByTypeManagedIdentity, + CreatedByTypeUser, + } +} + +// 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 - Indicates the operation is initiated by a system. + OriginSystem Origin = "system" + // OriginUser - Indicates the operation is initiated by a user. + OriginUser Origin = "user" + // OriginUserSystem - Indicates the operation is initiated by a user or system. + OriginUserSystem Origin = "user,system" +) + +// PossibleOriginValues returns the possible values for the Origin const type. +func PossibleOriginValues() []Origin { + return []Origin{ + OriginSystem, + OriginUser, + OriginUserSystem, + } +} + +// ProvisioningState - The resource provisioning state. +type ProvisioningState string + +const ( + // ProvisioningStateAccepted - The resource create request has been accepted + ProvisioningStateAccepted ProvisioningState = "Accepted" + // ProvisioningStateCanceled - Resource creation was canceled. + ProvisioningStateCanceled ProvisioningState = "Canceled" + // ProvisioningStateDeleting - The resource is being deleted + ProvisioningStateDeleting ProvisioningState = "Deleting" + // ProvisioningStateFailed - Resource creation failed. + ProvisioningStateFailed ProvisioningState = "Failed" + // ProvisioningStateProvisioning - The resource is being provisioned + ProvisioningStateProvisioning ProvisioningState = "Provisioning" + // ProvisioningStateSucceeded - Resource has been created. + ProvisioningStateSucceeded ProvisioningState = "Succeeded" + // ProvisioningStateUpdating - The resource is updating + ProvisioningStateUpdating ProvisioningState = "Updating" +) + +// PossibleProvisioningStateValues returns the possible values for the ProvisioningState const type. +func PossibleProvisioningStateValues() []ProvisioningState { + return []ProvisioningState{ + ProvisioningStateAccepted, + ProvisioningStateCanceled, + ProvisioningStateDeleting, + ProvisioningStateFailed, + ProvisioningStateProvisioning, + ProvisioningStateSucceeded, + ProvisioningStateUpdating, + } +} diff --git a/sdk/resourcemanager/contoso/armcontoso/employees_client.go b/sdk/resourcemanager/contoso/armcontoso/employees_client.go new file mode 100644 index 000000000000..4ec0f62b9e70 --- /dev/null +++ b/sdk/resourcemanager/contoso/armcontoso/employees_client.go @@ -0,0 +1,444 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcontoso + +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" +) + +// EmployeesClient contains the methods for the Employees group. +// Don't use this type directly, use NewEmployeesClient() instead. +type EmployeesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewEmployeesClient creates a new instance of EmployeesClient 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 NewEmployeesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*EmployeesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &EmployeesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Create a Employee +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2021-11-01 +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - employeeName - The name of the Employee +// - resource - Resource create parameters. +// - options - EmployeesClientBeginCreateOrUpdateOptions contains the optional parameters for the EmployeesClient.BeginCreateOrUpdate +// method. +func (client *EmployeesClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, employeeName string, resource Employee, options *EmployeesClientBeginCreateOrUpdateOptions) (*runtime.Poller[EmployeesClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, employeeName, resource, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[EmployeesClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[EmployeesClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Create a Employee +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2021-11-01 +func (client *EmployeesClient) createOrUpdate(ctx context.Context, resourceGroupName string, employeeName string, resource Employee, options *EmployeesClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "EmployeesClient.BeginCreateOrUpdate" + 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, employeeName, 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 +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *EmployeesClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, employeeName string, resource Employee, _ *EmployeesClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Contoso/employees/{employeeName}" + 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 employeeName == "" { + return nil, errors.New("parameter employeeName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{employeeName}", url.PathEscape(employeeName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-11-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, resource); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Delete a Employee +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2021-11-01 +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - employeeName - The name of the Employee +// - options - EmployeesClientBeginDeleteOptions contains the optional parameters for the EmployeesClient.BeginDelete method. +func (client *EmployeesClient) BeginDelete(ctx context.Context, resourceGroupName string, employeeName string, options *EmployeesClientBeginDeleteOptions) (*runtime.Poller[EmployeesClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, employeeName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[EmployeesClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[EmployeesClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Delete a Employee +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2021-11-01 +func (client *EmployeesClient) deleteOperation(ctx context.Context, resourceGroupName string, employeeName string, options *EmployeesClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "EmployeesClient.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, employeeName, 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 *EmployeesClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, employeeName string, _ *EmployeesClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Contoso/employees/{employeeName}" + 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 employeeName == "" { + return nil, errors.New("parameter employeeName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{employeeName}", url.PathEscape(employeeName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-11-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Get a Employee +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2021-11-01 +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - employeeName - The name of the Employee +// - options - EmployeesClientGetOptions contains the optional parameters for the EmployeesClient.Get method. +func (client *EmployeesClient) Get(ctx context.Context, resourceGroupName string, employeeName string, options *EmployeesClientGetOptions) (EmployeesClientGetResponse, error) { + var err error + const operationName = "EmployeesClient.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, employeeName, options) + if err != nil { + return EmployeesClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return EmployeesClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return EmployeesClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *EmployeesClient) getCreateRequest(ctx context.Context, resourceGroupName string, employeeName string, _ *EmployeesClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Contoso/employees/{employeeName}" + 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 employeeName == "" { + return nil, errors.New("parameter employeeName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{employeeName}", url.PathEscape(employeeName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-11-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *EmployeesClient) getHandleResponse(resp *http.Response) (EmployeesClientGetResponse, error) { + result := EmployeesClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Employee); err != nil { + return EmployeesClientGetResponse{}, err + } + return result, nil +} + +// NewListByResourceGroupPager - List Employee resources by resource group +// +// Generated from API version 2021-11-01 +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - options - EmployeesClientListByResourceGroupOptions contains the optional parameters for the EmployeesClient.NewListByResourceGroupPager +// method. +func (client *EmployeesClient) NewListByResourceGroupPager(resourceGroupName string, options *EmployeesClientListByResourceGroupOptions) *runtime.Pager[EmployeesClientListByResourceGroupResponse] { + return runtime.NewPager(runtime.PagingHandler[EmployeesClientListByResourceGroupResponse]{ + More: func(page EmployeesClientListByResourceGroupResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *EmployeesClientListByResourceGroupResponse) (EmployeesClientListByResourceGroupResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "EmployeesClient.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 EmployeesClientListByResourceGroupResponse{}, err + } + return client.listByResourceGroupHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByResourceGroupCreateRequest creates the ListByResourceGroup request. +func (client *EmployeesClient) listByResourceGroupCreateRequest(ctx context.Context, resourceGroupName string, _ *EmployeesClientListByResourceGroupOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Contoso/employees" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-11-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByResourceGroupHandleResponse handles the ListByResourceGroup response. +func (client *EmployeesClient) listByResourceGroupHandleResponse(resp *http.Response) (EmployeesClientListByResourceGroupResponse, error) { + result := EmployeesClientListByResourceGroupResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.EmployeeListResult); err != nil { + return EmployeesClientListByResourceGroupResponse{}, err + } + return result, nil +} + +// NewListBySubscriptionPager - List Employee resources by subscription ID +// +// Generated from API version 2021-11-01 +// - options - EmployeesClientListBySubscriptionOptions contains the optional parameters for the EmployeesClient.NewListBySubscriptionPager +// method. +func (client *EmployeesClient) NewListBySubscriptionPager(options *EmployeesClientListBySubscriptionOptions) *runtime.Pager[EmployeesClientListBySubscriptionResponse] { + return runtime.NewPager(runtime.PagingHandler[EmployeesClientListBySubscriptionResponse]{ + More: func(page EmployeesClientListBySubscriptionResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *EmployeesClientListBySubscriptionResponse) (EmployeesClientListBySubscriptionResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "EmployeesClient.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 EmployeesClientListBySubscriptionResponse{}, err + } + return client.listBySubscriptionHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listBySubscriptionCreateRequest creates the ListBySubscription request. +func (client *EmployeesClient) listBySubscriptionCreateRequest(ctx context.Context, _ *EmployeesClientListBySubscriptionOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Contoso/employees" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-11-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listBySubscriptionHandleResponse handles the ListBySubscription response. +func (client *EmployeesClient) listBySubscriptionHandleResponse(resp *http.Response) (EmployeesClientListBySubscriptionResponse, error) { + result := EmployeesClientListBySubscriptionResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.EmployeeListResult); err != nil { + return EmployeesClientListBySubscriptionResponse{}, err + } + return result, nil +} + +// Update - Update a Employee +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2021-11-01 +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - employeeName - The name of the Employee +// - properties - The resource properties to be updated. +// - options - EmployeesClientUpdateOptions contains the optional parameters for the EmployeesClient.Update method. +func (client *EmployeesClient) Update(ctx context.Context, resourceGroupName string, employeeName string, properties Employee, options *EmployeesClientUpdateOptions) (EmployeesClientUpdateResponse, error) { + var err error + const operationName = "EmployeesClient.Update" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateCreateRequest(ctx, resourceGroupName, employeeName, properties, options) + if err != nil { + return EmployeesClientUpdateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return EmployeesClientUpdateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return EmployeesClientUpdateResponse{}, err + } + resp, err := client.updateHandleResponse(httpResp) + return resp, err +} + +// updateCreateRequest creates the Update request. +func (client *EmployeesClient) updateCreateRequest(ctx context.Context, resourceGroupName string, employeeName string, properties Employee, _ *EmployeesClientUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Contoso/employees/{employeeName}" + 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 employeeName == "" { + return nil, errors.New("parameter employeeName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{employeeName}", url.PathEscape(employeeName)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-11-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, properties); err != nil { + return nil, err + } + return req, nil +} + +// updateHandleResponse handles the Update response. +func (client *EmployeesClient) updateHandleResponse(resp *http.Response) (EmployeesClientUpdateResponse, error) { + result := EmployeesClientUpdateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Employee); err != nil { + return EmployeesClientUpdateResponse{}, err + } + return result, nil +} diff --git a/sdk/resourcemanager/contoso/armcontoso/employees_client_example_test.go b/sdk/resourcemanager/contoso/armcontoso/employees_client_example_test.go new file mode 100644 index 000000000000..44948db27382 --- /dev/null +++ b/sdk/resourcemanager/contoso/armcontoso/employees_client_example_test.go @@ -0,0 +1,302 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcontoso_test + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/Azure/azure-sdk-for-go/sdk/azidentity" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/contoso/armcontoso" + "log" +) + +// Generated from example definition: 2021-11-01/Employees_CreateOrUpdate.json +func ExampleEmployeesClient_BeginCreateOrUpdate() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armcontoso.NewClientFactory("11809CA1-E126-4017-945E-AA795CD5C5A9", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + poller, err := clientFactory.NewEmployeesClient().BeginCreateOrUpdate(ctx, "rgopenapi", "9KF-f-8b", armcontoso.Employee{ + Properties: &armcontoso.EmployeeProperties{ + Age: to.Ptr[int32](30), + City: to.Ptr("gydhnntudughbmxlkyzrskcdkotrxn"), + Profile: []byte("ms"), + }, + Tags: map[string]*string{ + "key2913": to.Ptr("urperxmkkhhkp"), + }, + Location: to.Ptr("itajgxyqozseoygnl"), + }, nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + res, err := poller.PollUntilDone(ctx, nil) + if err != nil { + log.Fatalf("failed to pull the result: %v", err) + } + // You could use response here. We use blank identifier for just demo purposes. + _ = res + // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // res = armcontoso.EmployeesClientCreateOrUpdateResponse{ + // Employee: &armcontoso.Employee{ + // Properties: &armcontoso.EmployeeProperties{ + // Age: to.Ptr[int32](30), + // City: to.Ptr("gydhnntudughbmxlkyzrskcdkotrxn"), + // Profile: []byte("ms"), + // ProvisioningState: to.Ptr(armcontoso.ProvisioningStateSucceeded), + // }, + // Tags: map[string]*string{ + // "key2913": to.Ptr("urperxmkkhhkp"), + // }, + // Location: to.Ptr("itajgxyqozseoygnl"), + // ID: to.Ptr("/subscriptions/11809CA1-E126-4017-945E-AA795CD5C5A9/resourceGroups/rgopenapi/providers/Microsoft.Contoso/employees/le-8MU--J3W6q8D386p3-iT3"), + // Name: to.Ptr("xepyxhpb"), + // Type: to.Ptr("svvamxrdnnv"), + // SystemData: &armcontoso.SystemData{ + // CreatedBy: to.Ptr("iewyxsnriqktsvp"), + // CreatedByType: to.Ptr(armcontoso.CreatedByTypeUser), + // CreatedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2023-05-19T00:28:48.610Z"); return t}()), + // LastModifiedBy: to.Ptr("xrchbnnuzierzpxw"), + // LastModifiedByType: to.Ptr(armcontoso.CreatedByTypeUser), + // LastModifiedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2023-05-19T00:28:48.610Z"); return t}()), + // }, + // }, + // } +} + +// Generated from example definition: 2021-11-01/Employees_Delete.json +func ExampleEmployeesClient_BeginDelete() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armcontoso.NewClientFactory("11809CA1-E126-4017-945E-AA795CD5C5A9", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + poller, err := clientFactory.NewEmployeesClient().BeginDelete(ctx, "rgopenapi", "5vX--BxSu3ux48rI4O9OQ569", nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + _, err = poller.PollUntilDone(ctx, nil) + if err != nil { + log.Fatalf("failed to pull the result: %v", err) + } +} + +// Generated from example definition: 2021-11-01/Employees_Get.json +func ExampleEmployeesClient_Get() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armcontoso.NewClientFactory("11809CA1-E126-4017-945E-AA795CD5C5A9", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + res, err := clientFactory.NewEmployeesClient().Get(ctx, "rgopenapi", "le-8MU--J3W6q8D386p3-iT3", nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + // You could use response here. We use blank identifier for just demo purposes. + _ = res + // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // res = armcontoso.EmployeesClientGetResponse{ + // Employee: &armcontoso.Employee{ + // Properties: &armcontoso.EmployeeProperties{ + // Age: to.Ptr[int32](30), + // City: to.Ptr("gydhnntudughbmxlkyzrskcdkotrxn"), + // Profile: []byte("ms"), + // ProvisioningState: to.Ptr(armcontoso.ProvisioningStateSucceeded), + // }, + // Tags: map[string]*string{ + // "key2913": to.Ptr("urperxmkkhhkp"), + // }, + // Location: to.Ptr("itajgxyqozseoygnl"), + // ID: to.Ptr("/subscriptions/11809CA1-E126-4017-945E-AA795CD5C5A9/resourceGroups/rgopenapi/providers/Microsoft.Contoso/employees/le-8MU--J3W6q8D386p3-iT3"), + // Name: to.Ptr("xepyxhpb"), + // Type: to.Ptr("svvamxrdnnv"), + // SystemData: &armcontoso.SystemData{ + // CreatedBy: to.Ptr("iewyxsnriqktsvp"), + // CreatedByType: to.Ptr(armcontoso.CreatedByTypeUser), + // CreatedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2023-05-19T00:28:48.610Z"); return t}()), + // LastModifiedBy: to.Ptr("xrchbnnuzierzpxw"), + // LastModifiedByType: to.Ptr(armcontoso.CreatedByTypeUser), + // LastModifiedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2023-05-19T00:28:48.610Z"); return t}()), + // }, + // }, + // } +} + +// Generated from example definition: 2021-11-01/Employees_ListByResourceGroup.json +func ExampleEmployeesClient_NewListByResourceGroupPager() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armcontoso.NewClientFactory("11809CA1-E126-4017-945E-AA795CD5C5A9", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + pager := clientFactory.NewEmployeesClient().NewListByResourceGroupPager("rgopenapi", nil) + for pager.More() { + page, err := pager.NextPage(ctx) + if err != nil { + log.Fatalf("failed to advance page: %v", err) + } + for _, v := range page.Value { + // You could use page here. We use blank identifier for just demo purposes. + _ = v + } + // If the HTTP response code is 200 as defined in example definition, your page structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // page = armcontoso.EmployeesClientListByResourceGroupResponse{ + // EmployeeListResult: armcontoso.EmployeeListResult{ + // Value: []*armcontoso.Employee{ + // { + // Properties: &armcontoso.EmployeeProperties{ + // Age: to.Ptr[int32](30), + // City: to.Ptr("gydhnntudughbmxlkyzrskcdkotrxn"), + // Profile: []byte("ms"), + // ProvisioningState: to.Ptr(armcontoso.ProvisioningStateSucceeded), + // }, + // Tags: map[string]*string{ + // "key2913": to.Ptr("urperxmkkhhkp"), + // }, + // Location: to.Ptr("itajgxyqozseoygnl"), + // ID: to.Ptr("/subscriptions/11809CA1-E126-4017-945E-AA795CD5C5A9/resourceGroups/rgopenapi/providers/Microsoft.Contoso/employees/test"), + // Name: to.Ptr("xepyxhpb"), + // Type: to.Ptr("svvamxrdnnv"), + // SystemData: &armcontoso.SystemData{ + // CreatedBy: to.Ptr("iewyxsnriqktsvp"), + // CreatedByType: to.Ptr(armcontoso.CreatedByTypeUser), + // CreatedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2023-05-19T00:28:48.610Z"); return t}()), + // LastModifiedBy: to.Ptr("xrchbnnuzierzpxw"), + // LastModifiedByType: to.Ptr(armcontoso.CreatedByTypeUser), + // LastModifiedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2023-05-19T00:28:48.610Z"); return t}()), + // }, + // }, + // }, + // NextLink: to.Ptr("https://microsoft.com/a"), + // }, + // } + } +} + +// Generated from example definition: 2021-11-01/Employees_ListBySubscription.json +func ExampleEmployeesClient_NewListBySubscriptionPager() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armcontoso.NewClientFactory("11809CA1-E126-4017-945E-AA795CD5C5A9", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + pager := clientFactory.NewEmployeesClient().NewListBySubscriptionPager(nil) + for pager.More() { + page, err := pager.NextPage(ctx) + if err != nil { + log.Fatalf("failed to advance page: %v", err) + } + for _, v := range page.Value { + // You could use page here. We use blank identifier for just demo purposes. + _ = v + } + // If the HTTP response code is 200 as defined in example definition, your page structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // page = armcontoso.EmployeesClientListBySubscriptionResponse{ + // EmployeeListResult: armcontoso.EmployeeListResult{ + // Value: []*armcontoso.Employee{ + // { + // Properties: &armcontoso.EmployeeProperties{ + // Age: to.Ptr[int32](30), + // City: to.Ptr("gydhnntudughbmxlkyzrskcdkotrxn"), + // Profile: []byte("ms"), + // ProvisioningState: to.Ptr(armcontoso.ProvisioningStateSucceeded), + // }, + // Tags: map[string]*string{ + // "key2913": to.Ptr("urperxmkkhhkp"), + // }, + // Location: to.Ptr("itajgxyqozseoygnl"), + // ID: to.Ptr("/subscriptions/11809CA1-E126-4017-945E-AA795CD5C5A9/resourceGroups/rgopenapi/providers/Microsoft.Contoso/employees/test"), + // Name: to.Ptr("xepyxhpb"), + // Type: to.Ptr("svvamxrdnnv"), + // SystemData: &armcontoso.SystemData{ + // CreatedBy: to.Ptr("iewyxsnriqktsvp"), + // CreatedByType: to.Ptr(armcontoso.CreatedByTypeUser), + // CreatedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2023-05-19T00:28:48.610Z"); return t}()), + // LastModifiedBy: to.Ptr("xrchbnnuzierzpxw"), + // LastModifiedByType: to.Ptr(armcontoso.CreatedByTypeUser), + // LastModifiedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2023-05-19T00:28:48.610Z"); return t}()), + // }, + // }, + // }, + // NextLink: to.Ptr("https://microsoft.com/a"), + // }, + // } + } +} + +// Generated from example definition: 2021-11-01/Employees_Update.json +func ExampleEmployeesClient_Update() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armcontoso.NewClientFactory("11809CA1-E126-4017-945E-AA795CD5C5A9", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + res, err := clientFactory.NewEmployeesClient().Update(ctx, "rgopenapi", "-XhyNJ--", armcontoso.Employee{ + Tags: map[string]*string{ + "key7952": to.Ptr("no"), + }, + Properties: &armcontoso.EmployeeProperties{ + Age: to.Ptr[int32](24), + City: to.Ptr("uyfg"), + Profile: []byte("oapgijcswfkruiuuzbwco"), + }, + }, nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + // You could use response here. We use blank identifier for just demo purposes. + _ = res + // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // res = armcontoso.EmployeesClientUpdateResponse{ + // Employee: &armcontoso.Employee{ + // Properties: &armcontoso.EmployeeProperties{ + // Age: to.Ptr[int32](30), + // City: to.Ptr("gydhnntudughbmxlkyzrskcdkotrxn"), + // Profile: []byte("ms"), + // ProvisioningState: to.Ptr(armcontoso.ProvisioningStateSucceeded), + // }, + // Tags: map[string]*string{ + // "key2913": to.Ptr("urperxmkkhhkp"), + // }, + // Location: to.Ptr("itajgxyqozseoygnl"), + // ID: to.Ptr("/subscriptions/11809CA1-E126-4017-945E-AA795CD5C5A9/resourceGroups/contoso/providers/Microsoft.Contoso/employees/test"), + // Name: to.Ptr("xepyxhpb"), + // Type: to.Ptr("svvamxrdnnv"), + // SystemData: &armcontoso.SystemData{ + // CreatedBy: to.Ptr("iewyxsnriqktsvp"), + // CreatedByType: to.Ptr(armcontoso.CreatedByTypeUser), + // CreatedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2023-05-19T00:28:48.610Z"); return t}()), + // LastModifiedBy: to.Ptr("xrchbnnuzierzpxw"), + // LastModifiedByType: to.Ptr(armcontoso.CreatedByTypeUser), + // LastModifiedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2023-05-19T00:28:48.610Z"); return t}()), + // }, + // }, + // } +} diff --git a/sdk/resourcemanager/contoso/armcontoso/fake/employees_server.go b/sdk/resourcemanager/contoso/armcontoso/fake/employees_server.go new file mode 100644 index 000000000000..cd478a5d611e --- /dev/null +++ b/sdk/resourcemanager/contoso/armcontoso/fake/employees_server.go @@ -0,0 +1,361 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/contoso/armcontoso" + "net/http" + "net/url" + "regexp" +) + +// EmployeesServer is a fake server for instances of the armcontoso.EmployeesClient type. +type EmployeesServer struct { + // BeginCreateOrUpdate is the fake for method EmployeesClient.BeginCreateOrUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + BeginCreateOrUpdate func(ctx context.Context, resourceGroupName string, employeeName string, resource armcontoso.Employee, options *armcontoso.EmployeesClientBeginCreateOrUpdateOptions) (resp azfake.PollerResponder[armcontoso.EmployeesClientCreateOrUpdateResponse], errResp azfake.ErrorResponder) + + // BeginDelete is the fake for method EmployeesClient.BeginDelete + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent + BeginDelete func(ctx context.Context, resourceGroupName string, employeeName string, options *armcontoso.EmployeesClientBeginDeleteOptions) (resp azfake.PollerResponder[armcontoso.EmployeesClientDeleteResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method EmployeesClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceGroupName string, employeeName string, options *armcontoso.EmployeesClientGetOptions) (resp azfake.Responder[armcontoso.EmployeesClientGetResponse], errResp azfake.ErrorResponder) + + // NewListByResourceGroupPager is the fake for method EmployeesClient.NewListByResourceGroupPager + // HTTP status codes to indicate success: http.StatusOK + NewListByResourceGroupPager func(resourceGroupName string, options *armcontoso.EmployeesClientListByResourceGroupOptions) (resp azfake.PagerResponder[armcontoso.EmployeesClientListByResourceGroupResponse]) + + // NewListBySubscriptionPager is the fake for method EmployeesClient.NewListBySubscriptionPager + // HTTP status codes to indicate success: http.StatusOK + NewListBySubscriptionPager func(options *armcontoso.EmployeesClientListBySubscriptionOptions) (resp azfake.PagerResponder[armcontoso.EmployeesClientListBySubscriptionResponse]) + + // Update is the fake for method EmployeesClient.Update + // HTTP status codes to indicate success: http.StatusOK + Update func(ctx context.Context, resourceGroupName string, employeeName string, properties armcontoso.Employee, options *armcontoso.EmployeesClientUpdateOptions) (resp azfake.Responder[armcontoso.EmployeesClientUpdateResponse], errResp azfake.ErrorResponder) +} + +// NewEmployeesServerTransport creates a new instance of EmployeesServerTransport with the provided implementation. +// The returned EmployeesServerTransport instance is connected to an instance of armcontoso.EmployeesClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewEmployeesServerTransport(srv *EmployeesServer) *EmployeesServerTransport { + return &EmployeesServerTransport{ + srv: srv, + beginCreateOrUpdate: newTracker[azfake.PollerResponder[armcontoso.EmployeesClientCreateOrUpdateResponse]](), + beginDelete: newTracker[azfake.PollerResponder[armcontoso.EmployeesClientDeleteResponse]](), + newListByResourceGroupPager: newTracker[azfake.PagerResponder[armcontoso.EmployeesClientListByResourceGroupResponse]](), + newListBySubscriptionPager: newTracker[azfake.PagerResponder[armcontoso.EmployeesClientListBySubscriptionResponse]](), + } +} + +// EmployeesServerTransport connects instances of armcontoso.EmployeesClient to instances of EmployeesServer. +// Don't use this type directly, use NewEmployeesServerTransport instead. +type EmployeesServerTransport struct { + srv *EmployeesServer + beginCreateOrUpdate *tracker[azfake.PollerResponder[armcontoso.EmployeesClientCreateOrUpdateResponse]] + beginDelete *tracker[azfake.PollerResponder[armcontoso.EmployeesClientDeleteResponse]] + newListByResourceGroupPager *tracker[azfake.PagerResponder[armcontoso.EmployeesClientListByResourceGroupResponse]] + newListBySubscriptionPager *tracker[azfake.PagerResponder[armcontoso.EmployeesClientListBySubscriptionResponse]] +} + +// Do implements the policy.Transporter interface for EmployeesServerTransport. +func (e *EmployeesServerTransport) 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 *EmployeesServerTransport) 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 employeesServerTransportInterceptor != nil { + res.resp, res.err, intercepted = employeesServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "EmployeesClient.BeginCreateOrUpdate": + res.resp, res.err = e.dispatchBeginCreateOrUpdate(req) + case "EmployeesClient.BeginDelete": + res.resp, res.err = e.dispatchBeginDelete(req) + case "EmployeesClient.Get": + res.resp, res.err = e.dispatchGet(req) + case "EmployeesClient.NewListByResourceGroupPager": + res.resp, res.err = e.dispatchNewListByResourceGroupPager(req) + case "EmployeesClient.NewListBySubscriptionPager": + res.resp, res.err = e.dispatchNewListBySubscriptionPager(req) + case "EmployeesClient.Update": + res.resp, res.err = e.dispatchUpdate(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 *EmployeesServerTransport) dispatchBeginCreateOrUpdate(req *http.Request) (*http.Response, error) { + if e.srv.BeginCreateOrUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginCreateOrUpdate not implemented")} + } + beginCreateOrUpdate := e.beginCreateOrUpdate.get(req) + if beginCreateOrUpdate == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Contoso/employees/(?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[armcontoso.Employee](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + employeeNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("employeeName")]) + if err != nil { + return nil, err + } + respr, errRespr := e.srv.BeginCreateOrUpdate(req.Context(), resourceGroupNameParam, employeeNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginCreateOrUpdate = &respr + e.beginCreateOrUpdate.add(req, beginCreateOrUpdate) + } + + resp, err := server.PollerResponderNext(beginCreateOrUpdate, req) + if err != nil { + return nil, err + } + + if !contains([]int{http.StatusOK, http.StatusCreated}, resp.StatusCode) { + e.beginCreateOrUpdate.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", resp.StatusCode)} + } + if !server.PollerResponderMore(beginCreateOrUpdate) { + e.beginCreateOrUpdate.remove(req) + } + + return resp, nil +} + +func (e *EmployeesServerTransport) dispatchBeginDelete(req *http.Request) (*http.Response, error) { + if e.srv.BeginDelete == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginDelete not implemented")} + } + beginDelete := e.beginDelete.get(req) + if beginDelete == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Contoso/employees/(?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 + } + employeeNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("employeeName")]) + if err != nil { + return nil, err + } + respr, errRespr := e.srv.BeginDelete(req.Context(), resourceGroupNameParam, employeeNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginDelete = &respr + e.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) { + e.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) { + e.beginDelete.remove(req) + } + + return resp, nil +} + +func (e *EmployeesServerTransport) 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\.Contoso/employees/(?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 + } + employeeNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("employeeName")]) + if err != nil { + return nil, err + } + respr, errRespr := e.srv.Get(req.Context(), resourceGroupNameParam, employeeNameParam, 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).Employee, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (e *EmployeesServerTransport) dispatchNewListByResourceGroupPager(req *http.Request) (*http.Response, error) { + if e.srv.NewListByResourceGroupPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListByResourceGroupPager not implemented")} + } + newListByResourceGroupPager := e.newListByResourceGroupPager.get(req) + if newListByResourceGroupPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Contoso/employees` + 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 := e.srv.NewListByResourceGroupPager(resourceGroupNameParam, nil) + newListByResourceGroupPager = &resp + e.newListByResourceGroupPager.add(req, newListByResourceGroupPager) + server.PagerResponderInjectNextLinks(newListByResourceGroupPager, req, func(page *armcontoso.EmployeesClientListByResourceGroupResponse, 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) { + e.newListByResourceGroupPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListByResourceGroupPager) { + e.newListByResourceGroupPager.remove(req) + } + return resp, nil +} + +func (e *EmployeesServerTransport) dispatchNewListBySubscriptionPager(req *http.Request) (*http.Response, error) { + if e.srv.NewListBySubscriptionPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListBySubscriptionPager not implemented")} + } + newListBySubscriptionPager := e.newListBySubscriptionPager.get(req) + if newListBySubscriptionPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Contoso/employees` + 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 := e.srv.NewListBySubscriptionPager(nil) + newListBySubscriptionPager = &resp + e.newListBySubscriptionPager.add(req, newListBySubscriptionPager) + server.PagerResponderInjectNextLinks(newListBySubscriptionPager, req, func(page *armcontoso.EmployeesClientListBySubscriptionResponse, 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) { + e.newListBySubscriptionPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListBySubscriptionPager) { + e.newListBySubscriptionPager.remove(req) + } + return resp, nil +} + +func (e *EmployeesServerTransport) dispatchUpdate(req *http.Request) (*http.Response, error) { + if e.srv.Update == nil { + return nil, &nonRetriableError{errors.New("fake for method Update not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Contoso/employees/(?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[armcontoso.Employee](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + employeeNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("employeeName")]) + if err != nil { + return nil, err + } + respr, errRespr := e.srv.Update(req.Context(), resourceGroupNameParam, employeeNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Employee, req) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to EmployeesServerTransport +var employeesServerTransportInterceptor 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/contoso/armcontoso/fake/internal.go b/sdk/resourcemanager/contoso/armcontoso/fake/internal.go new file mode 100644 index 000000000000..7425b6a669e2 --- /dev/null +++ b/sdk/resourcemanager/contoso/armcontoso/fake/internal.go @@ -0,0 +1,65 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "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 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/contoso/armcontoso/fake/operations_server.go b/sdk/resourcemanager/contoso/armcontoso/fake/operations_server.go new file mode 100644 index 000000000000..c33444bdc46a --- /dev/null +++ b/sdk/resourcemanager/contoso/armcontoso/fake/operations_server.go @@ -0,0 +1,117 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/contoso/armcontoso" + "net/http" +) + +// OperationsServer is a fake server for instances of the armcontoso.OperationsClient type. +type OperationsServer struct { + // NewListPager is the fake for method OperationsClient.NewListPager + // HTTP status codes to indicate success: http.StatusOK + NewListPager func(options *armcontoso.OperationsClientListOptions) (resp azfake.PagerResponder[armcontoso.OperationsClientListResponse]) +} + +// NewOperationsServerTransport creates a new instance of OperationsServerTransport with the provided implementation. +// The returned OperationsServerTransport instance is connected to an instance of armcontoso.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[armcontoso.OperationsClientListResponse]](), + } +} + +// OperationsServerTransport connects instances of armcontoso.OperationsClient to instances of OperationsServer. +// Don't use this type directly, use NewOperationsServerTransport instead. +type OperationsServerTransport struct { + srv *OperationsServer + newListPager *tracker[azfake.PagerResponder[armcontoso.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 *armcontoso.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/contoso/armcontoso/fake/server_factory.go b/sdk/resourcemanager/contoso/armcontoso/fake/server_factory.go new file mode 100644 index 000000000000..9ddfd8463c5a --- /dev/null +++ b/sdk/resourcemanager/contoso/armcontoso/fake/server_factory.go @@ -0,0 +1,79 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "errors" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" + "sync" +) + +// ServerFactory is a fake server for instances of the armcontoso.ClientFactory type. +type ServerFactory struct { + // EmployeesServer contains the fakes for client EmployeesClient + EmployeesServer EmployeesServer + + // OperationsServer contains the fakes for client OperationsClient + OperationsServer OperationsServer +} + +// NewServerFactoryTransport creates a new instance of ServerFactoryTransport with the provided implementation. +// The returned ServerFactoryTransport instance is connected to an instance of armcontoso.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 armcontoso.ClientFactory to instances of ServerFactory. +// Don't use this type directly, use NewServerFactoryTransport instead. +type ServerFactoryTransport struct { + srv *ServerFactory + trMu sync.Mutex + trEmployeesServer *EmployeesServerTransport + trOperationsServer *OperationsServerTransport +} + +// 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 "EmployeesClient": + initServer(s, &s.trEmployeesServer, func() *EmployeesServerTransport { return NewEmployeesServerTransport(&s.srv.EmployeesServer) }) + resp, err = s.trEmployeesServer.Do(req) + case "OperationsClient": + initServer(s, &s.trOperationsServer, func() *OperationsServerTransport { return NewOperationsServerTransport(&s.srv.OperationsServer) }) + resp, err = s.trOperationsServer.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/contoso/armcontoso/fake/time_rfc3339.go b/sdk/resourcemanager/contoso/armcontoso/fake/time_rfc3339.go new file mode 100644 index 000000000000..87ee11e83b32 --- /dev/null +++ b/sdk/resourcemanager/contoso/armcontoso/fake/time_rfc3339.go @@ -0,0 +1,109 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "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 +} diff --git a/sdk/resourcemanager/contoso/armcontoso/go.mod b/sdk/resourcemanager/contoso/armcontoso/go.mod new file mode 100644 index 000000000000..6a6717468b34 --- /dev/null +++ b/sdk/resourcemanager/contoso/armcontoso/go.mod @@ -0,0 +1,23 @@ +module github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/contoso/armcontoso + +go 1.23.0 + +toolchain go1.23.8 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.17.1 + github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.7.0 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.10.0 // indirect + github.com/AzureAD/microsoft-authentication-library-for-go v1.2.2 // indirect + github.com/golang-jwt/jwt/v5 v5.2.1 // indirect + github.com/google/uuid v1.6.0 // indirect + github.com/kylelemons/godebug v1.1.0 // indirect + github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c // indirect + golang.org/x/crypto v0.36.0 // indirect + golang.org/x/net v0.37.0 // indirect + golang.org/x/sys v0.31.0 // indirect + golang.org/x/text v0.23.0 // indirect +) diff --git a/sdk/resourcemanager/contoso/armcontoso/go.sum b/sdk/resourcemanager/contoso/armcontoso/go.sum new file mode 100644 index 000000000000..1f92486fbbcf --- /dev/null +++ b/sdk/resourcemanager/contoso/armcontoso/go.sum @@ -0,0 +1,33 @@ +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/azidentity v1.7.0 h1:tfLQ34V6F7tVSwoTf/4lH5sE0o6eCJuNDTmH09nDpbc= +github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.7.0/go.mod h1:9kIvujWAA58nmPmWB1m23fyWic1kYZMxD9CxaWn4Qpg= +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/AzureAD/microsoft-authentication-library-for-go v1.2.2 h1:XHOnouVk1mxXfQidrMEnLlPk9UMeRtyBTnEFtxkV0kU= +github.com/AzureAD/microsoft-authentication-library-for-go v1.2.2/go.mod h1:wP83P5OoQ5p6ip3ScPr0BAq0BvuPAvacpEuSzyouqAI= +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/golang-jwt/jwt/v5 v5.2.1 h1:OuVbFODueb089Lh128TAcimifWaLhJwVflnrgM17wHk= +github.com/golang-jwt/jwt/v5 v5.2.1/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk= +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc= +github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= +github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c h1:+mdjkGKdHQG3305AYmdv1U2eRNDiU2ErMBj1gwrq8eQ= +github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c/go.mod h1:7rwL4CYBLnjLxUqIJNnCWiEdr3bn6IUYi15bNlnbCCU= +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/crypto v0.36.0 h1:AnAEvhDddvBdpY+uR+MyHmuZzzNqXSe/GvuDeob5L34= +golang.org/x/crypto v0.36.0/go.mod h1:Y4J0ReaxCR1IMaabaSMugxJES1EpwhBHhv2bDHklZvc= +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/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.31.0 h1:ioabZlmFYtWhL+TRYpcnNlLwhyxaM9kWTDEmfnprqik= +golang.org/x/sys v0.31.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= +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/contoso/armcontoso/models.go b/sdk/resourcemanager/contoso/armcontoso/models.go new file mode 100644 index 000000000000..5fe8eeb422cb --- /dev/null +++ b/sdk/resourcemanager/contoso/armcontoso/models.go @@ -0,0 +1,125 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcontoso + +import "time" + +// Employee resource +type Employee struct { + // REQUIRED; The geo-location where the resource lives + Location *string + + // The resource-specific properties for this resource. + Properties *EmployeeProperties + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; The name of the Employee + Name *string + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *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 +} + +// EmployeeListResult - The response of a Employee list operation. +type EmployeeListResult struct { + // REQUIRED; The Employee items on this page + Value []*Employee + + // The link to the next page of items + NextLink *string +} + +// EmployeeProperties - Employee properties +type EmployeeProperties struct { + // Age of employee + Age *int32 + + // City of employee + City *string + + // Profile of employee + Profile []byte + + // READ-ONLY; The status of the last operation. + ProvisioningState *ProvisioningState +} + +// 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; Extensible 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 Azure + // Resource Manager/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 and 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 { + // REQUIRED; The Operation items on this page + Value []*Operation + + // The link to the next page of items + NextLink *string +} + +// 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 +} diff --git a/sdk/resourcemanager/contoso/armcontoso/models_serde.go b/sdk/resourcemanager/contoso/armcontoso/models_serde.go new file mode 100644 index 000000000000..b3254af63ba4 --- /dev/null +++ b/sdk/resourcemanager/contoso/armcontoso/models_serde.go @@ -0,0 +1,328 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcontoso + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "reflect" +) + +// MarshalJSON implements the json.Marshaller interface for type Employee. +func (e Employee) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", e.ID) + populate(objectMap, "location", e.Location) + populate(objectMap, "name", e.Name) + populate(objectMap, "properties", e.Properties) + populate(objectMap, "systemData", e.SystemData) + populate(objectMap, "tags", e.Tags) + populate(objectMap, "type", e.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Employee. +func (e *Employee) 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 "location": + err = unpopulate(val, "Location", &e.Location) + 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 "tags": + err = unpopulate(val, "Tags", &e.Tags) + 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 EmployeeListResult. +func (e EmployeeListResult) 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 EmployeeListResult. +func (e *EmployeeListResult) 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 EmployeeProperties. +func (e EmployeeProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "age", e.Age) + populate(objectMap, "city", e.City) + populateByteArray(objectMap, "profile", e.Profile, func() any { + return runtime.EncodeByteArray(e.Profile, runtime.Base64URLFormat) + }) + populate(objectMap, "provisioningState", e.ProvisioningState) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type EmployeeProperties. +func (e *EmployeeProperties) 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 "age": + err = unpopulate(val, "Age", &e.Age) + delete(rawMsg, key) + case "city": + err = unpopulate(val, "City", &e.City) + delete(rawMsg, key) + case "profile": + if val != nil && string(val) != "null" { + err = runtime.DecodeByteArray(string(val), &e.Profile, runtime.Base64URLFormat) + } + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &e.ProvisioningState) + 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 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 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 +} + +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 populateByteArray[T any](m map[string]any, k string, b []T, convert func() any) { + if azcore.IsNullValue(b) { + m[k] = nil + } else if len(b) == 0 { + return + } else { + m[k] = convert() + } +} + +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/contoso/armcontoso/operations_client.go b/sdk/resourcemanager/contoso/armcontoso/operations_client.go new file mode 100644 index 000000000000..cc57f6103c1d --- /dev/null +++ b/sdk/resourcemanager/contoso/armcontoso/operations_client.go @@ -0,0 +1,84 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcontoso + +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 2021-11-01 +// - options - OperationsClientListOptions contains the optional parameters for the OperationsClient.NewListPager method. +func (client *OperationsClient) NewListPager(options *OperationsClientListOptions) *runtime.Pager[OperationsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[OperationsClientListResponse]{ + 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.Contoso/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", "2021-11-01") + 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/contoso/armcontoso/operations_client_example_test.go b/sdk/resourcemanager/contoso/armcontoso/operations_client_example_test.go new file mode 100644 index 000000000000..84d61e5c7bd6 --- /dev/null +++ b/sdk/resourcemanager/contoso/armcontoso/operations_client_example_test.go @@ -0,0 +1,56 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcontoso_test + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azidentity" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/contoso/armcontoso" + "log" +) + +// Generated from example definition: 2021-11-01/Operations_List.json +func ExampleOperationsClient_NewListPager() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armcontoso.NewClientFactory("", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + pager := clientFactory.NewOperationsClient().NewListPager(nil) + for pager.More() { + page, err := pager.NextPage(ctx) + if err != nil { + log.Fatalf("failed to advance page: %v", err) + } + for _, v := range page.Value { + // You could use page here. We use blank identifier for just demo purposes. + _ = v + } + // If the HTTP response code is 200 as defined in example definition, your page structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // page = armcontoso.OperationsClientListResponse{ + // OperationListResult: armcontoso.OperationListResult{ + // Value: []*armcontoso.Operation{ + // { + // Name: to.Ptr("ymeow"), + // IsDataAction: to.Ptr(true), + // Display: &armcontoso.OperationDisplay{ + // Provider: to.Ptr("qxyznq"), + // Resource: to.Ptr("bqfwkox"), + // Operation: to.Ptr("td"), + // Description: to.Ptr("yvgkhsuwartgxb"), + // }, + // Origin: to.Ptr(armcontoso.OriginUser), + // ActionType: to.Ptr(armcontoso.ActionTypeInternal), + // }, + // }, + // NextLink: to.Ptr("https://sample.com/nextLink"), + // }, + // } + } +} diff --git a/sdk/resourcemanager/contoso/armcontoso/options.go b/sdk/resourcemanager/contoso/armcontoso/options.go new file mode 100644 index 000000000000..11fee1c76771 --- /dev/null +++ b/sdk/resourcemanager/contoso/armcontoso/options.go @@ -0,0 +1,45 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcontoso + +// EmployeesClientBeginCreateOrUpdateOptions contains the optional parameters for the EmployeesClient.BeginCreateOrUpdate +// method. +type EmployeesClientBeginCreateOrUpdateOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// EmployeesClientBeginDeleteOptions contains the optional parameters for the EmployeesClient.BeginDelete method. +type EmployeesClientBeginDeleteOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// EmployeesClientGetOptions contains the optional parameters for the EmployeesClient.Get method. +type EmployeesClientGetOptions struct { + // placeholder for future optional parameters +} + +// EmployeesClientListByResourceGroupOptions contains the optional parameters for the EmployeesClient.NewListByResourceGroupPager +// method. +type EmployeesClientListByResourceGroupOptions struct { + // placeholder for future optional parameters +} + +// EmployeesClientListBySubscriptionOptions contains the optional parameters for the EmployeesClient.NewListBySubscriptionPager +// method. +type EmployeesClientListBySubscriptionOptions struct { + // placeholder for future optional parameters +} + +// EmployeesClientUpdateOptions contains the optional parameters for the EmployeesClient.Update method. +type EmployeesClientUpdateOptions struct { + // placeholder for future optional parameters +} + +// OperationsClientListOptions contains the optional parameters for the OperationsClient.NewListPager method. +type OperationsClientListOptions struct { + // placeholder for future optional parameters +} diff --git a/sdk/resourcemanager/contoso/armcontoso/responses.go b/sdk/resourcemanager/contoso/armcontoso/responses.go new file mode 100644 index 000000000000..9b28221cf0cb --- /dev/null +++ b/sdk/resourcemanager/contoso/armcontoso/responses.go @@ -0,0 +1,46 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcontoso + +// EmployeesClientCreateOrUpdateResponse contains the response from method EmployeesClient.BeginCreateOrUpdate. +type EmployeesClientCreateOrUpdateResponse struct { + // Employee resource + Employee +} + +// EmployeesClientDeleteResponse contains the response from method EmployeesClient.BeginDelete. +type EmployeesClientDeleteResponse struct { + // placeholder for future response values +} + +// EmployeesClientGetResponse contains the response from method EmployeesClient.Get. +type EmployeesClientGetResponse struct { + // Employee resource + Employee +} + +// EmployeesClientListByResourceGroupResponse contains the response from method EmployeesClient.NewListByResourceGroupPager. +type EmployeesClientListByResourceGroupResponse struct { + // The response of a Employee list operation. + EmployeeListResult +} + +// EmployeesClientListBySubscriptionResponse contains the response from method EmployeesClient.NewListBySubscriptionPager. +type EmployeesClientListBySubscriptionResponse struct { + // The response of a Employee list operation. + EmployeeListResult +} + +// EmployeesClientUpdateResponse contains the response from method EmployeesClient.Update. +type EmployeesClientUpdateResponse struct { + // Employee resource + Employee +} + +// 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 +} diff --git a/sdk/resourcemanager/contoso/armcontoso/time_rfc3339.go b/sdk/resourcemanager/contoso/armcontoso/time_rfc3339.go new file mode 100644 index 000000000000..fd129d84c771 --- /dev/null +++ b/sdk/resourcemanager/contoso/armcontoso/time_rfc3339.go @@ -0,0 +1,109 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcontoso + +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 +} diff --git a/sdk/resourcemanager/contoso/armcontoso/tsp-location.yaml b/sdk/resourcemanager/contoso/armcontoso/tsp-location.yaml new file mode 100644 index 000000000000..ac3fd3b600dc --- /dev/null +++ b/sdk/resourcemanager/contoso/armcontoso/tsp-location.yaml @@ -0,0 +1,4 @@ +directory: specification/contosowidgetmanager/Contoso.Management +commit: 1f578543d267d08febc1bebf4e33ffe14363ddfc +repo: Azure/azure-rest-api-specs +additionalDirectories: diff --git a/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager/CHANGELOG.md b/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager/CHANGELOG.md new file mode 100644 index 000000000000..4830689416a7 --- /dev/null +++ b/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager/CHANGELOG.md @@ -0,0 +1,8 @@ +# Release History + +## 0.1.0 (2025-04-27) +### Other Changes + +The package of `github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager` 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/databasefleetmanager/armdatabasefleetmanager/LICENSE.txt b/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager/LICENSE.txt new file mode 100644 index 000000000000..dc0c2ffb3dc1 --- /dev/null +++ b/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager/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/databasefleetmanager/armdatabasefleetmanager/README.md b/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager/README.md new file mode 100644 index 000000000000..5284a75848db --- /dev/null +++ b/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager/README.md @@ -0,0 +1,90 @@ +# Azure Databasefleetmanager Module for Go + +The `armdatabasefleetmanager` module provides operations for working with Azure Databasefleetmanager. + +[Source code](https://github.com/Azure/azure-sdk-for-go/tree/main/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager) + +# 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 Databasefleetmanager module: + +```sh +go get github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager +``` + +## Authorization + +When creating a client, you will need to provide a credential for authenticating with Azure Databasefleetmanager. 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 Databasefleetmanager 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 := armdatabasefleetmanager.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 := armdatabasefleetmanager.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.NewFirewallRulesClient() +``` + +## 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 `Databasefleetmanager` 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/databasefleetmanager/armdatabasefleetmanager/ci.yml b/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager/ci.yml new file mode 100644 index 000000000000..cfeeed61f070 --- /dev/null +++ b/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager/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/databasefleetmanager/armdatabasefleetmanager/ + +pr: + branches: + include: + - main + - feature/* + - hotfix/* + - release/* + paths: + include: + - sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager/ + +extends: + template: /eng/pipelines/templates/jobs/archetype-sdk-client.yml + parameters: + ServiceDirectory: 'resourcemanager/databasefleetmanager/armdatabasefleetmanager' diff --git a/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager/client_factory.go b/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager/client_factory.go new file mode 100644 index 000000000000..2afecb91e05c --- /dev/null +++ b/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager/client_factory.go @@ -0,0 +1,80 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armdatabasefleetmanager + +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 +} + +// NewFirewallRulesClient creates a new instance of FirewallRulesClient. +func (c *ClientFactory) NewFirewallRulesClient() *FirewallRulesClient { + return &FirewallRulesClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewFleetDatabasesClient creates a new instance of FleetDatabasesClient. +func (c *ClientFactory) NewFleetDatabasesClient() *FleetDatabasesClient { + return &FleetDatabasesClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewFleetTiersClient creates a new instance of FleetTiersClient. +func (c *ClientFactory) NewFleetTiersClient() *FleetTiersClient { + return &FleetTiersClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewFleetsClient creates a new instance of FleetsClient. +func (c *ClientFactory) NewFleetsClient() *FleetsClient { + return &FleetsClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewFleetspacesClient creates a new instance of FleetspacesClient. +func (c *ClientFactory) NewFleetspacesClient() *FleetspacesClient { + return &FleetspacesClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewOperationsClient creates a new instance of OperationsClient. +func (c *ClientFactory) NewOperationsClient() *OperationsClient { + return &OperationsClient{ + internal: c.internal, + } +} diff --git a/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager/constants.go b/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager/constants.go new file mode 100644 index 000000000000..6447efae7876 --- /dev/null +++ b/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager/constants.go @@ -0,0 +1,194 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armdatabasefleetmanager + +const ( + moduleName = "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager" + moduleVersion = "v0.1.0" +) + +// ActionType - Extensible enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. +type ActionType string + +const ( + // ActionTypeInternal - Actions are for internal-only APIs. + ActionTypeInternal ActionType = "Internal" +) + +// PossibleActionTypeValues returns the possible values for the ActionType const type. +func PossibleActionTypeValues() []ActionType { + return []ActionType{ + ActionTypeInternal, + } +} + +// AzureProvisioningState - The provisioning state of the resource. +type AzureProvisioningState string + +const ( + // AzureProvisioningStateAccepted - Request on the resource has been accepted. + AzureProvisioningStateAccepted AzureProvisioningState = "Accepted" + // AzureProvisioningStateCanceled - Resource creation was canceled. + AzureProvisioningStateCanceled AzureProvisioningState = "Canceled" + // AzureProvisioningStateFailed - Resource creation failed. + AzureProvisioningStateFailed AzureProvisioningState = "Failed" + // AzureProvisioningStateProvisioning - Resource is provisioning. + AzureProvisioningStateProvisioning AzureProvisioningState = "Provisioning" + // AzureProvisioningStateSucceeded - Resource has been created. + AzureProvisioningStateSucceeded AzureProvisioningState = "Succeeded" +) + +// PossibleAzureProvisioningStateValues returns the possible values for the AzureProvisioningState const type. +func PossibleAzureProvisioningStateValues() []AzureProvisioningState { + return []AzureProvisioningState{ + AzureProvisioningStateAccepted, + AzureProvisioningStateCanceled, + AzureProvisioningStateFailed, + AzureProvisioningStateProvisioning, + AzureProvisioningStateSucceeded, + } +} + +// CreatedByType - The kind of entity that created the resource. +type CreatedByType string + +const ( + // CreatedByTypeApplication - The entity was created by an application. + CreatedByTypeApplication CreatedByType = "Application" + // CreatedByTypeKey - The entity was created by a key. + CreatedByTypeKey CreatedByType = "Key" + // CreatedByTypeManagedIdentity - The entity was created by a managed identity. + CreatedByTypeManagedIdentity CreatedByType = "ManagedIdentity" + // CreatedByTypeUser - The entity was created by a user. + CreatedByTypeUser CreatedByType = "User" +) + +// PossibleCreatedByTypeValues returns the possible values for the CreatedByType const type. +func PossibleCreatedByTypeValues() []CreatedByType { + return []CreatedByType{ + CreatedByTypeApplication, + CreatedByTypeKey, + CreatedByTypeManagedIdentity, + CreatedByTypeUser, + } +} + +// DatabaseCreateMode - Create mode. Available options: Default - Create a database. Copy - Copy the source database (source +// database name must be specified) PointInTimeRestore - Create a database by restoring source database from a point in time +// (source database name and restore from time must be specified) +type DatabaseCreateMode string + +const ( + // DatabaseCreateModeCopy - Copy the source database (source database name must be specified). + DatabaseCreateModeCopy DatabaseCreateMode = "Copy" + // DatabaseCreateModeDefault - Create a database. + DatabaseCreateModeDefault DatabaseCreateMode = "Default" + // DatabaseCreateModePointInTimeRestore - Create a database by restoring source database from a point in time (source database + // name and restore from time must be specified). + DatabaseCreateModePointInTimeRestore DatabaseCreateMode = "PointInTimeRestore" +) + +// PossibleDatabaseCreateModeValues returns the possible values for the DatabaseCreateMode const type. +func PossibleDatabaseCreateModeValues() []DatabaseCreateMode { + return []DatabaseCreateMode{ + DatabaseCreateModeCopy, + DatabaseCreateModeDefault, + DatabaseCreateModePointInTimeRestore, + } +} + +// IdentityType - Identity type of the main principal. +type IdentityType string + +const ( + // IdentityTypeNone - No identity. + IdentityTypeNone IdentityType = "None" + // IdentityTypeUserAssigned - User assigned identity. + IdentityTypeUserAssigned IdentityType = "UserAssigned" +) + +// PossibleIdentityTypeValues returns the possible values for the IdentityType const type. +func PossibleIdentityTypeValues() []IdentityType { + return []IdentityType{ + IdentityTypeNone, + IdentityTypeUserAssigned, + } +} + +// 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 - Indicates the operation is initiated by a system. + OriginSystem Origin = "system" + // OriginUser - Indicates the operation is initiated by a user. + OriginUser Origin = "user" + // OriginUserSystem - Indicates the operation is initiated by a user or system. + OriginUserSystem Origin = "user,system" +) + +// PossibleOriginValues returns the possible values for the Origin const type. +func PossibleOriginValues() []Origin { + return []Origin{ + OriginSystem, + OriginUser, + OriginUserSystem, + } +} + +// PrincipalType - Principal type of the authorized principal. +type PrincipalType string + +const ( + // PrincipalTypeApplication - Application principal type. + PrincipalTypeApplication PrincipalType = "Application" + // PrincipalTypeUser - User principal type. + PrincipalTypeUser PrincipalType = "User" +) + +// PossiblePrincipalTypeValues returns the possible values for the PrincipalType const type. +func PossiblePrincipalTypeValues() []PrincipalType { + return []PrincipalType{ + PrincipalTypeApplication, + PrincipalTypeUser, + } +} + +// ResourceType - Resource type of the destination tier override. +type ResourceType string + +const ( + // ResourceTypeDatabase - Database resource type. + ResourceTypeDatabase ResourceType = "Database" + // ResourceTypePool - Elastic pool resource type. + ResourceTypePool ResourceType = "Pool" +) + +// PossibleResourceTypeValues returns the possible values for the ResourceType const type. +func PossibleResourceTypeValues() []ResourceType { + return []ResourceType{ + ResourceTypeDatabase, + ResourceTypePool, + } +} + +// ZoneRedundancy - Status of zone redundancy in a tier. +type ZoneRedundancy string + +const ( + // ZoneRedundancyDisabled - Zone redundancy disabled. + ZoneRedundancyDisabled ZoneRedundancy = "Disabled" + // ZoneRedundancyEnabled - Zone redundancy enabled. + ZoneRedundancyEnabled ZoneRedundancy = "Enabled" +) + +// PossibleZoneRedundancyValues returns the possible values for the ZoneRedundancy const type. +func PossibleZoneRedundancyValues() []ZoneRedundancy { + return []ZoneRedundancy{ + ZoneRedundancyDisabled, + ZoneRedundancyEnabled, + } +} diff --git a/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager/fake/firewallrules_server.go b/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager/fake/firewallrules_server.go new file mode 100644 index 000000000000..8647c11c820a --- /dev/null +++ b/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager/fake/firewallrules_server.go @@ -0,0 +1,352 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager" + "net/http" + "net/url" + "regexp" + "strconv" +) + +// FirewallRulesServer is a fake server for instances of the armdatabasefleetmanager.FirewallRulesClient type. +type FirewallRulesServer struct { + // BeginCreateOrUpdate is the fake for method FirewallRulesClient.BeginCreateOrUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + BeginCreateOrUpdate func(ctx context.Context, resourceGroupName string, fleetName string, fleetspaceName string, firewallRuleName string, resource armdatabasefleetmanager.FirewallRule, options *armdatabasefleetmanager.FirewallRulesClientBeginCreateOrUpdateOptions) (resp azfake.PollerResponder[armdatabasefleetmanager.FirewallRulesClientCreateOrUpdateResponse], errResp azfake.ErrorResponder) + + // BeginDelete is the fake for method FirewallRulesClient.BeginDelete + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent + BeginDelete func(ctx context.Context, resourceGroupName string, fleetName string, fleetspaceName string, firewallRuleName string, options *armdatabasefleetmanager.FirewallRulesClientBeginDeleteOptions) (resp azfake.PollerResponder[armdatabasefleetmanager.FirewallRulesClientDeleteResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method FirewallRulesClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceGroupName string, fleetName string, fleetspaceName string, firewallRuleName string, options *armdatabasefleetmanager.FirewallRulesClientGetOptions) (resp azfake.Responder[armdatabasefleetmanager.FirewallRulesClientGetResponse], errResp azfake.ErrorResponder) + + // NewListByFleetspacePager is the fake for method FirewallRulesClient.NewListByFleetspacePager + // HTTP status codes to indicate success: http.StatusOK + NewListByFleetspacePager func(resourceGroupName string, fleetName string, fleetspaceName string, options *armdatabasefleetmanager.FirewallRulesClientListByFleetspaceOptions) (resp azfake.PagerResponder[armdatabasefleetmanager.FirewallRulesClientListByFleetspaceResponse]) +} + +// NewFirewallRulesServerTransport creates a new instance of FirewallRulesServerTransport with the provided implementation. +// The returned FirewallRulesServerTransport instance is connected to an instance of armdatabasefleetmanager.FirewallRulesClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewFirewallRulesServerTransport(srv *FirewallRulesServer) *FirewallRulesServerTransport { + return &FirewallRulesServerTransport{ + srv: srv, + beginCreateOrUpdate: newTracker[azfake.PollerResponder[armdatabasefleetmanager.FirewallRulesClientCreateOrUpdateResponse]](), + beginDelete: newTracker[azfake.PollerResponder[armdatabasefleetmanager.FirewallRulesClientDeleteResponse]](), + newListByFleetspacePager: newTracker[azfake.PagerResponder[armdatabasefleetmanager.FirewallRulesClientListByFleetspaceResponse]](), + } +} + +// FirewallRulesServerTransport connects instances of armdatabasefleetmanager.FirewallRulesClient to instances of FirewallRulesServer. +// Don't use this type directly, use NewFirewallRulesServerTransport instead. +type FirewallRulesServerTransport struct { + srv *FirewallRulesServer + beginCreateOrUpdate *tracker[azfake.PollerResponder[armdatabasefleetmanager.FirewallRulesClientCreateOrUpdateResponse]] + beginDelete *tracker[azfake.PollerResponder[armdatabasefleetmanager.FirewallRulesClientDeleteResponse]] + newListByFleetspacePager *tracker[azfake.PagerResponder[armdatabasefleetmanager.FirewallRulesClientListByFleetspaceResponse]] +} + +// Do implements the policy.Transporter interface for FirewallRulesServerTransport. +func (f *FirewallRulesServerTransport) 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 f.dispatchToMethodFake(req, method) +} + +func (f *FirewallRulesServerTransport) 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 firewallRulesServerTransportInterceptor != nil { + res.resp, res.err, intercepted = firewallRulesServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "FirewallRulesClient.BeginCreateOrUpdate": + res.resp, res.err = f.dispatchBeginCreateOrUpdate(req) + case "FirewallRulesClient.BeginDelete": + res.resp, res.err = f.dispatchBeginDelete(req) + case "FirewallRulesClient.Get": + res.resp, res.err = f.dispatchGet(req) + case "FirewallRulesClient.NewListByFleetspacePager": + res.resp, res.err = f.dispatchNewListByFleetspacePager(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 (f *FirewallRulesServerTransport) dispatchBeginCreateOrUpdate(req *http.Request) (*http.Response, error) { + if f.srv.BeginCreateOrUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginCreateOrUpdate not implemented")} + } + beginCreateOrUpdate := f.beginCreateOrUpdate.get(req) + if beginCreateOrUpdate == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DatabaseFleetManager/fleets/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/fleetspaces/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/firewallRules/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if matches == nil || len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armdatabasefleetmanager.FirewallRule](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + fleetNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("fleetName")]) + if err != nil { + return nil, err + } + fleetspaceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("fleetspaceName")]) + if err != nil { + return nil, err + } + firewallRuleNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("firewallRuleName")]) + if err != nil { + return nil, err + } + respr, errRespr := f.srv.BeginCreateOrUpdate(req.Context(), resourceGroupNameParam, fleetNameParam, fleetspaceNameParam, firewallRuleNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginCreateOrUpdate = &respr + f.beginCreateOrUpdate.add(req, beginCreateOrUpdate) + } + + resp, err := server.PollerResponderNext(beginCreateOrUpdate, req) + if err != nil { + return nil, err + } + + if !contains([]int{http.StatusOK, http.StatusCreated}, resp.StatusCode) { + f.beginCreateOrUpdate.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", resp.StatusCode)} + } + if !server.PollerResponderMore(beginCreateOrUpdate) { + f.beginCreateOrUpdate.remove(req) + } + + return resp, nil +} + +func (f *FirewallRulesServerTransport) dispatchBeginDelete(req *http.Request) (*http.Response, error) { + if f.srv.BeginDelete == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginDelete not implemented")} + } + beginDelete := f.beginDelete.get(req) + if beginDelete == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DatabaseFleetManager/fleets/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/fleetspaces/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/firewallRules/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if matches == nil || len(matches) < 5 { + 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 + } + fleetNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("fleetName")]) + if err != nil { + return nil, err + } + fleetspaceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("fleetspaceName")]) + if err != nil { + return nil, err + } + firewallRuleNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("firewallRuleName")]) + if err != nil { + return nil, err + } + respr, errRespr := f.srv.BeginDelete(req.Context(), resourceGroupNameParam, fleetNameParam, fleetspaceNameParam, firewallRuleNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginDelete = &respr + f.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) { + f.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) { + f.beginDelete.remove(req) + } + + return resp, nil +} + +func (f *FirewallRulesServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if f.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\.DatabaseFleetManager/fleets/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/fleetspaces/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/firewallRules/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if matches == nil || len(matches) < 5 { + 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 + } + fleetNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("fleetName")]) + if err != nil { + return nil, err + } + fleetspaceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("fleetspaceName")]) + if err != nil { + return nil, err + } + firewallRuleNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("firewallRuleName")]) + if err != nil { + return nil, err + } + respr, errRespr := f.srv.Get(req.Context(), resourceGroupNameParam, fleetNameParam, fleetspaceNameParam, firewallRuleNameParam, 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).FirewallRule, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (f *FirewallRulesServerTransport) dispatchNewListByFleetspacePager(req *http.Request) (*http.Response, error) { + if f.srv.NewListByFleetspacePager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListByFleetspacePager not implemented")} + } + newListByFleetspacePager := f.newListByFleetspacePager.get(req) + if newListByFleetspacePager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DatabaseFleetManager/fleets/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/fleetspaces/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/firewallRules` + 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) + } + qp := req.URL.Query() + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + fleetNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("fleetName")]) + if err != nil { + return nil, err + } + fleetspaceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("fleetspaceName")]) + if err != nil { + return nil, err + } + skipUnescaped, err := url.QueryUnescape(qp.Get("$skip")) + if err != nil { + return nil, err + } + skipParam, err := parseOptional(skipUnescaped, func(v string) (int64, error) { + p, parseErr := strconv.ParseInt(v, 10, 64) + if parseErr != nil { + return 0, parseErr + } + return p, nil + }) + if err != nil { + return nil, err + } + topUnescaped, err := url.QueryUnescape(qp.Get("$top")) + if err != nil { + return nil, err + } + topParam, err := parseOptional(topUnescaped, func(v string) (int64, error) { + p, parseErr := strconv.ParseInt(v, 10, 64) + if parseErr != nil { + return 0, parseErr + } + return p, nil + }) + if err != nil { + return nil, err + } + skiptokenUnescaped, err := url.QueryUnescape(qp.Get("$skiptoken")) + if err != nil { + return nil, err + } + skiptokenParam := getOptional(skiptokenUnescaped) + var options *armdatabasefleetmanager.FirewallRulesClientListByFleetspaceOptions + if skipParam != nil || topParam != nil || skiptokenParam != nil { + options = &armdatabasefleetmanager.FirewallRulesClientListByFleetspaceOptions{ + Skip: skipParam, + Top: topParam, + Skiptoken: skiptokenParam, + } + } + resp := f.srv.NewListByFleetspacePager(resourceGroupNameParam, fleetNameParam, fleetspaceNameParam, options) + newListByFleetspacePager = &resp + f.newListByFleetspacePager.add(req, newListByFleetspacePager) + server.PagerResponderInjectNextLinks(newListByFleetspacePager, req, func(page *armdatabasefleetmanager.FirewallRulesClientListByFleetspaceResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListByFleetspacePager, req) + if err != nil { + return nil, err + } + if !contains([]int{http.StatusOK}, resp.StatusCode) { + f.newListByFleetspacePager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListByFleetspacePager) { + f.newListByFleetspacePager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to FirewallRulesServerTransport +var firewallRulesServerTransportInterceptor 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/databasefleetmanager/armdatabasefleetmanager/fake/fleetdatabases_server.go b/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager/fake/fleetdatabases_server.go new file mode 100644 index 000000000000..4685274ef9ce --- /dev/null +++ b/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager/fake/fleetdatabases_server.go @@ -0,0 +1,610 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager" + "net/http" + "net/url" + "regexp" + "strconv" +) + +// FleetDatabasesServer is a fake server for instances of the armdatabasefleetmanager.FleetDatabasesClient type. +type FleetDatabasesServer struct { + // BeginChangeTier is the fake for method FleetDatabasesClient.BeginChangeTier + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent + BeginChangeTier func(ctx context.Context, resourceGroupName string, fleetName string, fleetspaceName string, databaseName string, body armdatabasefleetmanager.DatabaseChangeTierProperties, options *armdatabasefleetmanager.FleetDatabasesClientBeginChangeTierOptions) (resp azfake.PollerResponder[armdatabasefleetmanager.FleetDatabasesClientChangeTierResponse], errResp azfake.ErrorResponder) + + // BeginCreateOrUpdate is the fake for method FleetDatabasesClient.BeginCreateOrUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + BeginCreateOrUpdate func(ctx context.Context, resourceGroupName string, fleetName string, fleetspaceName string, databaseName string, resource armdatabasefleetmanager.FleetDatabase, options *armdatabasefleetmanager.FleetDatabasesClientBeginCreateOrUpdateOptions) (resp azfake.PollerResponder[armdatabasefleetmanager.FleetDatabasesClientCreateOrUpdateResponse], errResp azfake.ErrorResponder) + + // BeginDelete is the fake for method FleetDatabasesClient.BeginDelete + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent + BeginDelete func(ctx context.Context, resourceGroupName string, fleetName string, fleetspaceName string, databaseName string, options *armdatabasefleetmanager.FleetDatabasesClientBeginDeleteOptions) (resp azfake.PollerResponder[armdatabasefleetmanager.FleetDatabasesClientDeleteResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method FleetDatabasesClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceGroupName string, fleetName string, fleetspaceName string, databaseName string, options *armdatabasefleetmanager.FleetDatabasesClientGetOptions) (resp azfake.Responder[armdatabasefleetmanager.FleetDatabasesClientGetResponse], errResp azfake.ErrorResponder) + + // NewListByFleetspacePager is the fake for method FleetDatabasesClient.NewListByFleetspacePager + // HTTP status codes to indicate success: http.StatusOK + NewListByFleetspacePager func(resourceGroupName string, fleetName string, fleetspaceName string, options *armdatabasefleetmanager.FleetDatabasesClientListByFleetspaceOptions) (resp azfake.PagerResponder[armdatabasefleetmanager.FleetDatabasesClientListByFleetspaceResponse]) + + // BeginRename is the fake for method FleetDatabasesClient.BeginRename + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent + BeginRename func(ctx context.Context, resourceGroupName string, fleetName string, fleetspaceName string, databaseName string, body armdatabasefleetmanager.DatabaseRenameProperties, options *armdatabasefleetmanager.FleetDatabasesClientBeginRenameOptions) (resp azfake.PollerResponder[armdatabasefleetmanager.FleetDatabasesClientRenameResponse], errResp azfake.ErrorResponder) + + // BeginRevert is the fake for method FleetDatabasesClient.BeginRevert + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent + BeginRevert func(ctx context.Context, resourceGroupName string, fleetName string, fleetspaceName string, databaseName string, options *armdatabasefleetmanager.FleetDatabasesClientBeginRevertOptions) (resp azfake.PollerResponder[armdatabasefleetmanager.FleetDatabasesClientRevertResponse], errResp azfake.ErrorResponder) + + // BeginUpdate is the fake for method FleetDatabasesClient.BeginUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted + BeginUpdate func(ctx context.Context, resourceGroupName string, fleetName string, fleetspaceName string, databaseName string, properties armdatabasefleetmanager.FleetDatabase, options *armdatabasefleetmanager.FleetDatabasesClientBeginUpdateOptions) (resp azfake.PollerResponder[armdatabasefleetmanager.FleetDatabasesClientUpdateResponse], errResp azfake.ErrorResponder) +} + +// NewFleetDatabasesServerTransport creates a new instance of FleetDatabasesServerTransport with the provided implementation. +// The returned FleetDatabasesServerTransport instance is connected to an instance of armdatabasefleetmanager.FleetDatabasesClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewFleetDatabasesServerTransport(srv *FleetDatabasesServer) *FleetDatabasesServerTransport { + return &FleetDatabasesServerTransport{ + srv: srv, + beginChangeTier: newTracker[azfake.PollerResponder[armdatabasefleetmanager.FleetDatabasesClientChangeTierResponse]](), + beginCreateOrUpdate: newTracker[azfake.PollerResponder[armdatabasefleetmanager.FleetDatabasesClientCreateOrUpdateResponse]](), + beginDelete: newTracker[azfake.PollerResponder[armdatabasefleetmanager.FleetDatabasesClientDeleteResponse]](), + newListByFleetspacePager: newTracker[azfake.PagerResponder[armdatabasefleetmanager.FleetDatabasesClientListByFleetspaceResponse]](), + beginRename: newTracker[azfake.PollerResponder[armdatabasefleetmanager.FleetDatabasesClientRenameResponse]](), + beginRevert: newTracker[azfake.PollerResponder[armdatabasefleetmanager.FleetDatabasesClientRevertResponse]](), + beginUpdate: newTracker[azfake.PollerResponder[armdatabasefleetmanager.FleetDatabasesClientUpdateResponse]](), + } +} + +// FleetDatabasesServerTransport connects instances of armdatabasefleetmanager.FleetDatabasesClient to instances of FleetDatabasesServer. +// Don't use this type directly, use NewFleetDatabasesServerTransport instead. +type FleetDatabasesServerTransport struct { + srv *FleetDatabasesServer + beginChangeTier *tracker[azfake.PollerResponder[armdatabasefleetmanager.FleetDatabasesClientChangeTierResponse]] + beginCreateOrUpdate *tracker[azfake.PollerResponder[armdatabasefleetmanager.FleetDatabasesClientCreateOrUpdateResponse]] + beginDelete *tracker[azfake.PollerResponder[armdatabasefleetmanager.FleetDatabasesClientDeleteResponse]] + newListByFleetspacePager *tracker[azfake.PagerResponder[armdatabasefleetmanager.FleetDatabasesClientListByFleetspaceResponse]] + beginRename *tracker[azfake.PollerResponder[armdatabasefleetmanager.FleetDatabasesClientRenameResponse]] + beginRevert *tracker[azfake.PollerResponder[armdatabasefleetmanager.FleetDatabasesClientRevertResponse]] + beginUpdate *tracker[azfake.PollerResponder[armdatabasefleetmanager.FleetDatabasesClientUpdateResponse]] +} + +// Do implements the policy.Transporter interface for FleetDatabasesServerTransport. +func (f *FleetDatabasesServerTransport) 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 f.dispatchToMethodFake(req, method) +} + +func (f *FleetDatabasesServerTransport) 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 fleetDatabasesServerTransportInterceptor != nil { + res.resp, res.err, intercepted = fleetDatabasesServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "FleetDatabasesClient.BeginChangeTier": + res.resp, res.err = f.dispatchBeginChangeTier(req) + case "FleetDatabasesClient.BeginCreateOrUpdate": + res.resp, res.err = f.dispatchBeginCreateOrUpdate(req) + case "FleetDatabasesClient.BeginDelete": + res.resp, res.err = f.dispatchBeginDelete(req) + case "FleetDatabasesClient.Get": + res.resp, res.err = f.dispatchGet(req) + case "FleetDatabasesClient.NewListByFleetspacePager": + res.resp, res.err = f.dispatchNewListByFleetspacePager(req) + case "FleetDatabasesClient.BeginRename": + res.resp, res.err = f.dispatchBeginRename(req) + case "FleetDatabasesClient.BeginRevert": + res.resp, res.err = f.dispatchBeginRevert(req) + case "FleetDatabasesClient.BeginUpdate": + res.resp, res.err = f.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 (f *FleetDatabasesServerTransport) dispatchBeginChangeTier(req *http.Request) (*http.Response, error) { + if f.srv.BeginChangeTier == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginChangeTier not implemented")} + } + beginChangeTier := f.beginChangeTier.get(req) + if beginChangeTier == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DatabaseFleetManager/fleets/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/fleetspaces/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/databases/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/changeTier` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if matches == nil || len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armdatabasefleetmanager.DatabaseChangeTierProperties](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + fleetNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("fleetName")]) + if err != nil { + return nil, err + } + fleetspaceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("fleetspaceName")]) + if err != nil { + return nil, err + } + databaseNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("databaseName")]) + if err != nil { + return nil, err + } + respr, errRespr := f.srv.BeginChangeTier(req.Context(), resourceGroupNameParam, fleetNameParam, fleetspaceNameParam, databaseNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginChangeTier = &respr + f.beginChangeTier.add(req, beginChangeTier) + } + + resp, err := server.PollerResponderNext(beginChangeTier, req) + if err != nil { + return nil, err + } + + if !contains([]int{http.StatusOK, http.StatusAccepted, http.StatusNoContent}, resp.StatusCode) { + f.beginChangeTier.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(beginChangeTier) { + f.beginChangeTier.remove(req) + } + + return resp, nil +} + +func (f *FleetDatabasesServerTransport) dispatchBeginCreateOrUpdate(req *http.Request) (*http.Response, error) { + if f.srv.BeginCreateOrUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginCreateOrUpdate not implemented")} + } + beginCreateOrUpdate := f.beginCreateOrUpdate.get(req) + if beginCreateOrUpdate == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DatabaseFleetManager/fleets/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/fleetspaces/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/databases/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if matches == nil || len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armdatabasefleetmanager.FleetDatabase](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + fleetNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("fleetName")]) + if err != nil { + return nil, err + } + fleetspaceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("fleetspaceName")]) + if err != nil { + return nil, err + } + databaseNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("databaseName")]) + if err != nil { + return nil, err + } + respr, errRespr := f.srv.BeginCreateOrUpdate(req.Context(), resourceGroupNameParam, fleetNameParam, fleetspaceNameParam, databaseNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginCreateOrUpdate = &respr + f.beginCreateOrUpdate.add(req, beginCreateOrUpdate) + } + + resp, err := server.PollerResponderNext(beginCreateOrUpdate, req) + if err != nil { + return nil, err + } + + if !contains([]int{http.StatusOK, http.StatusCreated}, resp.StatusCode) { + f.beginCreateOrUpdate.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", resp.StatusCode)} + } + if !server.PollerResponderMore(beginCreateOrUpdate) { + f.beginCreateOrUpdate.remove(req) + } + + return resp, nil +} + +func (f *FleetDatabasesServerTransport) dispatchBeginDelete(req *http.Request) (*http.Response, error) { + if f.srv.BeginDelete == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginDelete not implemented")} + } + beginDelete := f.beginDelete.get(req) + if beginDelete == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DatabaseFleetManager/fleets/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/fleetspaces/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/databases/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if matches == nil || len(matches) < 5 { + 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 + } + fleetNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("fleetName")]) + if err != nil { + return nil, err + } + fleetspaceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("fleetspaceName")]) + if err != nil { + return nil, err + } + databaseNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("databaseName")]) + if err != nil { + return nil, err + } + respr, errRespr := f.srv.BeginDelete(req.Context(), resourceGroupNameParam, fleetNameParam, fleetspaceNameParam, databaseNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginDelete = &respr + f.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) { + f.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) { + f.beginDelete.remove(req) + } + + return resp, nil +} + +func (f *FleetDatabasesServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if f.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\.DatabaseFleetManager/fleets/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/fleetspaces/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/databases/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if matches == nil || len(matches) < 5 { + 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 + } + fleetNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("fleetName")]) + if err != nil { + return nil, err + } + fleetspaceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("fleetspaceName")]) + if err != nil { + return nil, err + } + databaseNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("databaseName")]) + if err != nil { + return nil, err + } + respr, errRespr := f.srv.Get(req.Context(), resourceGroupNameParam, fleetNameParam, fleetspaceNameParam, databaseNameParam, 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).FleetDatabase, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (f *FleetDatabasesServerTransport) dispatchNewListByFleetspacePager(req *http.Request) (*http.Response, error) { + if f.srv.NewListByFleetspacePager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListByFleetspacePager not implemented")} + } + newListByFleetspacePager := f.newListByFleetspacePager.get(req) + if newListByFleetspacePager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DatabaseFleetManager/fleets/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/fleetspaces/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/databases` + 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) + } + qp := req.URL.Query() + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + fleetNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("fleetName")]) + if err != nil { + return nil, err + } + fleetspaceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("fleetspaceName")]) + if err != nil { + return nil, err + } + skipUnescaped, err := url.QueryUnescape(qp.Get("$skip")) + if err != nil { + return nil, err + } + skipParam, err := parseOptional(skipUnescaped, func(v string) (int64, error) { + p, parseErr := strconv.ParseInt(v, 10, 64) + if parseErr != nil { + return 0, parseErr + } + return p, nil + }) + if err != nil { + return nil, err + } + topUnescaped, err := url.QueryUnescape(qp.Get("$top")) + if err != nil { + return nil, err + } + topParam, err := parseOptional(topUnescaped, func(v string) (int64, error) { + p, parseErr := strconv.ParseInt(v, 10, 64) + if parseErr != nil { + return 0, parseErr + } + return p, nil + }) + if err != nil { + return nil, err + } + filterUnescaped, err := url.QueryUnescape(qp.Get("$filter")) + if err != nil { + return nil, err + } + filterParam := getOptional(filterUnescaped) + skiptokenUnescaped, err := url.QueryUnescape(qp.Get("$skiptoken")) + if err != nil { + return nil, err + } + skiptokenParam := getOptional(skiptokenUnescaped) + var options *armdatabasefleetmanager.FleetDatabasesClientListByFleetspaceOptions + if skipParam != nil || topParam != nil || filterParam != nil || skiptokenParam != nil { + options = &armdatabasefleetmanager.FleetDatabasesClientListByFleetspaceOptions{ + Skip: skipParam, + Top: topParam, + Filter: filterParam, + Skiptoken: skiptokenParam, + } + } + resp := f.srv.NewListByFleetspacePager(resourceGroupNameParam, fleetNameParam, fleetspaceNameParam, options) + newListByFleetspacePager = &resp + f.newListByFleetspacePager.add(req, newListByFleetspacePager) + server.PagerResponderInjectNextLinks(newListByFleetspacePager, req, func(page *armdatabasefleetmanager.FleetDatabasesClientListByFleetspaceResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListByFleetspacePager, req) + if err != nil { + return nil, err + } + if !contains([]int{http.StatusOK}, resp.StatusCode) { + f.newListByFleetspacePager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListByFleetspacePager) { + f.newListByFleetspacePager.remove(req) + } + return resp, nil +} + +func (f *FleetDatabasesServerTransport) dispatchBeginRename(req *http.Request) (*http.Response, error) { + if f.srv.BeginRename == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginRename not implemented")} + } + beginRename := f.beginRename.get(req) + if beginRename == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DatabaseFleetManager/fleets/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/fleetspaces/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/databases/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/rename` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if matches == nil || len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armdatabasefleetmanager.DatabaseRenameProperties](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + fleetNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("fleetName")]) + if err != nil { + return nil, err + } + fleetspaceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("fleetspaceName")]) + if err != nil { + return nil, err + } + databaseNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("databaseName")]) + if err != nil { + return nil, err + } + respr, errRespr := f.srv.BeginRename(req.Context(), resourceGroupNameParam, fleetNameParam, fleetspaceNameParam, databaseNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginRename = &respr + f.beginRename.add(req, beginRename) + } + + resp, err := server.PollerResponderNext(beginRename, req) + if err != nil { + return nil, err + } + + if !contains([]int{http.StatusOK, http.StatusAccepted, http.StatusNoContent}, resp.StatusCode) { + f.beginRename.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(beginRename) { + f.beginRename.remove(req) + } + + return resp, nil +} + +func (f *FleetDatabasesServerTransport) dispatchBeginRevert(req *http.Request) (*http.Response, error) { + if f.srv.BeginRevert == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginRevert not implemented")} + } + beginRevert := f.beginRevert.get(req) + if beginRevert == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DatabaseFleetManager/fleets/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/fleetspaces/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/databases/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/revert` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if matches == nil || len(matches) < 5 { + 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 + } + fleetNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("fleetName")]) + if err != nil { + return nil, err + } + fleetspaceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("fleetspaceName")]) + if err != nil { + return nil, err + } + databaseNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("databaseName")]) + if err != nil { + return nil, err + } + respr, errRespr := f.srv.BeginRevert(req.Context(), resourceGroupNameParam, fleetNameParam, fleetspaceNameParam, databaseNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginRevert = &respr + f.beginRevert.add(req, beginRevert) + } + + resp, err := server.PollerResponderNext(beginRevert, req) + if err != nil { + return nil, err + } + + if !contains([]int{http.StatusOK, http.StatusAccepted, http.StatusNoContent}, resp.StatusCode) { + f.beginRevert.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(beginRevert) { + f.beginRevert.remove(req) + } + + return resp, nil +} + +func (f *FleetDatabasesServerTransport) dispatchBeginUpdate(req *http.Request) (*http.Response, error) { + if f.srv.BeginUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginUpdate not implemented")} + } + beginUpdate := f.beginUpdate.get(req) + if beginUpdate == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DatabaseFleetManager/fleets/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/fleetspaces/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/databases/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if matches == nil || len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armdatabasefleetmanager.FleetDatabase](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + fleetNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("fleetName")]) + if err != nil { + return nil, err + } + fleetspaceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("fleetspaceName")]) + if err != nil { + return nil, err + } + databaseNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("databaseName")]) + if err != nil { + return nil, err + } + respr, errRespr := f.srv.BeginUpdate(req.Context(), resourceGroupNameParam, fleetNameParam, fleetspaceNameParam, databaseNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginUpdate = &respr + f.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) { + f.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) { + f.beginUpdate.remove(req) + } + + return resp, nil +} + +// set this to conditionally intercept incoming requests to FleetDatabasesServerTransport +var fleetDatabasesServerTransportInterceptor 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/databasefleetmanager/armdatabasefleetmanager/fake/fleets_server.go b/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager/fake/fleets_server.go new file mode 100644 index 000000000000..e5d68393ad38 --- /dev/null +++ b/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager/fake/fleets_server.go @@ -0,0 +1,417 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager" + "net/http" + "net/url" + "regexp" + "strconv" +) + +// FleetsServer is a fake server for instances of the armdatabasefleetmanager.FleetsClient type. +type FleetsServer struct { + // BeginCreateOrUpdate is the fake for method FleetsClient.BeginCreateOrUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + BeginCreateOrUpdate func(ctx context.Context, resourceGroupName string, fleetName string, resource armdatabasefleetmanager.Fleet, options *armdatabasefleetmanager.FleetsClientBeginCreateOrUpdateOptions) (resp azfake.PollerResponder[armdatabasefleetmanager.FleetsClientCreateOrUpdateResponse], errResp azfake.ErrorResponder) + + // BeginDelete is the fake for method FleetsClient.BeginDelete + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent + BeginDelete func(ctx context.Context, resourceGroupName string, fleetName string, options *armdatabasefleetmanager.FleetsClientBeginDeleteOptions) (resp azfake.PollerResponder[armdatabasefleetmanager.FleetsClientDeleteResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method FleetsClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceGroupName string, fleetName string, options *armdatabasefleetmanager.FleetsClientGetOptions) (resp azfake.Responder[armdatabasefleetmanager.FleetsClientGetResponse], errResp azfake.ErrorResponder) + + // NewListPager is the fake for method FleetsClient.NewListPager + // HTTP status codes to indicate success: http.StatusOK + NewListPager func(options *armdatabasefleetmanager.FleetsClientListOptions) (resp azfake.PagerResponder[armdatabasefleetmanager.FleetsClientListResponse]) + + // NewListByResourceGroupPager is the fake for method FleetsClient.NewListByResourceGroupPager + // HTTP status codes to indicate success: http.StatusOK + NewListByResourceGroupPager func(resourceGroupName string, options *armdatabasefleetmanager.FleetsClientListByResourceGroupOptions) (resp azfake.PagerResponder[armdatabasefleetmanager.FleetsClientListByResourceGroupResponse]) + + // BeginUpdate is the fake for method FleetsClient.BeginUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted + BeginUpdate func(ctx context.Context, resourceGroupName string, fleetName string, properties armdatabasefleetmanager.FleetUpdate, options *armdatabasefleetmanager.FleetsClientBeginUpdateOptions) (resp azfake.PollerResponder[armdatabasefleetmanager.FleetsClientUpdateResponse], errResp azfake.ErrorResponder) +} + +// NewFleetsServerTransport creates a new instance of FleetsServerTransport with the provided implementation. +// The returned FleetsServerTransport instance is connected to an instance of armdatabasefleetmanager.FleetsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewFleetsServerTransport(srv *FleetsServer) *FleetsServerTransport { + return &FleetsServerTransport{ + srv: srv, + beginCreateOrUpdate: newTracker[azfake.PollerResponder[armdatabasefleetmanager.FleetsClientCreateOrUpdateResponse]](), + beginDelete: newTracker[azfake.PollerResponder[armdatabasefleetmanager.FleetsClientDeleteResponse]](), + newListPager: newTracker[azfake.PagerResponder[armdatabasefleetmanager.FleetsClientListResponse]](), + newListByResourceGroupPager: newTracker[azfake.PagerResponder[armdatabasefleetmanager.FleetsClientListByResourceGroupResponse]](), + beginUpdate: newTracker[azfake.PollerResponder[armdatabasefleetmanager.FleetsClientUpdateResponse]](), + } +} + +// FleetsServerTransport connects instances of armdatabasefleetmanager.FleetsClient to instances of FleetsServer. +// Don't use this type directly, use NewFleetsServerTransport instead. +type FleetsServerTransport struct { + srv *FleetsServer + beginCreateOrUpdate *tracker[azfake.PollerResponder[armdatabasefleetmanager.FleetsClientCreateOrUpdateResponse]] + beginDelete *tracker[azfake.PollerResponder[armdatabasefleetmanager.FleetsClientDeleteResponse]] + newListPager *tracker[azfake.PagerResponder[armdatabasefleetmanager.FleetsClientListResponse]] + newListByResourceGroupPager *tracker[azfake.PagerResponder[armdatabasefleetmanager.FleetsClientListByResourceGroupResponse]] + beginUpdate *tracker[azfake.PollerResponder[armdatabasefleetmanager.FleetsClientUpdateResponse]] +} + +// Do implements the policy.Transporter interface for FleetsServerTransport. +func (f *FleetsServerTransport) 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 f.dispatchToMethodFake(req, method) +} + +func (f *FleetsServerTransport) 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 fleetsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = fleetsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "FleetsClient.BeginCreateOrUpdate": + res.resp, res.err = f.dispatchBeginCreateOrUpdate(req) + case "FleetsClient.BeginDelete": + res.resp, res.err = f.dispatchBeginDelete(req) + case "FleetsClient.Get": + res.resp, res.err = f.dispatchGet(req) + case "FleetsClient.NewListPager": + res.resp, res.err = f.dispatchNewListPager(req) + case "FleetsClient.NewListByResourceGroupPager": + res.resp, res.err = f.dispatchNewListByResourceGroupPager(req) + case "FleetsClient.BeginUpdate": + res.resp, res.err = f.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 (f *FleetsServerTransport) dispatchBeginCreateOrUpdate(req *http.Request) (*http.Response, error) { + if f.srv.BeginCreateOrUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginCreateOrUpdate not implemented")} + } + beginCreateOrUpdate := f.beginCreateOrUpdate.get(req) + if beginCreateOrUpdate == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DatabaseFleetManager/fleets/(?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[armdatabasefleetmanager.Fleet](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + fleetNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("fleetName")]) + if err != nil { + return nil, err + } + respr, errRespr := f.srv.BeginCreateOrUpdate(req.Context(), resourceGroupNameParam, fleetNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginCreateOrUpdate = &respr + f.beginCreateOrUpdate.add(req, beginCreateOrUpdate) + } + + resp, err := server.PollerResponderNext(beginCreateOrUpdate, req) + if err != nil { + return nil, err + } + + if !contains([]int{http.StatusOK, http.StatusCreated}, resp.StatusCode) { + f.beginCreateOrUpdate.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", resp.StatusCode)} + } + if !server.PollerResponderMore(beginCreateOrUpdate) { + f.beginCreateOrUpdate.remove(req) + } + + return resp, nil +} + +func (f *FleetsServerTransport) dispatchBeginDelete(req *http.Request) (*http.Response, error) { + if f.srv.BeginDelete == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginDelete not implemented")} + } + beginDelete := f.beginDelete.get(req) + if beginDelete == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DatabaseFleetManager/fleets/(?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 + } + fleetNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("fleetName")]) + if err != nil { + return nil, err + } + respr, errRespr := f.srv.BeginDelete(req.Context(), resourceGroupNameParam, fleetNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginDelete = &respr + f.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) { + f.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) { + f.beginDelete.remove(req) + } + + return resp, nil +} + +func (f *FleetsServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if f.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\.DatabaseFleetManager/fleets/(?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 + } + fleetNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("fleetName")]) + if err != nil { + return nil, err + } + respr, errRespr := f.srv.Get(req.Context(), resourceGroupNameParam, fleetNameParam, 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).Fleet, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (f *FleetsServerTransport) dispatchNewListPager(req *http.Request) (*http.Response, error) { + if f.srv.NewListPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListPager not implemented")} + } + newListPager := f.newListPager.get(req) + if newListPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DatabaseFleetManager/fleets` + 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 := f.srv.NewListPager(nil) + newListPager = &resp + f.newListPager.add(req, newListPager) + server.PagerResponderInjectNextLinks(newListPager, req, func(page *armdatabasefleetmanager.FleetsClientListResponse, 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) { + f.newListPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListPager) { + f.newListPager.remove(req) + } + return resp, nil +} + +func (f *FleetsServerTransport) dispatchNewListByResourceGroupPager(req *http.Request) (*http.Response, error) { + if f.srv.NewListByResourceGroupPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListByResourceGroupPager not implemented")} + } + newListByResourceGroupPager := f.newListByResourceGroupPager.get(req) + if newListByResourceGroupPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DatabaseFleetManager/fleets` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if matches == nil || len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + qp := req.URL.Query() + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + skipUnescaped, err := url.QueryUnescape(qp.Get("$skip")) + if err != nil { + return nil, err + } + skipParam, err := parseOptional(skipUnescaped, func(v string) (int64, error) { + p, parseErr := strconv.ParseInt(v, 10, 64) + if parseErr != nil { + return 0, parseErr + } + return p, nil + }) + if err != nil { + return nil, err + } + topUnescaped, err := url.QueryUnescape(qp.Get("$top")) + if err != nil { + return nil, err + } + topParam, err := parseOptional(topUnescaped, func(v string) (int64, error) { + p, parseErr := strconv.ParseInt(v, 10, 64) + if parseErr != nil { + return 0, parseErr + } + return p, nil + }) + if err != nil { + return nil, err + } + skiptokenUnescaped, err := url.QueryUnescape(qp.Get("$skiptoken")) + if err != nil { + return nil, err + } + skiptokenParam := getOptional(skiptokenUnescaped) + var options *armdatabasefleetmanager.FleetsClientListByResourceGroupOptions + if skipParam != nil || topParam != nil || skiptokenParam != nil { + options = &armdatabasefleetmanager.FleetsClientListByResourceGroupOptions{ + Skip: skipParam, + Top: topParam, + Skiptoken: skiptokenParam, + } + } + resp := f.srv.NewListByResourceGroupPager(resourceGroupNameParam, options) + newListByResourceGroupPager = &resp + f.newListByResourceGroupPager.add(req, newListByResourceGroupPager) + server.PagerResponderInjectNextLinks(newListByResourceGroupPager, req, func(page *armdatabasefleetmanager.FleetsClientListByResourceGroupResponse, 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) { + f.newListByResourceGroupPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListByResourceGroupPager) { + f.newListByResourceGroupPager.remove(req) + } + return resp, nil +} + +func (f *FleetsServerTransport) dispatchBeginUpdate(req *http.Request) (*http.Response, error) { + if f.srv.BeginUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginUpdate not implemented")} + } + beginUpdate := f.beginUpdate.get(req) + if beginUpdate == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DatabaseFleetManager/fleets/(?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[armdatabasefleetmanager.FleetUpdate](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + fleetNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("fleetName")]) + if err != nil { + return nil, err + } + respr, errRespr := f.srv.BeginUpdate(req.Context(), resourceGroupNameParam, fleetNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginUpdate = &respr + f.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) { + f.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) { + f.beginUpdate.remove(req) + } + + return resp, nil +} + +// set this to conditionally intercept incoming requests to FleetsServerTransport +var fleetsServerTransportInterceptor 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/databasefleetmanager/armdatabasefleetmanager/fake/fleetspaces_server.go b/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager/fake/fleetspaces_server.go new file mode 100644 index 000000000000..b1de42345aa8 --- /dev/null +++ b/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager/fake/fleetspaces_server.go @@ -0,0 +1,512 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager" + "net/http" + "net/url" + "regexp" + "strconv" +) + +// FleetspacesServer is a fake server for instances of the armdatabasefleetmanager.FleetspacesClient type. +type FleetspacesServer struct { + // BeginCreateOrUpdate is the fake for method FleetspacesClient.BeginCreateOrUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + BeginCreateOrUpdate func(ctx context.Context, resourceGroupName string, fleetName string, fleetspaceName string, resource armdatabasefleetmanager.Fleetspace, options *armdatabasefleetmanager.FleetspacesClientBeginCreateOrUpdateOptions) (resp azfake.PollerResponder[armdatabasefleetmanager.FleetspacesClientCreateOrUpdateResponse], errResp azfake.ErrorResponder) + + // BeginDelete is the fake for method FleetspacesClient.BeginDelete + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent + BeginDelete func(ctx context.Context, resourceGroupName string, fleetName string, fleetspaceName string, options *armdatabasefleetmanager.FleetspacesClientBeginDeleteOptions) (resp azfake.PollerResponder[armdatabasefleetmanager.FleetspacesClientDeleteResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method FleetspacesClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceGroupName string, fleetName string, fleetspaceName string, options *armdatabasefleetmanager.FleetspacesClientGetOptions) (resp azfake.Responder[armdatabasefleetmanager.FleetspacesClientGetResponse], errResp azfake.ErrorResponder) + + // NewListByFleetPager is the fake for method FleetspacesClient.NewListByFleetPager + // HTTP status codes to indicate success: http.StatusOK + NewListByFleetPager func(resourceGroupName string, fleetName string, options *armdatabasefleetmanager.FleetspacesClientListByFleetOptions) (resp azfake.PagerResponder[armdatabasefleetmanager.FleetspacesClientListByFleetResponse]) + + // BeginRegisterServer is the fake for method FleetspacesClient.BeginRegisterServer + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent + BeginRegisterServer func(ctx context.Context, resourceGroupName string, fleetName string, fleetspaceName string, body armdatabasefleetmanager.RegisterServerProperties, options *armdatabasefleetmanager.FleetspacesClientBeginRegisterServerOptions) (resp azfake.PollerResponder[armdatabasefleetmanager.FleetspacesClientRegisterServerResponse], errResp azfake.ErrorResponder) + + // BeginUnregister is the fake for method FleetspacesClient.BeginUnregister + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent + BeginUnregister func(ctx context.Context, resourceGroupName string, fleetName string, fleetspaceName string, options *armdatabasefleetmanager.FleetspacesClientBeginUnregisterOptions) (resp azfake.PollerResponder[armdatabasefleetmanager.FleetspacesClientUnregisterResponse], errResp azfake.ErrorResponder) + + // BeginUpdate is the fake for method FleetspacesClient.BeginUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted + BeginUpdate func(ctx context.Context, resourceGroupName string, fleetName string, fleetspaceName string, properties armdatabasefleetmanager.Fleetspace, options *armdatabasefleetmanager.FleetspacesClientBeginUpdateOptions) (resp azfake.PollerResponder[armdatabasefleetmanager.FleetspacesClientUpdateResponse], errResp azfake.ErrorResponder) +} + +// NewFleetspacesServerTransport creates a new instance of FleetspacesServerTransport with the provided implementation. +// The returned FleetspacesServerTransport instance is connected to an instance of armdatabasefleetmanager.FleetspacesClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewFleetspacesServerTransport(srv *FleetspacesServer) *FleetspacesServerTransport { + return &FleetspacesServerTransport{ + srv: srv, + beginCreateOrUpdate: newTracker[azfake.PollerResponder[armdatabasefleetmanager.FleetspacesClientCreateOrUpdateResponse]](), + beginDelete: newTracker[azfake.PollerResponder[armdatabasefleetmanager.FleetspacesClientDeleteResponse]](), + newListByFleetPager: newTracker[azfake.PagerResponder[armdatabasefleetmanager.FleetspacesClientListByFleetResponse]](), + beginRegisterServer: newTracker[azfake.PollerResponder[armdatabasefleetmanager.FleetspacesClientRegisterServerResponse]](), + beginUnregister: newTracker[azfake.PollerResponder[armdatabasefleetmanager.FleetspacesClientUnregisterResponse]](), + beginUpdate: newTracker[azfake.PollerResponder[armdatabasefleetmanager.FleetspacesClientUpdateResponse]](), + } +} + +// FleetspacesServerTransport connects instances of armdatabasefleetmanager.FleetspacesClient to instances of FleetspacesServer. +// Don't use this type directly, use NewFleetspacesServerTransport instead. +type FleetspacesServerTransport struct { + srv *FleetspacesServer + beginCreateOrUpdate *tracker[azfake.PollerResponder[armdatabasefleetmanager.FleetspacesClientCreateOrUpdateResponse]] + beginDelete *tracker[azfake.PollerResponder[armdatabasefleetmanager.FleetspacesClientDeleteResponse]] + newListByFleetPager *tracker[azfake.PagerResponder[armdatabasefleetmanager.FleetspacesClientListByFleetResponse]] + beginRegisterServer *tracker[azfake.PollerResponder[armdatabasefleetmanager.FleetspacesClientRegisterServerResponse]] + beginUnregister *tracker[azfake.PollerResponder[armdatabasefleetmanager.FleetspacesClientUnregisterResponse]] + beginUpdate *tracker[azfake.PollerResponder[armdatabasefleetmanager.FleetspacesClientUpdateResponse]] +} + +// Do implements the policy.Transporter interface for FleetspacesServerTransport. +func (f *FleetspacesServerTransport) 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 f.dispatchToMethodFake(req, method) +} + +func (f *FleetspacesServerTransport) 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 fleetspacesServerTransportInterceptor != nil { + res.resp, res.err, intercepted = fleetspacesServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "FleetspacesClient.BeginCreateOrUpdate": + res.resp, res.err = f.dispatchBeginCreateOrUpdate(req) + case "FleetspacesClient.BeginDelete": + res.resp, res.err = f.dispatchBeginDelete(req) + case "FleetspacesClient.Get": + res.resp, res.err = f.dispatchGet(req) + case "FleetspacesClient.NewListByFleetPager": + res.resp, res.err = f.dispatchNewListByFleetPager(req) + case "FleetspacesClient.BeginRegisterServer": + res.resp, res.err = f.dispatchBeginRegisterServer(req) + case "FleetspacesClient.BeginUnregister": + res.resp, res.err = f.dispatchBeginUnregister(req) + case "FleetspacesClient.BeginUpdate": + res.resp, res.err = f.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 (f *FleetspacesServerTransport) dispatchBeginCreateOrUpdate(req *http.Request) (*http.Response, error) { + if f.srv.BeginCreateOrUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginCreateOrUpdate not implemented")} + } + beginCreateOrUpdate := f.beginCreateOrUpdate.get(req) + if beginCreateOrUpdate == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DatabaseFleetManager/fleets/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/fleetspaces/(?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[armdatabasefleetmanager.Fleetspace](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + fleetNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("fleetName")]) + if err != nil { + return nil, err + } + fleetspaceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("fleetspaceName")]) + if err != nil { + return nil, err + } + respr, errRespr := f.srv.BeginCreateOrUpdate(req.Context(), resourceGroupNameParam, fleetNameParam, fleetspaceNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginCreateOrUpdate = &respr + f.beginCreateOrUpdate.add(req, beginCreateOrUpdate) + } + + resp, err := server.PollerResponderNext(beginCreateOrUpdate, req) + if err != nil { + return nil, err + } + + if !contains([]int{http.StatusOK, http.StatusCreated}, resp.StatusCode) { + f.beginCreateOrUpdate.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", resp.StatusCode)} + } + if !server.PollerResponderMore(beginCreateOrUpdate) { + f.beginCreateOrUpdate.remove(req) + } + + return resp, nil +} + +func (f *FleetspacesServerTransport) dispatchBeginDelete(req *http.Request) (*http.Response, error) { + if f.srv.BeginDelete == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginDelete not implemented")} + } + beginDelete := f.beginDelete.get(req) + if beginDelete == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DatabaseFleetManager/fleets/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/fleetspaces/(?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 + } + fleetNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("fleetName")]) + if err != nil { + return nil, err + } + fleetspaceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("fleetspaceName")]) + if err != nil { + return nil, err + } + respr, errRespr := f.srv.BeginDelete(req.Context(), resourceGroupNameParam, fleetNameParam, fleetspaceNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginDelete = &respr + f.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) { + f.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) { + f.beginDelete.remove(req) + } + + return resp, nil +} + +func (f *FleetspacesServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if f.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\.DatabaseFleetManager/fleets/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/fleetspaces/(?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 + } + fleetNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("fleetName")]) + if err != nil { + return nil, err + } + fleetspaceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("fleetspaceName")]) + if err != nil { + return nil, err + } + respr, errRespr := f.srv.Get(req.Context(), resourceGroupNameParam, fleetNameParam, fleetspaceNameParam, 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).Fleetspace, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (f *FleetspacesServerTransport) dispatchNewListByFleetPager(req *http.Request) (*http.Response, error) { + if f.srv.NewListByFleetPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListByFleetPager not implemented")} + } + newListByFleetPager := f.newListByFleetPager.get(req) + if newListByFleetPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DatabaseFleetManager/fleets/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/fleetspaces` + 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 + } + fleetNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("fleetName")]) + if err != nil { + return nil, err + } + skipUnescaped, err := url.QueryUnescape(qp.Get("$skip")) + if err != nil { + return nil, err + } + skipParam, err := parseOptional(skipUnescaped, func(v string) (int64, error) { + p, parseErr := strconv.ParseInt(v, 10, 64) + if parseErr != nil { + return 0, parseErr + } + return p, nil + }) + if err != nil { + return nil, err + } + topUnescaped, err := url.QueryUnescape(qp.Get("$top")) + if err != nil { + return nil, err + } + topParam, err := parseOptional(topUnescaped, func(v string) (int64, error) { + p, parseErr := strconv.ParseInt(v, 10, 64) + if parseErr != nil { + return 0, parseErr + } + return p, nil + }) + if err != nil { + return nil, err + } + skiptokenUnescaped, err := url.QueryUnescape(qp.Get("$skiptoken")) + if err != nil { + return nil, err + } + skiptokenParam := getOptional(skiptokenUnescaped) + var options *armdatabasefleetmanager.FleetspacesClientListByFleetOptions + if skipParam != nil || topParam != nil || skiptokenParam != nil { + options = &armdatabasefleetmanager.FleetspacesClientListByFleetOptions{ + Skip: skipParam, + Top: topParam, + Skiptoken: skiptokenParam, + } + } + resp := f.srv.NewListByFleetPager(resourceGroupNameParam, fleetNameParam, options) + newListByFleetPager = &resp + f.newListByFleetPager.add(req, newListByFleetPager) + server.PagerResponderInjectNextLinks(newListByFleetPager, req, func(page *armdatabasefleetmanager.FleetspacesClientListByFleetResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListByFleetPager, req) + if err != nil { + return nil, err + } + if !contains([]int{http.StatusOK}, resp.StatusCode) { + f.newListByFleetPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListByFleetPager) { + f.newListByFleetPager.remove(req) + } + return resp, nil +} + +func (f *FleetspacesServerTransport) dispatchBeginRegisterServer(req *http.Request) (*http.Response, error) { + if f.srv.BeginRegisterServer == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginRegisterServer not implemented")} + } + beginRegisterServer := f.beginRegisterServer.get(req) + if beginRegisterServer == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DatabaseFleetManager/fleets/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/fleetspaces/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/registerServer` + 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[armdatabasefleetmanager.RegisterServerProperties](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + fleetNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("fleetName")]) + if err != nil { + return nil, err + } + fleetspaceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("fleetspaceName")]) + if err != nil { + return nil, err + } + respr, errRespr := f.srv.BeginRegisterServer(req.Context(), resourceGroupNameParam, fleetNameParam, fleetspaceNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginRegisterServer = &respr + f.beginRegisterServer.add(req, beginRegisterServer) + } + + resp, err := server.PollerResponderNext(beginRegisterServer, req) + if err != nil { + return nil, err + } + + if !contains([]int{http.StatusOK, http.StatusAccepted, http.StatusNoContent}, resp.StatusCode) { + f.beginRegisterServer.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(beginRegisterServer) { + f.beginRegisterServer.remove(req) + } + + return resp, nil +} + +func (f *FleetspacesServerTransport) dispatchBeginUnregister(req *http.Request) (*http.Response, error) { + if f.srv.BeginUnregister == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginUnregister not implemented")} + } + beginUnregister := f.beginUnregister.get(req) + if beginUnregister == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DatabaseFleetManager/fleets/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/fleetspaces/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/unregister` + 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 + } + fleetNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("fleetName")]) + if err != nil { + return nil, err + } + fleetspaceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("fleetspaceName")]) + if err != nil { + return nil, err + } + respr, errRespr := f.srv.BeginUnregister(req.Context(), resourceGroupNameParam, fleetNameParam, fleetspaceNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginUnregister = &respr + f.beginUnregister.add(req, beginUnregister) + } + + resp, err := server.PollerResponderNext(beginUnregister, req) + if err != nil { + return nil, err + } + + if !contains([]int{http.StatusOK, http.StatusAccepted, http.StatusNoContent}, resp.StatusCode) { + f.beginUnregister.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(beginUnregister) { + f.beginUnregister.remove(req) + } + + return resp, nil +} + +func (f *FleetspacesServerTransport) dispatchBeginUpdate(req *http.Request) (*http.Response, error) { + if f.srv.BeginUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginUpdate not implemented")} + } + beginUpdate := f.beginUpdate.get(req) + if beginUpdate == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DatabaseFleetManager/fleets/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/fleetspaces/(?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[armdatabasefleetmanager.Fleetspace](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + fleetNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("fleetName")]) + if err != nil { + return nil, err + } + fleetspaceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("fleetspaceName")]) + if err != nil { + return nil, err + } + respr, errRespr := f.srv.BeginUpdate(req.Context(), resourceGroupNameParam, fleetNameParam, fleetspaceNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginUpdate = &respr + f.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) { + f.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) { + f.beginUpdate.remove(req) + } + + return resp, nil +} + +// set this to conditionally intercept incoming requests to FleetspacesServerTransport +var fleetspacesServerTransportInterceptor 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/databasefleetmanager/armdatabasefleetmanager/fake/fleettiers_server.go b/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager/fake/fleettiers_server.go new file mode 100644 index 000000000000..10f00ff891dd --- /dev/null +++ b/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager/fake/fleettiers_server.go @@ -0,0 +1,439 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager" + "net/http" + "net/url" + "regexp" + "strconv" +) + +// FleetTiersServer is a fake server for instances of the armdatabasefleetmanager.FleetTiersClient type. +type FleetTiersServer struct { + // BeginCreateOrUpdate is the fake for method FleetTiersClient.BeginCreateOrUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + BeginCreateOrUpdate func(ctx context.Context, resourceGroupName string, fleetName string, tierName string, resource armdatabasefleetmanager.FleetTier, options *armdatabasefleetmanager.FleetTiersClientBeginCreateOrUpdateOptions) (resp azfake.PollerResponder[armdatabasefleetmanager.FleetTiersClientCreateOrUpdateResponse], errResp azfake.ErrorResponder) + + // BeginDelete is the fake for method FleetTiersClient.BeginDelete + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent + BeginDelete func(ctx context.Context, resourceGroupName string, fleetName string, tierName string, options *armdatabasefleetmanager.FleetTiersClientBeginDeleteOptions) (resp azfake.PollerResponder[armdatabasefleetmanager.FleetTiersClientDeleteResponse], errResp azfake.ErrorResponder) + + // Disable is the fake for method FleetTiersClient.Disable + // HTTP status codes to indicate success: http.StatusOK + Disable func(ctx context.Context, resourceGroupName string, fleetName string, tierName string, options *armdatabasefleetmanager.FleetTiersClientDisableOptions) (resp azfake.Responder[armdatabasefleetmanager.FleetTiersClientDisableResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method FleetTiersClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceGroupName string, fleetName string, tierName string, options *armdatabasefleetmanager.FleetTiersClientGetOptions) (resp azfake.Responder[armdatabasefleetmanager.FleetTiersClientGetResponse], errResp azfake.ErrorResponder) + + // NewListByFleetPager is the fake for method FleetTiersClient.NewListByFleetPager + // HTTP status codes to indicate success: http.StatusOK + NewListByFleetPager func(resourceGroupName string, fleetName string, options *armdatabasefleetmanager.FleetTiersClientListByFleetOptions) (resp azfake.PagerResponder[armdatabasefleetmanager.FleetTiersClientListByFleetResponse]) + + // BeginUpdate is the fake for method FleetTiersClient.BeginUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted + BeginUpdate func(ctx context.Context, resourceGroupName string, fleetName string, tierName string, properties armdatabasefleetmanager.FleetTier, options *armdatabasefleetmanager.FleetTiersClientBeginUpdateOptions) (resp azfake.PollerResponder[armdatabasefleetmanager.FleetTiersClientUpdateResponse], errResp azfake.ErrorResponder) +} + +// NewFleetTiersServerTransport creates a new instance of FleetTiersServerTransport with the provided implementation. +// The returned FleetTiersServerTransport instance is connected to an instance of armdatabasefleetmanager.FleetTiersClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewFleetTiersServerTransport(srv *FleetTiersServer) *FleetTiersServerTransport { + return &FleetTiersServerTransport{ + srv: srv, + beginCreateOrUpdate: newTracker[azfake.PollerResponder[armdatabasefleetmanager.FleetTiersClientCreateOrUpdateResponse]](), + beginDelete: newTracker[azfake.PollerResponder[armdatabasefleetmanager.FleetTiersClientDeleteResponse]](), + newListByFleetPager: newTracker[azfake.PagerResponder[armdatabasefleetmanager.FleetTiersClientListByFleetResponse]](), + beginUpdate: newTracker[azfake.PollerResponder[armdatabasefleetmanager.FleetTiersClientUpdateResponse]](), + } +} + +// FleetTiersServerTransport connects instances of armdatabasefleetmanager.FleetTiersClient to instances of FleetTiersServer. +// Don't use this type directly, use NewFleetTiersServerTransport instead. +type FleetTiersServerTransport struct { + srv *FleetTiersServer + beginCreateOrUpdate *tracker[azfake.PollerResponder[armdatabasefleetmanager.FleetTiersClientCreateOrUpdateResponse]] + beginDelete *tracker[azfake.PollerResponder[armdatabasefleetmanager.FleetTiersClientDeleteResponse]] + newListByFleetPager *tracker[azfake.PagerResponder[armdatabasefleetmanager.FleetTiersClientListByFleetResponse]] + beginUpdate *tracker[azfake.PollerResponder[armdatabasefleetmanager.FleetTiersClientUpdateResponse]] +} + +// Do implements the policy.Transporter interface for FleetTiersServerTransport. +func (f *FleetTiersServerTransport) 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 f.dispatchToMethodFake(req, method) +} + +func (f *FleetTiersServerTransport) 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 fleetTiersServerTransportInterceptor != nil { + res.resp, res.err, intercepted = fleetTiersServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "FleetTiersClient.BeginCreateOrUpdate": + res.resp, res.err = f.dispatchBeginCreateOrUpdate(req) + case "FleetTiersClient.BeginDelete": + res.resp, res.err = f.dispatchBeginDelete(req) + case "FleetTiersClient.Disable": + res.resp, res.err = f.dispatchDisable(req) + case "FleetTiersClient.Get": + res.resp, res.err = f.dispatchGet(req) + case "FleetTiersClient.NewListByFleetPager": + res.resp, res.err = f.dispatchNewListByFleetPager(req) + case "FleetTiersClient.BeginUpdate": + res.resp, res.err = f.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 (f *FleetTiersServerTransport) dispatchBeginCreateOrUpdate(req *http.Request) (*http.Response, error) { + if f.srv.BeginCreateOrUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginCreateOrUpdate not implemented")} + } + beginCreateOrUpdate := f.beginCreateOrUpdate.get(req) + if beginCreateOrUpdate == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DatabaseFleetManager/fleets/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/tiers/(?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[armdatabasefleetmanager.FleetTier](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + fleetNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("fleetName")]) + if err != nil { + return nil, err + } + tierNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("tierName")]) + if err != nil { + return nil, err + } + respr, errRespr := f.srv.BeginCreateOrUpdate(req.Context(), resourceGroupNameParam, fleetNameParam, tierNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginCreateOrUpdate = &respr + f.beginCreateOrUpdate.add(req, beginCreateOrUpdate) + } + + resp, err := server.PollerResponderNext(beginCreateOrUpdate, req) + if err != nil { + return nil, err + } + + if !contains([]int{http.StatusOK, http.StatusCreated}, resp.StatusCode) { + f.beginCreateOrUpdate.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", resp.StatusCode)} + } + if !server.PollerResponderMore(beginCreateOrUpdate) { + f.beginCreateOrUpdate.remove(req) + } + + return resp, nil +} + +func (f *FleetTiersServerTransport) dispatchBeginDelete(req *http.Request) (*http.Response, error) { + if f.srv.BeginDelete == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginDelete not implemented")} + } + beginDelete := f.beginDelete.get(req) + if beginDelete == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DatabaseFleetManager/fleets/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/tiers/(?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 + } + fleetNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("fleetName")]) + if err != nil { + return nil, err + } + tierNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("tierName")]) + if err != nil { + return nil, err + } + respr, errRespr := f.srv.BeginDelete(req.Context(), resourceGroupNameParam, fleetNameParam, tierNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginDelete = &respr + f.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) { + f.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) { + f.beginDelete.remove(req) + } + + return resp, nil +} + +func (f *FleetTiersServerTransport) dispatchDisable(req *http.Request) (*http.Response, error) { + if f.srv.Disable == nil { + return nil, &nonRetriableError{errors.New("fake for method Disable not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DatabaseFleetManager/fleets/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/tiers/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/disable` + 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 + } + fleetNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("fleetName")]) + if err != nil { + return nil, err + } + tierNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("tierName")]) + if err != nil { + return nil, err + } + respr, errRespr := f.srv.Disable(req.Context(), resourceGroupNameParam, fleetNameParam, tierNameParam, 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).FleetTier, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (f *FleetTiersServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if f.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\.DatabaseFleetManager/fleets/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/tiers/(?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 + } + fleetNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("fleetName")]) + if err != nil { + return nil, err + } + tierNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("tierName")]) + if err != nil { + return nil, err + } + respr, errRespr := f.srv.Get(req.Context(), resourceGroupNameParam, fleetNameParam, tierNameParam, 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).FleetTier, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (f *FleetTiersServerTransport) dispatchNewListByFleetPager(req *http.Request) (*http.Response, error) { + if f.srv.NewListByFleetPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListByFleetPager not implemented")} + } + newListByFleetPager := f.newListByFleetPager.get(req) + if newListByFleetPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DatabaseFleetManager/fleets/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/tiers` + 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 + } + fleetNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("fleetName")]) + if err != nil { + return nil, err + } + skipUnescaped, err := url.QueryUnescape(qp.Get("$skip")) + if err != nil { + return nil, err + } + skipParam, err := parseOptional(skipUnescaped, func(v string) (int64, error) { + p, parseErr := strconv.ParseInt(v, 10, 64) + if parseErr != nil { + return 0, parseErr + } + return p, nil + }) + if err != nil { + return nil, err + } + topUnescaped, err := url.QueryUnescape(qp.Get("$top")) + if err != nil { + return nil, err + } + topParam, err := parseOptional(topUnescaped, func(v string) (int64, error) { + p, parseErr := strconv.ParseInt(v, 10, 64) + if parseErr != nil { + return 0, parseErr + } + return p, nil + }) + if err != nil { + return nil, err + } + skiptokenUnescaped, err := url.QueryUnescape(qp.Get("$skiptoken")) + if err != nil { + return nil, err + } + skiptokenParam := getOptional(skiptokenUnescaped) + var options *armdatabasefleetmanager.FleetTiersClientListByFleetOptions + if skipParam != nil || topParam != nil || skiptokenParam != nil { + options = &armdatabasefleetmanager.FleetTiersClientListByFleetOptions{ + Skip: skipParam, + Top: topParam, + Skiptoken: skiptokenParam, + } + } + resp := f.srv.NewListByFleetPager(resourceGroupNameParam, fleetNameParam, options) + newListByFleetPager = &resp + f.newListByFleetPager.add(req, newListByFleetPager) + server.PagerResponderInjectNextLinks(newListByFleetPager, req, func(page *armdatabasefleetmanager.FleetTiersClientListByFleetResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListByFleetPager, req) + if err != nil { + return nil, err + } + if !contains([]int{http.StatusOK}, resp.StatusCode) { + f.newListByFleetPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListByFleetPager) { + f.newListByFleetPager.remove(req) + } + return resp, nil +} + +func (f *FleetTiersServerTransport) dispatchBeginUpdate(req *http.Request) (*http.Response, error) { + if f.srv.BeginUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginUpdate not implemented")} + } + beginUpdate := f.beginUpdate.get(req) + if beginUpdate == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DatabaseFleetManager/fleets/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/tiers/(?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[armdatabasefleetmanager.FleetTier](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + fleetNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("fleetName")]) + if err != nil { + return nil, err + } + tierNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("tierName")]) + if err != nil { + return nil, err + } + respr, errRespr := f.srv.BeginUpdate(req.Context(), resourceGroupNameParam, fleetNameParam, tierNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginUpdate = &respr + f.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) { + f.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) { + f.beginUpdate.remove(req) + } + + return resp, nil +} + +// set this to conditionally intercept incoming requests to FleetTiersServerTransport +var fleetTiersServerTransportInterceptor 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/databasefleetmanager/armdatabasefleetmanager/fake/internal.go b/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager/fake/internal.go new file mode 100644 index 000000000000..41e62ec29233 --- /dev/null +++ b/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager/fake/internal.go @@ -0,0 +1,84 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "net/http" + "reflect" + "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 getOptional[T any](v T) *T { + if reflect.ValueOf(v).IsZero() { + return nil + } + return &v +} + +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/databasefleetmanager/armdatabasefleetmanager/fake/operations_server.go b/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager/fake/operations_server.go new file mode 100644 index 000000000000..d65ceda6770b --- /dev/null +++ b/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager/fake/operations_server.go @@ -0,0 +1,117 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager" + "net/http" +) + +// OperationsServer is a fake server for instances of the armdatabasefleetmanager.OperationsClient type. +type OperationsServer struct { + // NewListPager is the fake for method OperationsClient.NewListPager + // HTTP status codes to indicate success: http.StatusOK + NewListPager func(options *armdatabasefleetmanager.OperationsClientListOptions) (resp azfake.PagerResponder[armdatabasefleetmanager.OperationsClientListResponse]) +} + +// NewOperationsServerTransport creates a new instance of OperationsServerTransport with the provided implementation. +// The returned OperationsServerTransport instance is connected to an instance of armdatabasefleetmanager.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[armdatabasefleetmanager.OperationsClientListResponse]](), + } +} + +// OperationsServerTransport connects instances of armdatabasefleetmanager.OperationsClient to instances of OperationsServer. +// Don't use this type directly, use NewOperationsServerTransport instead. +type OperationsServerTransport struct { + srv *OperationsServer + newListPager *tracker[azfake.PagerResponder[armdatabasefleetmanager.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 *armdatabasefleetmanager.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/databasefleetmanager/armdatabasefleetmanager/fake/server_factory.go b/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager/fake/server_factory.go new file mode 100644 index 000000000000..ba9a95b5f73f --- /dev/null +++ b/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager/fake/server_factory.go @@ -0,0 +1,111 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "errors" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" + "sync" +) + +// ServerFactory is a fake server for instances of the armdatabasefleetmanager.ClientFactory type. +type ServerFactory struct { + // FirewallRulesServer contains the fakes for client FirewallRulesClient + FirewallRulesServer FirewallRulesServer + + // FleetDatabasesServer contains the fakes for client FleetDatabasesClient + FleetDatabasesServer FleetDatabasesServer + + // FleetTiersServer contains the fakes for client FleetTiersClient + FleetTiersServer FleetTiersServer + + // FleetsServer contains the fakes for client FleetsClient + FleetsServer FleetsServer + + // FleetspacesServer contains the fakes for client FleetspacesClient + FleetspacesServer FleetspacesServer + + // OperationsServer contains the fakes for client OperationsClient + OperationsServer OperationsServer +} + +// NewServerFactoryTransport creates a new instance of ServerFactoryTransport with the provided implementation. +// The returned ServerFactoryTransport instance is connected to an instance of armdatabasefleetmanager.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 armdatabasefleetmanager.ClientFactory to instances of ServerFactory. +// Don't use this type directly, use NewServerFactoryTransport instead. +type ServerFactoryTransport struct { + srv *ServerFactory + trMu sync.Mutex + trFirewallRulesServer *FirewallRulesServerTransport + trFleetDatabasesServer *FleetDatabasesServerTransport + trFleetTiersServer *FleetTiersServerTransport + trFleetsServer *FleetsServerTransport + trFleetspacesServer *FleetspacesServerTransport + trOperationsServer *OperationsServerTransport +} + +// 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 "FirewallRulesClient": + initServer(s, &s.trFirewallRulesServer, func() *FirewallRulesServerTransport { + return NewFirewallRulesServerTransport(&s.srv.FirewallRulesServer) + }) + resp, err = s.trFirewallRulesServer.Do(req) + case "FleetDatabasesClient": + initServer(s, &s.trFleetDatabasesServer, func() *FleetDatabasesServerTransport { + return NewFleetDatabasesServerTransport(&s.srv.FleetDatabasesServer) + }) + resp, err = s.trFleetDatabasesServer.Do(req) + case "FleetTiersClient": + initServer(s, &s.trFleetTiersServer, func() *FleetTiersServerTransport { return NewFleetTiersServerTransport(&s.srv.FleetTiersServer) }) + resp, err = s.trFleetTiersServer.Do(req) + case "FleetsClient": + initServer(s, &s.trFleetsServer, func() *FleetsServerTransport { return NewFleetsServerTransport(&s.srv.FleetsServer) }) + resp, err = s.trFleetsServer.Do(req) + case "FleetspacesClient": + initServer(s, &s.trFleetspacesServer, func() *FleetspacesServerTransport { return NewFleetspacesServerTransport(&s.srv.FleetspacesServer) }) + resp, err = s.trFleetspacesServer.Do(req) + case "OperationsClient": + initServer(s, &s.trOperationsServer, func() *OperationsServerTransport { return NewOperationsServerTransport(&s.srv.OperationsServer) }) + resp, err = s.trOperationsServer.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/databasefleetmanager/armdatabasefleetmanager/fake/time_rfc3339.go b/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager/fake/time_rfc3339.go new file mode 100644 index 000000000000..87ee11e83b32 --- /dev/null +++ b/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager/fake/time_rfc3339.go @@ -0,0 +1,109 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "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 +} diff --git a/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager/firewallrules_client.go b/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager/firewallrules_client.go new file mode 100644 index 000000000000..503cc3a93ac9 --- /dev/null +++ b/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager/firewallrules_client.go @@ -0,0 +1,371 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armdatabasefleetmanager + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strconv" + "strings" +) + +// FirewallRulesClient contains the methods for the FirewallRules group. +// Don't use this type directly, use NewFirewallRulesClient() instead. +type FirewallRulesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewFirewallRulesClient creates a new instance of FirewallRulesClient 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 NewFirewallRulesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*FirewallRulesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &FirewallRulesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Creates or updates a firewall rule. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2025-02-01-preview +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - fleetName - Name of the database fleet. +// - fleetspaceName - Name of the fleetspace. +// - firewallRuleName - Name of the firewall rule. +// - resource - The firewall rule object to create or update. +// - options - FirewallRulesClientBeginCreateOrUpdateOptions contains the optional parameters for the FirewallRulesClient.BeginCreateOrUpdate +// method. +func (client *FirewallRulesClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, fleetName string, fleetspaceName string, firewallRuleName string, resource FirewallRule, options *FirewallRulesClientBeginCreateOrUpdateOptions) (*runtime.Poller[FirewallRulesClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, fleetName, fleetspaceName, firewallRuleName, resource, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[FirewallRulesClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[FirewallRulesClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Creates or updates a firewall rule. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2025-02-01-preview +func (client *FirewallRulesClient) createOrUpdate(ctx context.Context, resourceGroupName string, fleetName string, fleetspaceName string, firewallRuleName string, resource FirewallRule, options *FirewallRulesClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "FirewallRulesClient.BeginCreateOrUpdate" + 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, fleetName, fleetspaceName, firewallRuleName, 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 +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *FirewallRulesClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, fleetName string, fleetspaceName string, firewallRuleName string, resource FirewallRule, _ *FirewallRulesClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DatabaseFleetManager/fleets/{fleetName}/fleetspaces/{fleetspaceName}/firewallRules/{firewallRuleName}" + 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 fleetName == "" { + return nil, errors.New("parameter fleetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{fleetName}", url.PathEscape(fleetName)) + if fleetspaceName == "" { + return nil, errors.New("parameter fleetspaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{fleetspaceName}", url.PathEscape(fleetspaceName)) + if firewallRuleName == "" { + return nil, errors.New("parameter firewallRuleName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{firewallRuleName}", url.PathEscape(firewallRuleName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2025-02-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, resource); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Deletes a firewall rule. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2025-02-01-preview +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - fleetName - Name of the database fleet. +// - fleetspaceName - Name of the fleetspace. +// - firewallRuleName - Name of the firewall rule. +// - options - FirewallRulesClientBeginDeleteOptions contains the optional parameters for the FirewallRulesClient.BeginDelete +// method. +func (client *FirewallRulesClient) BeginDelete(ctx context.Context, resourceGroupName string, fleetName string, fleetspaceName string, firewallRuleName string, options *FirewallRulesClientBeginDeleteOptions) (*runtime.Poller[FirewallRulesClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, fleetName, fleetspaceName, firewallRuleName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[FirewallRulesClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[FirewallRulesClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes a firewall rule. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2025-02-01-preview +func (client *FirewallRulesClient) deleteOperation(ctx context.Context, resourceGroupName string, fleetName string, fleetspaceName string, firewallRuleName string, options *FirewallRulesClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "FirewallRulesClient.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, fleetName, fleetspaceName, firewallRuleName, 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 *FirewallRulesClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, fleetName string, fleetspaceName string, firewallRuleName string, _ *FirewallRulesClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DatabaseFleetManager/fleets/{fleetName}/fleetspaces/{fleetspaceName}/firewallRules/{firewallRuleName}" + 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 fleetName == "" { + return nil, errors.New("parameter fleetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{fleetName}", url.PathEscape(fleetName)) + if fleetspaceName == "" { + return nil, errors.New("parameter fleetspaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{fleetspaceName}", url.PathEscape(fleetspaceName)) + if firewallRuleName == "" { + return nil, errors.New("parameter firewallRuleName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{firewallRuleName}", url.PathEscape(firewallRuleName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2025-02-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Gets a firewall rule. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2025-02-01-preview +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - fleetName - Name of the database fleet. +// - fleetspaceName - Name of the fleetspace. +// - firewallRuleName - Name of the firewall rule. +// - options - FirewallRulesClientGetOptions contains the optional parameters for the FirewallRulesClient.Get method. +func (client *FirewallRulesClient) Get(ctx context.Context, resourceGroupName string, fleetName string, fleetspaceName string, firewallRuleName string, options *FirewallRulesClientGetOptions) (FirewallRulesClientGetResponse, error) { + var err error + const operationName = "FirewallRulesClient.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, fleetName, fleetspaceName, firewallRuleName, options) + if err != nil { + return FirewallRulesClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return FirewallRulesClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return FirewallRulesClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *FirewallRulesClient) getCreateRequest(ctx context.Context, resourceGroupName string, fleetName string, fleetspaceName string, firewallRuleName string, _ *FirewallRulesClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DatabaseFleetManager/fleets/{fleetName}/fleetspaces/{fleetspaceName}/firewallRules/{firewallRuleName}" + 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 fleetName == "" { + return nil, errors.New("parameter fleetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{fleetName}", url.PathEscape(fleetName)) + if fleetspaceName == "" { + return nil, errors.New("parameter fleetspaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{fleetspaceName}", url.PathEscape(fleetspaceName)) + if firewallRuleName == "" { + return nil, errors.New("parameter firewallRuleName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{firewallRuleName}", url.PathEscape(firewallRuleName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2025-02-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 *FirewallRulesClient) getHandleResponse(resp *http.Response) (FirewallRulesClientGetResponse, error) { + result := FirewallRulesClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.FirewallRule); err != nil { + return FirewallRulesClientGetResponse{}, err + } + return result, nil +} + +// NewListByFleetspacePager - Gets all firewall rules in a fleetspace. +// +// Generated from API version 2025-02-01-preview +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - fleetName - Name of the database fleet. +// - fleetspaceName - Name of the fleetspace. +// - options - FirewallRulesClientListByFleetspaceOptions contains the optional parameters for the FirewallRulesClient.NewListByFleetspacePager +// method. +func (client *FirewallRulesClient) NewListByFleetspacePager(resourceGroupName string, fleetName string, fleetspaceName string, options *FirewallRulesClientListByFleetspaceOptions) *runtime.Pager[FirewallRulesClientListByFleetspaceResponse] { + return runtime.NewPager(runtime.PagingHandler[FirewallRulesClientListByFleetspaceResponse]{ + More: func(page FirewallRulesClientListByFleetspaceResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *FirewallRulesClientListByFleetspaceResponse) (FirewallRulesClientListByFleetspaceResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "FirewallRulesClient.NewListByFleetspacePager") + 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.listByFleetspaceCreateRequest(ctx, resourceGroupName, fleetName, fleetspaceName, options) + }, nil) + if err != nil { + return FirewallRulesClientListByFleetspaceResponse{}, err + } + return client.listByFleetspaceHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByFleetspaceCreateRequest creates the ListByFleetspace request. +func (client *FirewallRulesClient) listByFleetspaceCreateRequest(ctx context.Context, resourceGroupName string, fleetName string, fleetspaceName string, options *FirewallRulesClientListByFleetspaceOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DatabaseFleetManager/fleets/{fleetName}/fleetspaces/{fleetspaceName}/firewallRules" + 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 fleetName == "" { + return nil, errors.New("parameter fleetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{fleetName}", url.PathEscape(fleetName)) + if fleetspaceName == "" { + return nil, errors.New("parameter fleetspaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{fleetspaceName}", url.PathEscape(fleetspaceName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Skip != nil { + reqQP.Set("$skip", strconv.FormatInt(*options.Skip, 10)) + } + if options != nil && options.Skiptoken != nil { + reqQP.Set("$skiptoken", *options.Skiptoken) + } + if options != nil && options.Top != nil { + reqQP.Set("$top", strconv.FormatInt(*options.Top, 10)) + } + reqQP.Set("api-version", "2025-02-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByFleetspaceHandleResponse handles the ListByFleetspace response. +func (client *FirewallRulesClient) listByFleetspaceHandleResponse(resp *http.Response) (FirewallRulesClientListByFleetspaceResponse, error) { + result := FirewallRulesClientListByFleetspaceResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.FirewallRuleListResult); err != nil { + return FirewallRulesClientListByFleetspaceResponse{}, err + } + return result, nil +} diff --git a/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager/firewallrules_client_example_test.go b/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager/firewallrules_client_example_test.go new file mode 100644 index 000000000000..9389a0452127 --- /dev/null +++ b/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager/firewallrules_client_example_test.go @@ -0,0 +1,176 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armdatabasefleetmanager_test + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/Azure/azure-sdk-for-go/sdk/azidentity" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager" + "log" +) + +// Generated from example definition: 2025-02-01-preview/FirewallRules_CreateOrUpdate_MaximumSet_Gen.json +func ExampleFirewallRulesClient_BeginCreateOrUpdate() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armdatabasefleetmanager.NewClientFactory("a2b3c4d5-6789-0123-4567-89abcdef1234", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + poller, err := clientFactory.NewFirewallRulesClient().BeginCreateOrUpdate(ctx, "rg-networking-operations", "data-fleet-01", "prod-environment", "allow-10-0-0-0-24-to-10-1-0-0-24", armdatabasefleetmanager.FirewallRule{ + Properties: &armdatabasefleetmanager.FirewallRuleProperties{ + StartIPAddress: to.Ptr("10.0.0.0"), + EndIPAddress: to.Ptr("10.0.0.255"), + }, + }, nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + res, err := poller.PollUntilDone(ctx, nil) + if err != nil { + log.Fatalf("failed to pull the result: %v", err) + } + // You could use response here. We use blank identifier for just demo purposes. + _ = res + // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // res = armdatabasefleetmanager.FirewallRulesClientCreateOrUpdateResponse{ + // FirewallRule: &armdatabasefleetmanager.FirewallRule{ + // Properties: &armdatabasefleetmanager.FirewallRuleProperties{ + // StartIPAddress: to.Ptr("10.0.0.0"), + // EndIPAddress: to.Ptr("10.0.0.255"), + // ProvisioningState: to.Ptr(armdatabasefleetmanager.AzureProvisioningStateSucceeded), + // }, + // ID: to.Ptr("/subscriptions/a2b3c4d5-6789-0123-4567-89abcdef1234/resourceGroups/rg-networking-operations/providers/Microsoft.DatabaseFleetManager/fleets/data-fleet-01/fleetspaces/prod-environment/firewallRules/allow-10-0-0-0-24-to-10-1-0-0-24"), + // Name: to.Ptr("allow-10-0-0-0-24-to-10-1-0-0-24"), + // Type: to.Ptr("Microsoft.DatabaseFleetManager/firewallRules"), + // SystemData: &armdatabasefleetmanager.SystemData{ + // CreatedBy: to.Ptr("admin.jdoe"), + // CreatedByType: to.Ptr(armdatabasefleetmanager.CreatedByTypeUser), + // CreatedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2024-12-01T14:30:45.123Z"); return t}()), + // LastModifiedBy: to.Ptr("admin.jdoe"), + // LastModifiedByType: to.Ptr(armdatabasefleetmanager.CreatedByTypeUser), + // LastModifiedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2024-12-01T14:30:45.124Z"); return t}()), + // }, + // }, + // } +} + +// Generated from example definition: 2025-02-01-preview/FirewallRules_Delete_MaximumSet_Gen.json +func ExampleFirewallRulesClient_BeginDelete() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armdatabasefleetmanager.NewClientFactory("a2b3c4d5-6789-0123-4567-89abcdef1234", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + poller, err := clientFactory.NewFirewallRulesClient().BeginDelete(ctx, "rg-networking-operations", "data-fleet-01", "prod-environment", "allow-10-0-0-0-24-to-10-1-0-0-24", nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + _, err = poller.PollUntilDone(ctx, nil) + if err != nil { + log.Fatalf("failed to pull the result: %v", err) + } +} + +// Generated from example definition: 2025-02-01-preview/FirewallRules_Get_MaximumSet_Gen.json +func ExampleFirewallRulesClient_Get() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armdatabasefleetmanager.NewClientFactory("a2b3c4d5-6789-0123-4567-89abcdef1234", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + res, err := clientFactory.NewFirewallRulesClient().Get(ctx, "rg-networking-operations", "data-fleet-01", "prod-environment", "allow-10-0-0-0-24-to-10-1-0-0-24", nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + // You could use response here. We use blank identifier for just demo purposes. + _ = res + // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // res = armdatabasefleetmanager.FirewallRulesClientGetResponse{ + // FirewallRule: &armdatabasefleetmanager.FirewallRule{ + // Properties: &armdatabasefleetmanager.FirewallRuleProperties{ + // StartIPAddress: to.Ptr("10.0.0.0"), + // EndIPAddress: to.Ptr("10.0.0.255"), + // ProvisioningState: to.Ptr(armdatabasefleetmanager.AzureProvisioningStateSucceeded), + // }, + // ID: to.Ptr("/subscriptions/a2b3c4d5-6789-0123-4567-89abcdef1234/resourceGroups/rg-networking-operations/providers/Microsoft.DatabaseFleetManager/fleets/data-fleet-01/fleetspaces/prod-environment/firewallRules/allow-10-0-0-0-24-to-10-1-0-0-24"), + // Name: to.Ptr("allow-10-0-0-0-24-to-10-1-0-0-24"), + // Type: to.Ptr("Microsoft.DatabaseFleetManager/fleets/fleetspaces/firewallRules"), + // SystemData: &armdatabasefleetmanager.SystemData{ + // CreatedBy: to.Ptr("admin.jdoe"), + // CreatedByType: to.Ptr(armdatabasefleetmanager.CreatedByTypeUser), + // CreatedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2024-12-01T14:30:45.123Z"); return t}()), + // LastModifiedBy: to.Ptr("admin.jdoe"), + // LastModifiedByType: to.Ptr(armdatabasefleetmanager.CreatedByTypeUser), + // LastModifiedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2024-12-01T14:30:45.124Z"); return t}()), + // }, + // }, + // } +} + +// Generated from example definition: 2025-02-01-preview/FirewallRules_ListByFleetspace_MaximumSet_Gen.json +func ExampleFirewallRulesClient_NewListByFleetspacePager() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armdatabasefleetmanager.NewClientFactory("a2b3c4d5-6789-0123-4567-89abcdef1234", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + pager := clientFactory.NewFirewallRulesClient().NewListByFleetspacePager("rg-networking-operations", "data-fleet-01", "prod-environment", &FirewallRulesClientListByFleetspaceOptions{ + Skip: to.Ptr[int64](8), + Top: to.Ptr[int64](18), + Skiptoken: to.Ptr("thjchalxuwykrawwdgaie")}) + for pager.More() { + page, err := pager.NextPage(ctx) + if err != nil { + log.Fatalf("failed to advance page: %v", err) + } + for _, v := range page.Value { + // You could use page here. We use blank identifier for just demo purposes. + _ = v + } + // If the HTTP response code is 200 as defined in example definition, your page structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // page = armdatabasefleetmanager.FirewallRulesClientListByFleetspaceResponse{ + // FirewallRuleListResult: armdatabasefleetmanager.FirewallRuleListResult{ + // Value: []*armdatabasefleetmanager.FirewallRule{ + // { + // Properties: &armdatabasefleetmanager.FirewallRuleProperties{ + // StartIPAddress: to.Ptr("10.0.0.0"), + // EndIPAddress: to.Ptr("10.0.0.255"), + // ProvisioningState: to.Ptr(armdatabasefleetmanager.AzureProvisioningStateSucceeded), + // }, + // ID: to.Ptr("/subscriptions/a2b3c4d5-6789-0123-4567-89abcdef1234/resourceGroups/rg-networking-operations/providers/Microsoft.DatabaseFleetManager/fleets/data-fleet-01/fleetspaces/prod-environment/firewallRules/allow-10-0-0-0-24-to-10-1-0-0-24"), + // Name: to.Ptr("allow-10-0-0-0-24-to-10-1-0-0-24"), + // Type: to.Ptr("Microsoft.DatabaseFleetManager/fleets/fleetspaces/firewallRules"), + // SystemData: &armdatabasefleetmanager.SystemData{ + // CreatedBy: to.Ptr("admin.jdoe"), + // CreatedByType: to.Ptr(armdatabasefleetmanager.CreatedByTypeUser), + // CreatedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2024-12-01T14:30:45.123Z"); return t}()), + // LastModifiedBy: to.Ptr("admin.jdoe"), + // LastModifiedByType: to.Ptr(armdatabasefleetmanager.CreatedByTypeUser), + // LastModifiedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2024-12-01T14:30:45.124Z"); return t}()), + // }, + // }, + // }, + // NextLink: to.Ptr("https://microsoft.com/a"), + // }, + // } + } +} diff --git a/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager/fleetdatabases_client.go b/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager/fleetdatabases_client.go new file mode 100644 index 000000000000..d62796a17149 --- /dev/null +++ b/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager/fleetdatabases_client.go @@ -0,0 +1,733 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armdatabasefleetmanager + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strconv" + "strings" +) + +// FleetDatabasesClient contains the methods for the FleetDatabases group. +// Don't use this type directly, use NewFleetDatabasesClient() instead. +type FleetDatabasesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewFleetDatabasesClient creates a new instance of FleetDatabasesClient 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 NewFleetDatabasesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*FleetDatabasesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &FleetDatabasesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginChangeTier - Moves database to a different tier. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2025-02-01-preview +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - fleetName - Name of the database fleet. +// - fleetspaceName - Name of the fleetspace. +// - databaseName - Name of the database. +// - body - The details of the change tier operation. +// - options - FleetDatabasesClientBeginChangeTierOptions contains the optional parameters for the FleetDatabasesClient.BeginChangeTier +// method. +func (client *FleetDatabasesClient) BeginChangeTier(ctx context.Context, resourceGroupName string, fleetName string, fleetspaceName string, databaseName string, body DatabaseChangeTierProperties, options *FleetDatabasesClientBeginChangeTierOptions) (*runtime.Poller[FleetDatabasesClientChangeTierResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.changeTier(ctx, resourceGroupName, fleetName, fleetspaceName, databaseName, body, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[FleetDatabasesClientChangeTierResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[FleetDatabasesClientChangeTierResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// ChangeTier - Moves database to a different tier. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2025-02-01-preview +func (client *FleetDatabasesClient) changeTier(ctx context.Context, resourceGroupName string, fleetName string, fleetspaceName string, databaseName string, body DatabaseChangeTierProperties, options *FleetDatabasesClientBeginChangeTierOptions) (*http.Response, error) { + var err error + const operationName = "FleetDatabasesClient.BeginChangeTier" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.changeTierCreateRequest(ctx, resourceGroupName, fleetName, fleetspaceName, databaseName, body, 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) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// changeTierCreateRequest creates the ChangeTier request. +func (client *FleetDatabasesClient) changeTierCreateRequest(ctx context.Context, resourceGroupName string, fleetName string, fleetspaceName string, databaseName string, body DatabaseChangeTierProperties, _ *FleetDatabasesClientBeginChangeTierOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DatabaseFleetManager/fleets/{fleetName}/fleetspaces/{fleetspaceName}/databases/{databaseName}/changeTier" + 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 fleetName == "" { + return nil, errors.New("parameter fleetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{fleetName}", url.PathEscape(fleetName)) + if fleetspaceName == "" { + return nil, errors.New("parameter fleetspaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{fleetspaceName}", url.PathEscape(fleetspaceName)) + if databaseName == "" { + return nil, errors.New("parameter databaseName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{databaseName}", url.PathEscape(databaseName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2025-02-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// BeginCreateOrUpdate - Creates or updates a fleet database. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2025-02-01-preview +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - fleetName - Name of the database fleet. +// - fleetspaceName - Name of the fleetspace. +// - databaseName - Name of the database. +// - resource - The database object to create or update. +// - options - FleetDatabasesClientBeginCreateOrUpdateOptions contains the optional parameters for the FleetDatabasesClient.BeginCreateOrUpdate +// method. +func (client *FleetDatabasesClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, fleetName string, fleetspaceName string, databaseName string, resource FleetDatabase, options *FleetDatabasesClientBeginCreateOrUpdateOptions) (*runtime.Poller[FleetDatabasesClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, fleetName, fleetspaceName, databaseName, resource, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[FleetDatabasesClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[FleetDatabasesClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Creates or updates a fleet database. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2025-02-01-preview +func (client *FleetDatabasesClient) createOrUpdate(ctx context.Context, resourceGroupName string, fleetName string, fleetspaceName string, databaseName string, resource FleetDatabase, options *FleetDatabasesClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "FleetDatabasesClient.BeginCreateOrUpdate" + 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, fleetName, fleetspaceName, databaseName, 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 +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *FleetDatabasesClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, fleetName string, fleetspaceName string, databaseName string, resource FleetDatabase, _ *FleetDatabasesClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DatabaseFleetManager/fleets/{fleetName}/fleetspaces/{fleetspaceName}/databases/{databaseName}" + 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 fleetName == "" { + return nil, errors.New("parameter fleetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{fleetName}", url.PathEscape(fleetName)) + if fleetspaceName == "" { + return nil, errors.New("parameter fleetspaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{fleetspaceName}", url.PathEscape(fleetspaceName)) + if databaseName == "" { + return nil, errors.New("parameter databaseName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{databaseName}", url.PathEscape(databaseName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2025-02-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, resource); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Deletes a fleet database. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2025-02-01-preview +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - fleetName - Name of the database fleet. +// - fleetspaceName - Name of the fleetspace. +// - databaseName - Name of the database. +// - options - FleetDatabasesClientBeginDeleteOptions contains the optional parameters for the FleetDatabasesClient.BeginDelete +// method. +func (client *FleetDatabasesClient) BeginDelete(ctx context.Context, resourceGroupName string, fleetName string, fleetspaceName string, databaseName string, options *FleetDatabasesClientBeginDeleteOptions) (*runtime.Poller[FleetDatabasesClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, fleetName, fleetspaceName, databaseName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[FleetDatabasesClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[FleetDatabasesClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes a fleet database. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2025-02-01-preview +func (client *FleetDatabasesClient) deleteOperation(ctx context.Context, resourceGroupName string, fleetName string, fleetspaceName string, databaseName string, options *FleetDatabasesClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "FleetDatabasesClient.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, fleetName, fleetspaceName, databaseName, 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 *FleetDatabasesClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, fleetName string, fleetspaceName string, databaseName string, _ *FleetDatabasesClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DatabaseFleetManager/fleets/{fleetName}/fleetspaces/{fleetspaceName}/databases/{databaseName}" + 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 fleetName == "" { + return nil, errors.New("parameter fleetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{fleetName}", url.PathEscape(fleetName)) + if fleetspaceName == "" { + return nil, errors.New("parameter fleetspaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{fleetspaceName}", url.PathEscape(fleetspaceName)) + if databaseName == "" { + return nil, errors.New("parameter databaseName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{databaseName}", url.PathEscape(databaseName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2025-02-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Gets a fleet database. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2025-02-01-preview +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - fleetName - Name of the database fleet. +// - fleetspaceName - Name of the fleetspace. +// - databaseName - Name of the database. +// - options - FleetDatabasesClientGetOptions contains the optional parameters for the FleetDatabasesClient.Get method. +func (client *FleetDatabasesClient) Get(ctx context.Context, resourceGroupName string, fleetName string, fleetspaceName string, databaseName string, options *FleetDatabasesClientGetOptions) (FleetDatabasesClientGetResponse, error) { + var err error + const operationName = "FleetDatabasesClient.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, fleetName, fleetspaceName, databaseName, options) + if err != nil { + return FleetDatabasesClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return FleetDatabasesClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return FleetDatabasesClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *FleetDatabasesClient) getCreateRequest(ctx context.Context, resourceGroupName string, fleetName string, fleetspaceName string, databaseName string, _ *FleetDatabasesClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DatabaseFleetManager/fleets/{fleetName}/fleetspaces/{fleetspaceName}/databases/{databaseName}" + 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 fleetName == "" { + return nil, errors.New("parameter fleetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{fleetName}", url.PathEscape(fleetName)) + if fleetspaceName == "" { + return nil, errors.New("parameter fleetspaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{fleetspaceName}", url.PathEscape(fleetspaceName)) + if databaseName == "" { + return nil, errors.New("parameter databaseName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{databaseName}", url.PathEscape(databaseName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2025-02-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 *FleetDatabasesClient) getHandleResponse(resp *http.Response) (FleetDatabasesClientGetResponse, error) { + result := FleetDatabasesClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.FleetDatabase); err != nil { + return FleetDatabasesClientGetResponse{}, err + } + return result, nil +} + +// NewListByFleetspacePager - Gets all fleet databases in a fleetspace. +// +// Generated from API version 2025-02-01-preview +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - fleetName - Name of the database fleet. +// - fleetspaceName - Name of the fleetspace. +// - options - FleetDatabasesClientListByFleetspaceOptions contains the optional parameters for the FleetDatabasesClient.NewListByFleetspacePager +// method. +func (client *FleetDatabasesClient) NewListByFleetspacePager(resourceGroupName string, fleetName string, fleetspaceName string, options *FleetDatabasesClientListByFleetspaceOptions) *runtime.Pager[FleetDatabasesClientListByFleetspaceResponse] { + return runtime.NewPager(runtime.PagingHandler[FleetDatabasesClientListByFleetspaceResponse]{ + More: func(page FleetDatabasesClientListByFleetspaceResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *FleetDatabasesClientListByFleetspaceResponse) (FleetDatabasesClientListByFleetspaceResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "FleetDatabasesClient.NewListByFleetspacePager") + 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.listByFleetspaceCreateRequest(ctx, resourceGroupName, fleetName, fleetspaceName, options) + }, nil) + if err != nil { + return FleetDatabasesClientListByFleetspaceResponse{}, err + } + return client.listByFleetspaceHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByFleetspaceCreateRequest creates the ListByFleetspace request. +func (client *FleetDatabasesClient) listByFleetspaceCreateRequest(ctx context.Context, resourceGroupName string, fleetName string, fleetspaceName string, options *FleetDatabasesClientListByFleetspaceOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DatabaseFleetManager/fleets/{fleetName}/fleetspaces/{fleetspaceName}/databases" + 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 fleetName == "" { + return nil, errors.New("parameter fleetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{fleetName}", url.PathEscape(fleetName)) + if fleetspaceName == "" { + return nil, errors.New("parameter fleetspaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{fleetspaceName}", url.PathEscape(fleetspaceName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Filter != nil { + reqQP.Set("$filter", *options.Filter) + } + if options != nil && options.Skip != nil { + reqQP.Set("$skip", strconv.FormatInt(*options.Skip, 10)) + } + if options != nil && options.Skiptoken != nil { + reqQP.Set("$skiptoken", *options.Skiptoken) + } + if options != nil && options.Top != nil { + reqQP.Set("$top", strconv.FormatInt(*options.Top, 10)) + } + reqQP.Set("api-version", "2025-02-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByFleetspaceHandleResponse handles the ListByFleetspace response. +func (client *FleetDatabasesClient) listByFleetspaceHandleResponse(resp *http.Response) (FleetDatabasesClientListByFleetspaceResponse, error) { + result := FleetDatabasesClientListByFleetspaceResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.FleetDatabaseListResult); err != nil { + return FleetDatabasesClientListByFleetspaceResponse{}, err + } + return result, nil +} + +// BeginRename - Renames a database. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2025-02-01-preview +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - fleetName - Name of the database fleet. +// - fleetspaceName - Name of the fleetspace. +// - databaseName - Name of the database. +// - body - The details of the rename operation. +// - options - FleetDatabasesClientBeginRenameOptions contains the optional parameters for the FleetDatabasesClient.BeginRename +// method. +func (client *FleetDatabasesClient) BeginRename(ctx context.Context, resourceGroupName string, fleetName string, fleetspaceName string, databaseName string, body DatabaseRenameProperties, options *FleetDatabasesClientBeginRenameOptions) (*runtime.Poller[FleetDatabasesClientRenameResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.rename(ctx, resourceGroupName, fleetName, fleetspaceName, databaseName, body, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[FleetDatabasesClientRenameResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[FleetDatabasesClientRenameResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Rename - Renames a database. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2025-02-01-preview +func (client *FleetDatabasesClient) rename(ctx context.Context, resourceGroupName string, fleetName string, fleetspaceName string, databaseName string, body DatabaseRenameProperties, options *FleetDatabasesClientBeginRenameOptions) (*http.Response, error) { + var err error + const operationName = "FleetDatabasesClient.BeginRename" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.renameCreateRequest(ctx, resourceGroupName, fleetName, fleetspaceName, databaseName, body, 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) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// renameCreateRequest creates the Rename request. +func (client *FleetDatabasesClient) renameCreateRequest(ctx context.Context, resourceGroupName string, fleetName string, fleetspaceName string, databaseName string, body DatabaseRenameProperties, _ *FleetDatabasesClientBeginRenameOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DatabaseFleetManager/fleets/{fleetName}/fleetspaces/{fleetspaceName}/databases/{databaseName}/rename" + 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 fleetName == "" { + return nil, errors.New("parameter fleetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{fleetName}", url.PathEscape(fleetName)) + if fleetspaceName == "" { + return nil, errors.New("parameter fleetspaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{fleetspaceName}", url.PathEscape(fleetspaceName)) + if databaseName == "" { + return nil, errors.New("parameter databaseName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{databaseName}", url.PathEscape(databaseName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2025-02-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// BeginRevert - Revert a database transparent data encryption (TDE). +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2025-02-01-preview +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - fleetName - Name of the database fleet. +// - fleetspaceName - Name of the fleetspace. +// - databaseName - Name of the database. +// - options - FleetDatabasesClientBeginRevertOptions contains the optional parameters for the FleetDatabasesClient.BeginRevert +// method. +func (client *FleetDatabasesClient) BeginRevert(ctx context.Context, resourceGroupName string, fleetName string, fleetspaceName string, databaseName string, options *FleetDatabasesClientBeginRevertOptions) (*runtime.Poller[FleetDatabasesClientRevertResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.revert(ctx, resourceGroupName, fleetName, fleetspaceName, databaseName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[FleetDatabasesClientRevertResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[FleetDatabasesClientRevertResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Revert - Revert a database transparent data encryption (TDE). +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2025-02-01-preview +func (client *FleetDatabasesClient) revert(ctx context.Context, resourceGroupName string, fleetName string, fleetspaceName string, databaseName string, options *FleetDatabasesClientBeginRevertOptions) (*http.Response, error) { + var err error + const operationName = "FleetDatabasesClient.BeginRevert" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.revertCreateRequest(ctx, resourceGroupName, fleetName, fleetspaceName, databaseName, 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) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// revertCreateRequest creates the Revert request. +func (client *FleetDatabasesClient) revertCreateRequest(ctx context.Context, resourceGroupName string, fleetName string, fleetspaceName string, databaseName string, _ *FleetDatabasesClientBeginRevertOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DatabaseFleetManager/fleets/{fleetName}/fleetspaces/{fleetspaceName}/databases/{databaseName}/revert" + 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 fleetName == "" { + return nil, errors.New("parameter fleetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{fleetName}", url.PathEscape(fleetName)) + if fleetspaceName == "" { + return nil, errors.New("parameter fleetspaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{fleetspaceName}", url.PathEscape(fleetspaceName)) + if databaseName == "" { + return nil, errors.New("parameter databaseName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{databaseName}", url.PathEscape(databaseName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2025-02-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// BeginUpdate - Updates a fleet database. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2025-02-01-preview +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - fleetName - Name of the database fleet. +// - fleetspaceName - Name of the fleetspace. +// - databaseName - Name of the database. +// - properties - The database object to patch. +// - options - FleetDatabasesClientBeginUpdateOptions contains the optional parameters for the FleetDatabasesClient.BeginUpdate +// method. +func (client *FleetDatabasesClient) BeginUpdate(ctx context.Context, resourceGroupName string, fleetName string, fleetspaceName string, databaseName string, properties FleetDatabase, options *FleetDatabasesClientBeginUpdateOptions) (*runtime.Poller[FleetDatabasesClientUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.update(ctx, resourceGroupName, fleetName, fleetspaceName, databaseName, properties, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[FleetDatabasesClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[FleetDatabasesClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Update - Updates a fleet database. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2025-02-01-preview +func (client *FleetDatabasesClient) update(ctx context.Context, resourceGroupName string, fleetName string, fleetspaceName string, databaseName string, properties FleetDatabase, options *FleetDatabasesClientBeginUpdateOptions) (*http.Response, error) { + var err error + const operationName = "FleetDatabasesClient.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, fleetName, fleetspaceName, databaseName, 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 *FleetDatabasesClient) updateCreateRequest(ctx context.Context, resourceGroupName string, fleetName string, fleetspaceName string, databaseName string, properties FleetDatabase, _ *FleetDatabasesClientBeginUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DatabaseFleetManager/fleets/{fleetName}/fleetspaces/{fleetspaceName}/databases/{databaseName}" + 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 fleetName == "" { + return nil, errors.New("parameter fleetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{fleetName}", url.PathEscape(fleetName)) + if fleetspaceName == "" { + return nil, errors.New("parameter fleetspaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{fleetspaceName}", url.PathEscape(fleetspaceName)) + if databaseName == "" { + return nil, errors.New("parameter databaseName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{databaseName}", url.PathEscape(databaseName)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2025-02-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, properties); err != nil { + return nil, err + } + return req, nil +} diff --git a/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager/fleetdatabases_client_example_test.go b/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager/fleetdatabases_client_example_test.go new file mode 100644 index 000000000000..0c4bee52a57f --- /dev/null +++ b/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager/fleetdatabases_client_example_test.go @@ -0,0 +1,464 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armdatabasefleetmanager_test + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/Azure/azure-sdk-for-go/sdk/azidentity" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager" + "log" + "time" +) + +// Generated from example definition: 2025-02-01-preview/FleetDatabases_ChangeTier_MaximumSet_Gen.json +func ExampleFleetDatabasesClient_BeginChangeTier() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armdatabasefleetmanager.NewClientFactory("C3897315-3847-4D8A-B2FC-7307B066AD63", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + poller, err := clientFactory.NewFleetDatabasesClient().BeginChangeTier(ctx, "rg-database-operations", "data-fleet-01", "prod-environment", "customer-db-prod", armdatabasefleetmanager.DatabaseChangeTierProperties{ + TargetTierName: to.Ptr("Standard"), + }, nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + _, err = poller.PollUntilDone(ctx, nil) + if err != nil { + log.Fatalf("failed to pull the result: %v", err) + } +} + +// Generated from example definition: 2025-02-01-preview/FleetDatabases_CreateOrUpdate_MaximumSet_Gen.json +func ExampleFleetDatabasesClient_BeginCreateOrUpdate() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armdatabasefleetmanager.NewClientFactory("C3897315-3847-4D8A-B2FC-7307B066AD63", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + poller, err := clientFactory.NewFleetDatabasesClient().BeginCreateOrUpdate(ctx, "rg-database-operations", "data-fleet-01", "prod-environment", "customer-db-prod", armdatabasefleetmanager.FleetDatabase{ + Properties: &armdatabasefleetmanager.FleetDatabaseProperties{ + CreateMode: to.Ptr(armdatabasefleetmanager.DatabaseCreateModeDefault), + TierName: to.Ptr("Premium"), + RestoreFromTime: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2024-11-06T09:16:05.048Z"); return t }()), + SourceDatabaseName: to.Ptr("existing-db-prod"), + ResourceTags: map[string]*string{ + "project": to.Ptr("Customer Data"), + }, + Identity: &armdatabasefleetmanager.Identity{ + IdentityType: to.Ptr(armdatabasefleetmanager.IdentityTypeNone), + UserAssignedIdentities: []*armdatabasefleetmanager.DatabaseIdentity{ + { + ResourceID: to.Ptr("/subscriptions/12345678-90ab-cdef-1234-567890abcdef/resourceGroups/rg-database-operations/providers/Microsoft.ManagedIdentity/userAssignedIdentities/identity-01"), + PrincipalID: to.Ptr("a2b3c4d5-6789-0123-4567-89abcdef1234"), + ClientID: to.Ptr("a2b3c4d5-6789-0123-4567-89abcdef1234"), + }, + }, + FederatedClientID: to.Ptr("a2b3c4d5-6789-0123-4567-89abcdef1234"), + }, + TransparentDataEncryption: &armdatabasefleetmanager.TransparentDataEncryption{ + KeyURI: to.Ptr("https://keyvaultname.vault.azure.net/keys/myKey/12345"), + Keys: []*string{ + to.Ptr("key1"), + }, + EnableAutoRotation: to.Ptr(true), + }, + }, + }, nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + res, err := poller.PollUntilDone(ctx, nil) + if err != nil { + log.Fatalf("failed to pull the result: %v", err) + } + // You could use response here. We use blank identifier for just demo purposes. + _ = res + // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // res = armdatabasefleetmanager.FleetDatabasesClientCreateOrUpdateResponse{ + // FleetDatabase: &armdatabasefleetmanager.FleetDatabase{ + // Properties: &armdatabasefleetmanager.FleetDatabaseProperties{ + // OriginalDatabaseID: to.Ptr("uwzvasvknrwbnqgu"), + // ProvisioningState: to.Ptr(armdatabasefleetmanager.AzureProvisioningStateSucceeded), + // CreateMode: to.Ptr(armdatabasefleetmanager.DatabaseCreateModeDefault), + // TierName: to.Ptr("Premium"), + // ConnectionString: to.Ptr("Server=myserver.database.windows.net;Database=customer-db-prod;User Id=user;"), + // Recoverable: to.Ptr(true), + // RestoreFromTime: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2024-11-06T09:16:05.048Z"); return t}()), + // EarliestRestoreTime: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2024-11-06T09:16:05.048Z"); return t}()), + // LatestRestoreTime: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2024-11-06T09:16:05.048Z"); return t}()), + // BackupRetentionDays: to.Ptr[int32](22), + // DatabaseSizeGbMax: to.Ptr[int32](100), + // SourceDatabaseName: to.Ptr("existing-db-prod"), + // ResourceTags: map[string]*string{ + // "project": to.Ptr("Customer Data"), + // }, + // Identity: &armdatabasefleetmanager.Identity{ + // IdentityType: to.Ptr(armdatabasefleetmanager.IdentityTypeNone), + // UserAssignedIdentities: []*armdatabasefleetmanager.DatabaseIdentity{ + // { + // ResourceID: to.Ptr("/subscriptions/12345678-90ab-cdef-1234-567890abcdef/resourceGroups/rg-database-operations/providers/Microsoft.ManagedIdentity/userAssignedIdentities/identity-01"), + // PrincipalID: to.Ptr("a2b3c4d5-6789-0123-4567-89abcdef1234"), + // ClientID: to.Ptr("a2b3c4d5-6789-0123-4567-89abcdef1234"), + // }, + // }, + // FederatedClientID: to.Ptr("a2b3c4d5-6789-0123-4567-89abcdef1234"), + // }, + // TransparentDataEncryption: &armdatabasefleetmanager.TransparentDataEncryption{ + // KeyURI: to.Ptr("https://keyvaultname.vault.azure.net/keys/myKey/12345"), + // Keys: []*string{ + // to.Ptr("key1"), + // }, + // EnableAutoRotation: to.Ptr(true), + // }, + // }, + // ID: to.Ptr("/subscriptions/C3897315-3847-4D8A-B2FC-7307B066AD63/resourceGroups/rg-database-operations/providers/Microsoft.DatabaseFleetManager/fleet/fleetspace/database/customer-db-prod"), + // Name: to.Ptr("customer-db-prod"), + // Type: to.Ptr("Microsoft.DatabaseFleetManager/fleet/fleetspace/database"), + // SystemData: &armdatabasefleetmanager.SystemData{ + // CreatedBy: to.Ptr("admin-user"), + // CreatedByType: to.Ptr(armdatabasefleetmanager.CreatedByTypeUser), + // CreatedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2024-11-06T09:16:01.802Z"); return t}()), + // LastModifiedBy: to.Ptr("admin-user"), + // LastModifiedByType: to.Ptr(armdatabasefleetmanager.CreatedByTypeUser), + // LastModifiedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2024-11-06T09:16:01.803Z"); return t}()), + // }, + // }, + // } +} + +// Generated from example definition: 2025-02-01-preview/FleetDatabases_Delete_MaximumSet_Gen.json +func ExampleFleetDatabasesClient_BeginDelete() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armdatabasefleetmanager.NewClientFactory("C3897315-3847-4D8A-B2FC-7307B066AD63", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + poller, err := clientFactory.NewFleetDatabasesClient().BeginDelete(ctx, "rg-database-operations", "data-fleet-01", "prod-environment", "customer-db-prod", nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + _, err = poller.PollUntilDone(ctx, nil) + if err != nil { + log.Fatalf("failed to pull the result: %v", err) + } +} + +// Generated from example definition: 2025-02-01-preview/FleetDatabases_Get_MaximumSet_Gen.json +func ExampleFleetDatabasesClient_Get() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armdatabasefleetmanager.NewClientFactory("C3897315-3847-4D8A-B2FC-7307B066AD63", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + res, err := clientFactory.NewFleetDatabasesClient().Get(ctx, "rg-database-operations", "data-fleet-01", "prod-environment", "customer-db-prod", nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + // You could use response here. We use blank identifier for just demo purposes. + _ = res + // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // res = armdatabasefleetmanager.FleetDatabasesClientGetResponse{ + // FleetDatabase: &armdatabasefleetmanager.FleetDatabase{ + // Properties: &armdatabasefleetmanager.FleetDatabaseProperties{ + // OriginalDatabaseID: to.Ptr("uwzvasvknrwbnqgu"), + // ProvisioningState: to.Ptr(armdatabasefleetmanager.AzureProvisioningStateSucceeded), + // CreateMode: to.Ptr(armdatabasefleetmanager.DatabaseCreateModeDefault), + // TierName: to.Ptr("Premium"), + // ConnectionString: to.Ptr("Server=myserver.database.windows.net;Database=customer-db-prod;User Id=user;"), + // Recoverable: to.Ptr(true), + // RestoreFromTime: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2024-11-06T09:16:05.048Z"); return t}()), + // EarliestRestoreTime: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2024-11-06T09:16:05.048Z"); return t}()), + // LatestRestoreTime: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2024-11-06T09:16:05.048Z"); return t}()), + // BackupRetentionDays: to.Ptr[int32](22), + // DatabaseSizeGbMax: to.Ptr[int32](100), + // SourceDatabaseName: to.Ptr("existing-db-prod"), + // ResourceTags: map[string]*string{ + // "project": to.Ptr("Customer Data"), + // }, + // Identity: &armdatabasefleetmanager.Identity{ + // IdentityType: to.Ptr(armdatabasefleetmanager.IdentityTypeNone), + // UserAssignedIdentities: []*armdatabasefleetmanager.DatabaseIdentity{ + // { + // ResourceID: to.Ptr("/subscriptions/12345678-90ab-cdef-1234-567890abcdef/resourceGroups/rg-database-operations/providers/Microsoft.ManagedIdentity/userAssignedIdentities/identity-01"), + // PrincipalID: to.Ptr("a2b3c4d5-6789-0123-4567-89abcdef1234"), + // ClientID: to.Ptr("a2b3c4d5-6789-0123-4567-89abcdef1234"), + // }, + // }, + // FederatedClientID: to.Ptr("a2b3c4d5-6789-0123-4567-89abcdef1234"), + // }, + // TransparentDataEncryption: &armdatabasefleetmanager.TransparentDataEncryption{ + // KeyURI: to.Ptr("https://keyvaultname.vault.azure.net/keys/myKey/12345"), + // Keys: []*string{ + // to.Ptr("key1"), + // }, + // EnableAutoRotation: to.Ptr(true), + // }, + // }, + // ID: to.Ptr("/subscriptions/C3897315-3847-4D8A-B2FC-7307B066AD63/resourceGroups/rg-database-operations/providers/Microsoft.DatabaseFleetManager/fleets/fleet-01/fleetspaces/prod-environment/databases/customer-db-prod"), + // Name: to.Ptr("customer-db-prod"), + // Type: to.Ptr("Microsoft.DatabaseFleetManager/fleets/fleetspaces/databases"), + // SystemData: &armdatabasefleetmanager.SystemData{ + // CreatedBy: to.Ptr("admin-user"), + // CreatedByType: to.Ptr(armdatabasefleetmanager.CreatedByTypeUser), + // CreatedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2024-11-06T09:16:01.802Z"); return t}()), + // LastModifiedBy: to.Ptr("admin-user"), + // LastModifiedByType: to.Ptr(armdatabasefleetmanager.CreatedByTypeUser), + // LastModifiedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2024-11-06T09:16:01.803Z"); return t}()), + // }, + // }, + // } +} + +// Generated from example definition: 2025-02-01-preview/FleetDatabases_ListByFleetspace_MaximumSet_Gen.json +func ExampleFleetDatabasesClient_NewListByFleetspacePager() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armdatabasefleetmanager.NewClientFactory("C3897315-3847-4D8A-B2FC-7307B066AD63", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + pager := clientFactory.NewFleetDatabasesClient().NewListByFleetspacePager("rg-database-operations", "data-fleet-01", "prod-environment", &FleetDatabasesClientListByFleetspaceOptions{ + Skip: to.Ptr[int64](24), + Top: to.Ptr[int64](2), + Filter: to.Ptr("tier eq 'Premium'"), + Skiptoken: to.Ptr("sbrskcoueja")}) + for pager.More() { + page, err := pager.NextPage(ctx) + if err != nil { + log.Fatalf("failed to advance page: %v", err) + } + for _, v := range page.Value { + // You could use page here. We use blank identifier for just demo purposes. + _ = v + } + // If the HTTP response code is 200 as defined in example definition, your page structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // page = armdatabasefleetmanager.FleetDatabasesClientListByFleetspaceResponse{ + // FleetDatabaseListResult: armdatabasefleetmanager.FleetDatabaseListResult{ + // Value: []*armdatabasefleetmanager.FleetDatabase{ + // { + // Properties: &armdatabasefleetmanager.FleetDatabaseProperties{ + // OriginalDatabaseID: to.Ptr("uwzvasvknrwbnqgu"), + // ProvisioningState: to.Ptr(armdatabasefleetmanager.AzureProvisioningStateSucceeded), + // CreateMode: to.Ptr(armdatabasefleetmanager.DatabaseCreateModeDefault), + // TierName: to.Ptr("Premium"), + // ConnectionString: to.Ptr("Server=myserver.database.windows.net;Database=customer-db-prod;User Id=user;"), + // Recoverable: to.Ptr(true), + // RestoreFromTime: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2024-11-06T09:16:05.048Z"); return t}()), + // EarliestRestoreTime: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2024-11-06T09:16:05.048Z"); return t}()), + // LatestRestoreTime: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2024-11-06T09:16:05.048Z"); return t}()), + // BackupRetentionDays: to.Ptr[int32](22), + // DatabaseSizeGbMax: to.Ptr[int32](100), + // SourceDatabaseName: to.Ptr("existing-db-prod"), + // ResourceTags: map[string]*string{ + // "project": to.Ptr("Customer Data"), + // }, + // Identity: &armdatabasefleetmanager.Identity{ + // IdentityType: to.Ptr(armdatabasefleetmanager.IdentityTypeNone), + // UserAssignedIdentities: []*armdatabasefleetmanager.DatabaseIdentity{ + // { + // ResourceID: to.Ptr("/subscriptions/12345678-90ab-cdef-1234-567890abcdef/resourceGroups/rg-database-operations/providers/Microsoft.ManagedIdentity/userAssignedIdentities/identity-01"), + // PrincipalID: to.Ptr("a2b3c4d5-6789-0123-4567-89abcdef1234"), + // ClientID: to.Ptr("a2b3c4d5-6789-0123-4567-89abcdef1234"), + // }, + // }, + // FederatedClientID: to.Ptr("a2b3c4d5-6789-0123-4567-89abcdef1234"), + // }, + // TransparentDataEncryption: &armdatabasefleetmanager.TransparentDataEncryption{ + // KeyURI: to.Ptr("https://keyvaultname.vault.azure.net/keys/myKey/12345"), + // Keys: []*string{ + // to.Ptr("key1"), + // }, + // EnableAutoRotation: to.Ptr(true), + // }, + // }, + // ID: to.Ptr("/subscriptions/C3897315-3847-4D8A-B2FC-7307B066AD63/resourceGroups/rg-database-operations/providers/Microsoft.DatabaseFleetManager/fleets/fleet-01/fleetspaces/prod-environment/databases/customer-db-prod"), + // Name: to.Ptr("customer-db-prod"), + // Type: to.Ptr("Microsoft.DatabaseFleetManager/fleets/fleetspaces/databases"), + // SystemData: &armdatabasefleetmanager.SystemData{ + // CreatedBy: to.Ptr("admin-user"), + // CreatedByType: to.Ptr(armdatabasefleetmanager.CreatedByTypeUser), + // CreatedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2024-11-06T09:16:01.802Z"); return t}()), + // LastModifiedBy: to.Ptr("admin-user"), + // LastModifiedByType: to.Ptr(armdatabasefleetmanager.CreatedByTypeUser), + // LastModifiedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2024-11-06T09:16:01.803Z"); return t}()), + // }, + // }, + // }, + // NextLink: to.Ptr("https://microsoft.com/ajgwcc"), + // }, + // } + } +} + +// Generated from example definition: 2025-02-01-preview/FleetDatabases_Rename_MaximumSet_Gen.json +func ExampleFleetDatabasesClient_BeginRename() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armdatabasefleetmanager.NewClientFactory("C3897315-3847-4D8A-B2FC-7307B066AD63", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + poller, err := clientFactory.NewFleetDatabasesClient().BeginRename(ctx, "rg-database-operations", "data-fleet-01", "prod-environment", "customer-db-prod", armdatabasefleetmanager.DatabaseRenameProperties{ + NewName: to.Ptr("new-customer-db-prod"), + }, nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + _, err = poller.PollUntilDone(ctx, nil) + if err != nil { + log.Fatalf("failed to pull the result: %v", err) + } +} + +// Generated from example definition: 2025-02-01-preview/FleetDatabases_Revert_MaximumSet_Gen.json +func ExampleFleetDatabasesClient_BeginRevert() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armdatabasefleetmanager.NewClientFactory("C3897315-3847-4D8A-B2FC-7307B066AD63", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + poller, err := clientFactory.NewFleetDatabasesClient().BeginRevert(ctx, "rg-database-operations", "data-fleet-01", "prod-environment", "customer-db-prod", nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + _, err = poller.PollUntilDone(ctx, nil) + if err != nil { + log.Fatalf("failed to pull the result: %v", err) + } +} + +// Generated from example definition: 2025-02-01-preview/FleetDatabases_Update_MaximumSet_Gen.json +func ExampleFleetDatabasesClient_BeginUpdate() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armdatabasefleetmanager.NewClientFactory("C3897315-3847-4D8A-B2FC-7307B066AD63", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + poller, err := clientFactory.NewFleetDatabasesClient().BeginUpdate(ctx, "rgdatabasefleetmanager", "production-fleet", "primary-space", "customer-database-prod", armdatabasefleetmanager.FleetDatabase{ + Properties: &armdatabasefleetmanager.FleetDatabaseProperties{ + CreateMode: to.Ptr(armdatabasefleetmanager.DatabaseCreateModeDefault), + TierName: to.Ptr("Standard"), + RestoreFromTime: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2024-11-06T09:16:05.048Z"); return t }()), + SourceDatabaseName: to.Ptr("customer-database-staging"), + ResourceTags: map[string]*string{ + "environment": to.Ptr("production"), + "owner": to.Ptr("database-team"), + }, + Identity: &armdatabasefleetmanager.Identity{ + IdentityType: to.Ptr(armdatabasefleetmanager.IdentityTypeUserAssigned), + UserAssignedIdentities: []*armdatabasefleetmanager.DatabaseIdentity{ + { + ResourceID: to.Ptr("/subscriptions/C3897315-3847-4D8A-B2FC-7307B066AD63/resourcegroups/rgdatabasefleetmanager/providers/Microsoft.ManagedIdentity/userAssignedIdentities/db-identity"), + PrincipalID: to.Ptr("f8b7c2d3-b9c4-4f3b-85cd-3d56c6e49f92"), + ClientID: to.Ptr("d2d8b19e-c4f7-4c62-8e8d-7f0f96d94e39"), + }, + }, + FederatedClientID: to.Ptr("a2b3c4d5-6789-0123-4567-89abcdef1234"), + }, + TransparentDataEncryption: &armdatabasefleetmanager.TransparentDataEncryption{ + KeyURI: to.Ptr("https://keyvault-contoso.vault.azure.net/keys/db-encryption-key/abc123"), + Keys: []*string{ + to.Ptr("abc123"), + to.Ptr("xyz789"), + }, + EnableAutoRotation: to.Ptr(true), + }, + }, + }, nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + res, err := poller.PollUntilDone(ctx, nil) + if err != nil { + log.Fatalf("failed to pull the result: %v", err) + } + // You could use response here. We use blank identifier for just demo purposes. + _ = res + // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // res = armdatabasefleetmanager.FleetDatabasesClientUpdateResponse{ + // FleetDatabase: &armdatabasefleetmanager.FleetDatabase{ + // Properties: &armdatabasefleetmanager.FleetDatabaseProperties{ + // OriginalDatabaseID: to.Ptr("uwzvasvknrwbnqgu"), + // ProvisioningState: to.Ptr(armdatabasefleetmanager.AzureProvisioningStateSucceeded), + // CreateMode: to.Ptr(armdatabasefleetmanager.DatabaseCreateModeDefault), + // TierName: to.Ptr("Standard"), + // ConnectionString: to.Ptr("Server=tcp:dbserver.contoso.com;Database=customer-database-prod;User ID=dbadmin;"), + // Recoverable: to.Ptr(true), + // RestoreFromTime: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2024-11-06T09:16:05.048Z"); return t}()), + // EarliestRestoreTime: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2024-11-06T09:16:05.048Z"); return t}()), + // LatestRestoreTime: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2024-11-06T09:16:05.048Z"); return t}()), + // BackupRetentionDays: to.Ptr[int32](30), + // DatabaseSizeGbMax: to.Ptr[int32](500), + // SourceDatabaseName: to.Ptr("customer-database-staging"), + // ResourceTags: map[string]*string{ + // "environment": to.Ptr("production"), + // "owner": to.Ptr("database-team"), + // }, + // Identity: &armdatabasefleetmanager.Identity{ + // IdentityType: to.Ptr(armdatabasefleetmanager.IdentityTypeUserAssigned), + // UserAssignedIdentities: []*armdatabasefleetmanager.DatabaseIdentity{ + // { + // ResourceID: to.Ptr("/subscriptions/C3897315-3847-4D8A-B2FC-7307B066AD63/resourcegroups/rgdatabasefleetmanager/providers/Microsoft.ManagedIdentity/userAssignedIdentities/db-identity"), + // PrincipalID: to.Ptr("f8b7c2d3-b9c4-4f3b-85cd-3d56c6e49f92"), + // ClientID: to.Ptr("d2d8b19e-c4f7-4c62-8e8d-7f0f96d94e39"), + // }, + // }, + // FederatedClientID: to.Ptr("a2b3c4d5-6789-0123-4567-89abcdef1234"), + // }, + // TransparentDataEncryption: &armdatabasefleetmanager.TransparentDataEncryption{ + // KeyURI: to.Ptr("https://keyvault-contoso.vault.azure.net/keys/db-encryption-key/abc123"), + // Keys: []*string{ + // to.Ptr("abc123"), + // to.Ptr("xyz789"), + // }, + // EnableAutoRotation: to.Ptr(true), + // }, + // }, + // ID: to.Ptr("/subscriptions/C3897315-3847-4D8A-B2FC-7307B066AD63/resourceGroups/rg-database-operations/providers/Microsoft.DatabaseFleetManager/fleets/fleet-01/fleetspaces/prod-environment/databases/customer-db-prod"), + // Name: to.Ptr("customer-db-prod"), + // Type: to.Ptr("Microsoft.DatabaseFleetManager/fleets/fleetspaces/databases"), + // SystemData: &armdatabasefleetmanager.SystemData{ + // CreatedBy: to.Ptr("adminUser"), + // CreatedByType: to.Ptr(armdatabasefleetmanager.CreatedByTypeUser), + // CreatedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2024-11-06T09:16:01.802Z"); return t}()), + // LastModifiedBy: to.Ptr("adminUser"), + // LastModifiedByType: to.Ptr(armdatabasefleetmanager.CreatedByTypeUser), + // LastModifiedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2024-11-06T09:16:01.803Z"); return t}()), + // }, + // }, + // } +} diff --git a/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager/fleets_client.go b/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager/fleets_client.go new file mode 100644 index 000000000000..6804c316ea53 --- /dev/null +++ b/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager/fleets_client.go @@ -0,0 +1,464 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armdatabasefleetmanager + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strconv" + "strings" +) + +// FleetsClient contains the methods for the Fleets group. +// Don't use this type directly, use NewFleetsClient() instead. +type FleetsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewFleetsClient creates a new instance of FleetsClient 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 NewFleetsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*FleetsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &FleetsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Creates or updates a fleet resource. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2025-02-01-preview +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - fleetName - Name of the database fleet. +// - resource - The fleet object to create or update. +// - options - FleetsClientBeginCreateOrUpdateOptions contains the optional parameters for the FleetsClient.BeginCreateOrUpdate +// method. +func (client *FleetsClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, fleetName string, resource Fleet, options *FleetsClientBeginCreateOrUpdateOptions) (*runtime.Poller[FleetsClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, fleetName, resource, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[FleetsClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[FleetsClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Creates or updates a fleet resource. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2025-02-01-preview +func (client *FleetsClient) createOrUpdate(ctx context.Context, resourceGroupName string, fleetName string, resource Fleet, options *FleetsClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "FleetsClient.BeginCreateOrUpdate" + 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, fleetName, 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 +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *FleetsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, fleetName string, resource Fleet, _ *FleetsClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DatabaseFleetManager/fleets/{fleetName}" + 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 fleetName == "" { + return nil, errors.New("parameter fleetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{fleetName}", url.PathEscape(fleetName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2025-02-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, resource); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Deletes a fleet. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2025-02-01-preview +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - fleetName - Name of the database fleet. +// - options - FleetsClientBeginDeleteOptions contains the optional parameters for the FleetsClient.BeginDelete method. +func (client *FleetsClient) BeginDelete(ctx context.Context, resourceGroupName string, fleetName string, options *FleetsClientBeginDeleteOptions) (*runtime.Poller[FleetsClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, fleetName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[FleetsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[FleetsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes a fleet. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2025-02-01-preview +func (client *FleetsClient) deleteOperation(ctx context.Context, resourceGroupName string, fleetName string, options *FleetsClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "FleetsClient.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, fleetName, 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 *FleetsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, fleetName string, _ *FleetsClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DatabaseFleetManager/fleets/{fleetName}" + 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 fleetName == "" { + return nil, errors.New("parameter fleetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{fleetName}", url.PathEscape(fleetName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2025-02-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Gets a fleet resource. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2025-02-01-preview +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - fleetName - Name of the database fleet. +// - options - FleetsClientGetOptions contains the optional parameters for the FleetsClient.Get method. +func (client *FleetsClient) Get(ctx context.Context, resourceGroupName string, fleetName string, options *FleetsClientGetOptions) (FleetsClientGetResponse, error) { + var err error + const operationName = "FleetsClient.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, fleetName, options) + if err != nil { + return FleetsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return FleetsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return FleetsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *FleetsClient) getCreateRequest(ctx context.Context, resourceGroupName string, fleetName string, _ *FleetsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DatabaseFleetManager/fleets/{fleetName}" + 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 fleetName == "" { + return nil, errors.New("parameter fleetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{fleetName}", url.PathEscape(fleetName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2025-02-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 *FleetsClient) getHandleResponse(resp *http.Response) (FleetsClientGetResponse, error) { + result := FleetsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Fleet); err != nil { + return FleetsClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Gets all fleets in a subscription. +// +// Generated from API version 2025-02-01-preview +// - options - FleetsClientListOptions contains the optional parameters for the FleetsClient.NewListPager method. +func (client *FleetsClient) NewListPager(options *FleetsClientListOptions) *runtime.Pager[FleetsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[FleetsClientListResponse]{ + More: func(page FleetsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *FleetsClientListResponse) (FleetsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "FleetsClient.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 FleetsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *FleetsClient) listCreateRequest(ctx context.Context, _ *FleetsClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.DatabaseFleetManager/fleets" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2025-02-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 *FleetsClient) listHandleResponse(resp *http.Response) (FleetsClientListResponse, error) { + result := FleetsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.FleetListResult); err != nil { + return FleetsClientListResponse{}, err + } + return result, nil +} + +// NewListByResourceGroupPager - Gets all fleets in a resource group. +// +// Generated from API version 2025-02-01-preview +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - options - FleetsClientListByResourceGroupOptions contains the optional parameters for the FleetsClient.NewListByResourceGroupPager +// method. +func (client *FleetsClient) NewListByResourceGroupPager(resourceGroupName string, options *FleetsClientListByResourceGroupOptions) *runtime.Pager[FleetsClientListByResourceGroupResponse] { + return runtime.NewPager(runtime.PagingHandler[FleetsClientListByResourceGroupResponse]{ + More: func(page FleetsClientListByResourceGroupResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *FleetsClientListByResourceGroupResponse) (FleetsClientListByResourceGroupResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "FleetsClient.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 FleetsClientListByResourceGroupResponse{}, err + } + return client.listByResourceGroupHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByResourceGroupCreateRequest creates the ListByResourceGroup request. +func (client *FleetsClient) listByResourceGroupCreateRequest(ctx context.Context, resourceGroupName string, options *FleetsClientListByResourceGroupOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DatabaseFleetManager/fleets" + 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() + if options != nil && options.Skip != nil { + reqQP.Set("$skip", strconv.FormatInt(*options.Skip, 10)) + } + if options != nil && options.Skiptoken != nil { + reqQP.Set("$skiptoken", *options.Skiptoken) + } + if options != nil && options.Top != nil { + reqQP.Set("$top", strconv.FormatInt(*options.Top, 10)) + } + reqQP.Set("api-version", "2025-02-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 *FleetsClient) listByResourceGroupHandleResponse(resp *http.Response) (FleetsClientListByResourceGroupResponse, error) { + result := FleetsClientListByResourceGroupResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.FleetListResult); err != nil { + return FleetsClientListByResourceGroupResponse{}, err + } + return result, nil +} + +// BeginUpdate - Modifies a fleet resource. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2025-02-01-preview +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - fleetName - Name of the database fleet. +// - properties - The fleet object to patch. +// - options - FleetsClientBeginUpdateOptions contains the optional parameters for the FleetsClient.BeginUpdate method. +func (client *FleetsClient) BeginUpdate(ctx context.Context, resourceGroupName string, fleetName string, properties FleetUpdate, options *FleetsClientBeginUpdateOptions) (*runtime.Poller[FleetsClientUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.update(ctx, resourceGroupName, fleetName, properties, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[FleetsClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[FleetsClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Update - Modifies a fleet resource. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2025-02-01-preview +func (client *FleetsClient) update(ctx context.Context, resourceGroupName string, fleetName string, properties FleetUpdate, options *FleetsClientBeginUpdateOptions) (*http.Response, error) { + var err error + const operationName = "FleetsClient.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, fleetName, 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 *FleetsClient) updateCreateRequest(ctx context.Context, resourceGroupName string, fleetName string, properties FleetUpdate, _ *FleetsClientBeginUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DatabaseFleetManager/fleets/{fleetName}" + 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 fleetName == "" { + return nil, errors.New("parameter fleetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{fleetName}", url.PathEscape(fleetName)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2025-02-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, properties); err != nil { + return nil, err + } + return req, nil +} diff --git a/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager/fleets_client_example_test.go b/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager/fleets_client_example_test.go new file mode 100644 index 000000000000..23ed412afd59 --- /dev/null +++ b/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager/fleets_client_example_test.go @@ -0,0 +1,302 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armdatabasefleetmanager_test + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/Azure/azure-sdk-for-go/sdk/azidentity" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager" + "log" +) + +// Generated from example definition: 2025-02-01-preview/Fleets_CreateOrUpdate_MaximumSet_Gen.json +func ExampleFleetsClient_BeginCreateOrUpdate() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armdatabasefleetmanager.NewClientFactory("C3897315-3847-4D8A-B2FC-7307B066AD63", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + poller, err := clientFactory.NewFleetsClient().BeginCreateOrUpdate(ctx, "rg-database-fleet-manager", "production-fleet-01", armdatabasefleetmanager.Fleet{ + Properties: &armdatabasefleetmanager.FleetProperties{ + Description: to.Ptr("Production fleet for high availability and scalability."), + }, + Tags: map[string]*string{ + "environment": to.Ptr("production"), + "owner": to.Ptr("team-database"), + }, + Location: to.Ptr("East US"), + }, nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + res, err := poller.PollUntilDone(ctx, nil) + if err != nil { + log.Fatalf("failed to pull the result: %v", err) + } + // You could use response here. We use blank identifier for just demo purposes. + _ = res + // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // res = armdatabasefleetmanager.FleetsClientCreateOrUpdateResponse{ + // Fleet: &armdatabasefleetmanager.Fleet{ + // Properties: &armdatabasefleetmanager.FleetProperties{ + // Description: to.Ptr("Production fleet for high availability and scalability."), + // ProvisioningState: to.Ptr(armdatabasefleetmanager.AzureProvisioningStateSucceeded), + // }, + // Tags: map[string]*string{ + // "environment": to.Ptr("production"), + // "owner": to.Ptr("team-database"), + // }, + // Location: to.Ptr("East US"), + // ID: to.Ptr("/subscriptions/C3897315-3847-4D8A-B2FC-7307B066AD63/resourceGroups/rg-database-fleet-manager/providers/Microsoft.DatabaseFleetManager/fleet/production-fleet-01"), + // Name: to.Ptr("production-fleet-01"), + // Type: to.Ptr("Microsoft.DatabaseFleetManager/fleets"), + // SystemData: &armdatabasefleetmanager.SystemData{ + // CreatedBy: to.Ptr("adminuser"), + // CreatedByType: to.Ptr(armdatabasefleetmanager.CreatedByTypeUser), + // CreatedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2024-11-06T09:16:01.802Z"); return t}()), + // LastModifiedBy: to.Ptr("adminuser"), + // LastModifiedByType: to.Ptr(armdatabasefleetmanager.CreatedByTypeUser), + // LastModifiedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2024-11-06T09:16:01.803Z"); return t}()), + // }, + // }, + // } +} + +// Generated from example definition: 2025-02-01-preview/Fleets_Delete_MaximumSet_Gen.json +func ExampleFleetsClient_BeginDelete() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armdatabasefleetmanager.NewClientFactory("C3897315-3847-4D8A-B2FC-7307B066AD63", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + poller, err := clientFactory.NewFleetsClient().BeginDelete(ctx, "rg-database-fleet-manager", "production-fleet-01", nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + _, err = poller.PollUntilDone(ctx, nil) + if err != nil { + log.Fatalf("failed to pull the result: %v", err) + } +} + +// Generated from example definition: 2025-02-01-preview/Fleets_Get_MaximumSet_Gen.json +func ExampleFleetsClient_Get() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armdatabasefleetmanager.NewClientFactory("C3897315-3847-4D8A-B2FC-7307B066AD63", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + res, err := clientFactory.NewFleetsClient().Get(ctx, "rg-database-fleet-manager", "production-fleet-01", nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + // You could use response here. We use blank identifier for just demo purposes. + _ = res + // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // res = armdatabasefleetmanager.FleetsClientGetResponse{ + // Fleet: &armdatabasefleetmanager.Fleet{ + // Properties: &armdatabasefleetmanager.FleetProperties{ + // Description: to.Ptr("Production fleet for high availability and scalability."), + // ProvisioningState: to.Ptr(armdatabasefleetmanager.AzureProvisioningStateSucceeded), + // }, + // Tags: map[string]*string{ + // "environment": to.Ptr("production"), + // "owner": to.Ptr("team-database"), + // }, + // Location: to.Ptr("East US"), + // ID: to.Ptr("/subscriptions/C3897315-3847-4D8A-B2FC-7307B066AD63/resourceGroups/rg-database-fleet-manager/providers/Microsoft.DatabaseFleetManager/fleet/production-fleet-01"), + // Name: to.Ptr("production-fleet-01"), + // Type: to.Ptr("Microsoft.DatabaseFleetManager/fleets"), + // SystemData: &armdatabasefleetmanager.SystemData{ + // CreatedBy: to.Ptr("adminuser"), + // CreatedByType: to.Ptr(armdatabasefleetmanager.CreatedByTypeUser), + // CreatedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2024-11-06T09:16:01.802Z"); return t}()), + // LastModifiedBy: to.Ptr("adminuser"), + // LastModifiedByType: to.Ptr(armdatabasefleetmanager.CreatedByTypeUser), + // LastModifiedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2024-11-06T09:16:01.803Z"); return t}()), + // }, + // }, + // } +} + +// Generated from example definition: 2025-02-01-preview/Fleets_List_MaximumSet_Gen.json +func ExampleFleetsClient_NewListPager() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armdatabasefleetmanager.NewClientFactory("C3897315-3847-4D8A-B2FC-7307B066AD63", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + pager := clientFactory.NewFleetsClient().NewListPager(nil) + for pager.More() { + page, err := pager.NextPage(ctx) + if err != nil { + log.Fatalf("failed to advance page: %v", err) + } + for _, v := range page.Value { + // You could use page here. We use blank identifier for just demo purposes. + _ = v + } + // If the HTTP response code is 200 as defined in example definition, your page structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // page = armdatabasefleetmanager.FleetsClientListResponse{ + // FleetListResult: armdatabasefleetmanager.FleetListResult{ + // Value: []*armdatabasefleetmanager.Fleet{ + // { + // Properties: &armdatabasefleetmanager.FleetProperties{ + // Description: to.Ptr("Fleet containing critical production databases."), + // ProvisioningState: to.Ptr(armdatabasefleetmanager.AzureProvisioningStateSucceeded), + // }, + // Tags: map[string]*string{ + // "environment": to.Ptr("production"), + // "owner": to.Ptr("team-database"), + // }, + // Location: to.Ptr("East US"), + // ID: to.Ptr("/subscriptions/C3897315-3847-4D8A-B2FC-7307B066AD63/resourceGroups/rg-database-fleet-manager/providers/Microsoft.DatabaseFleetManager/fleet/critical-production-fleet"), + // Name: to.Ptr("critical-production-fleet"), + // Type: to.Ptr("Microsoft.DatabaseFleetManager/fleets"), + // SystemData: &armdatabasefleetmanager.SystemData{ + // CreatedBy: to.Ptr("adminuser"), + // CreatedByType: to.Ptr(armdatabasefleetmanager.CreatedByTypeUser), + // CreatedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2024-11-06T09:16:01.802Z"); return t}()), + // LastModifiedBy: to.Ptr("adminuser"), + // LastModifiedByType: to.Ptr(armdatabasefleetmanager.CreatedByTypeUser), + // LastModifiedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2024-11-06T09:16:01.803Z"); return t}()), + // }, + // }, + // }, + // NextLink: to.Ptr("https://microsoft.com/a"), + // }, + // } + } +} + +// Generated from example definition: 2025-02-01-preview/Fleets_ListByResourceGroup_MaximumSet_Gen.json +func ExampleFleetsClient_NewListByResourceGroupPager() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armdatabasefleetmanager.NewClientFactory("C3897315-3847-4D8A-B2FC-7307B066AD63", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + pager := clientFactory.NewFleetsClient().NewListByResourceGroupPager("rg-database-fleet-manager", &FleetsClientListByResourceGroupOptions{ + Skip: to.Ptr[int64](6), + Top: to.Ptr[int64](30), + Skiptoken: to.Ptr("ovlavzakdncfvvbdhqkal")}) + for pager.More() { + page, err := pager.NextPage(ctx) + if err != nil { + log.Fatalf("failed to advance page: %v", err) + } + for _, v := range page.Value { + // You could use page here. We use blank identifier for just demo purposes. + _ = v + } + // If the HTTP response code is 200 as defined in example definition, your page structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // page = armdatabasefleetmanager.FleetsClientListByResourceGroupResponse{ + // FleetListResult: armdatabasefleetmanager.FleetListResult{ + // Value: []*armdatabasefleetmanager.Fleet{ + // { + // Properties: &armdatabasefleetmanager.FleetProperties{ + // Description: to.Ptr("Production fleet for critical workloads."), + // ProvisioningState: to.Ptr(armdatabasefleetmanager.AzureProvisioningStateSucceeded), + // }, + // Tags: map[string]*string{ + // "environment": to.Ptr("production"), + // "owner": to.Ptr("team-database"), + // }, + // Location: to.Ptr("East US"), + // ID: to.Ptr("/subscriptions/C3897315-3847-4D8A-B2FC-7307B066AD63/resourceGroups/rg-database-fleet-manager/providers/Microsoft.DatabaseFleetManager/fleet/production-fleet-01"), + // Name: to.Ptr("production-fleet-01"), + // Type: to.Ptr("Microsoft.DatabaseFleetManager/fleets"), + // SystemData: &armdatabasefleetmanager.SystemData{ + // CreatedBy: to.Ptr("adminuser"), + // CreatedByType: to.Ptr(armdatabasefleetmanager.CreatedByTypeUser), + // CreatedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2024-11-06T09:16:01.802Z"); return t}()), + // LastModifiedBy: to.Ptr("adminuser"), + // LastModifiedByType: to.Ptr(armdatabasefleetmanager.CreatedByTypeUser), + // LastModifiedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2024-11-06T09:16:01.803Z"); return t}()), + // }, + // }, + // }, + // NextLink: to.Ptr("https://microsoft.com/a"), + // }, + // } + } +} + +// Generated from example definition: 2025-02-01-preview/Fleets_Update_MaximumSet_Gen.json +func ExampleFleetsClient_BeginUpdate() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armdatabasefleetmanager.NewClientFactory("C3897315-3847-4D8A-B2FC-7307B066AD63", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + poller, err := clientFactory.NewFleetsClient().BeginUpdate(ctx, "rg-database-fleet-manager", "critical-production-fleet", armdatabasefleetmanager.FleetUpdate{ + Properties: &armdatabasefleetmanager.FleetProperties{ + Description: to.Ptr("Fleet containing critical production databases and high availability configurations."), + }, + Tags: map[string]*string{ + "environment": to.Ptr("production"), + "owner": to.Ptr("team-database"), + }, + }, nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + res, err := poller.PollUntilDone(ctx, nil) + if err != nil { + log.Fatalf("failed to pull the result: %v", err) + } + // You could use response here. We use blank identifier for just demo purposes. + _ = res + // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // res = armdatabasefleetmanager.FleetsClientUpdateResponse{ + // Fleet: &armdatabasefleetmanager.Fleet{ + // Properties: &armdatabasefleetmanager.FleetProperties{ + // Description: to.Ptr("Fleet containing critical production databases and high availability configurations."), + // ProvisioningState: to.Ptr(armdatabasefleetmanager.AzureProvisioningStateSucceeded), + // }, + // Tags: map[string]*string{ + // "environment": to.Ptr("production"), + // "owner": to.Ptr("team-database"), + // }, + // Location: to.Ptr("East US"), + // ID: to.Ptr("/subscriptions/C3897315-3847-4D8A-B2FC-7307B066AD63/resourceGroups/rg-database-fleet-manager/providers/Microsoft.DatabaseFleetManager/fleet/critical-production-fleet"), + // Name: to.Ptr("critical-production-fleet"), + // Type: to.Ptr("Microsoft.DatabaseFleetManager/fleets"), + // SystemData: &armdatabasefleetmanager.SystemData{ + // CreatedBy: to.Ptr("adminuser"), + // CreatedByType: to.Ptr(armdatabasefleetmanager.CreatedByTypeUser), + // CreatedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2024-11-06T09:16:01.802Z"); return t}()), + // LastModifiedBy: to.Ptr("adminuser"), + // LastModifiedByType: to.Ptr(armdatabasefleetmanager.CreatedByTypeUser), + // LastModifiedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2024-11-06T09:16:01.803Z"); return t}()), + // }, + // }, + // } +} diff --git a/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager/fleetspaces_client.go b/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager/fleetspaces_client.go new file mode 100644 index 000000000000..deac337442c9 --- /dev/null +++ b/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager/fleetspaces_client.go @@ -0,0 +1,602 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armdatabasefleetmanager + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strconv" + "strings" +) + +// FleetspacesClient contains the methods for the Fleetspaces group. +// Don't use this type directly, use NewFleetspacesClient() instead. +type FleetspacesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewFleetspacesClient creates a new instance of FleetspacesClient 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 NewFleetspacesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*FleetspacesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &FleetspacesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Creates or updates a fleetspace resource. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2025-02-01-preview +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - fleetName - Name of the database fleet. +// - fleetspaceName - Name of the fleetspace. +// - resource - The fleet object to create or update. +// - options - FleetspacesClientBeginCreateOrUpdateOptions contains the optional parameters for the FleetspacesClient.BeginCreateOrUpdate +// method. +func (client *FleetspacesClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, fleetName string, fleetspaceName string, resource Fleetspace, options *FleetspacesClientBeginCreateOrUpdateOptions) (*runtime.Poller[FleetspacesClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, fleetName, fleetspaceName, resource, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[FleetspacesClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[FleetspacesClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Creates or updates a fleetspace resource. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2025-02-01-preview +func (client *FleetspacesClient) createOrUpdate(ctx context.Context, resourceGroupName string, fleetName string, fleetspaceName string, resource Fleetspace, options *FleetspacesClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "FleetspacesClient.BeginCreateOrUpdate" + 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, fleetName, fleetspaceName, 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 +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *FleetspacesClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, fleetName string, fleetspaceName string, resource Fleetspace, _ *FleetspacesClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DatabaseFleetManager/fleets/{fleetName}/fleetspaces/{fleetspaceName}" + 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 fleetName == "" { + return nil, errors.New("parameter fleetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{fleetName}", url.PathEscape(fleetName)) + if fleetspaceName == "" { + return nil, errors.New("parameter fleetspaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{fleetspaceName}", url.PathEscape(fleetspaceName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2025-02-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, resource); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Deletes a fleetspace. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2025-02-01-preview +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - fleetName - Name of the database fleet. +// - fleetspaceName - Name of the fleetspace. +// - options - FleetspacesClientBeginDeleteOptions contains the optional parameters for the FleetspacesClient.BeginDelete method. +func (client *FleetspacesClient) BeginDelete(ctx context.Context, resourceGroupName string, fleetName string, fleetspaceName string, options *FleetspacesClientBeginDeleteOptions) (*runtime.Poller[FleetspacesClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, fleetName, fleetspaceName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[FleetspacesClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[FleetspacesClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes a fleetspace. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2025-02-01-preview +func (client *FleetspacesClient) deleteOperation(ctx context.Context, resourceGroupName string, fleetName string, fleetspaceName string, options *FleetspacesClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "FleetspacesClient.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, fleetName, fleetspaceName, 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 *FleetspacesClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, fleetName string, fleetspaceName string, _ *FleetspacesClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DatabaseFleetManager/fleets/{fleetName}/fleetspaces/{fleetspaceName}" + 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 fleetName == "" { + return nil, errors.New("parameter fleetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{fleetName}", url.PathEscape(fleetName)) + if fleetspaceName == "" { + return nil, errors.New("parameter fleetspaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{fleetspaceName}", url.PathEscape(fleetspaceName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2025-02-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Gets fleetspace resource. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2025-02-01-preview +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - fleetName - Name of the database fleet. +// - fleetspaceName - Name of the fleetspace. +// - options - FleetspacesClientGetOptions contains the optional parameters for the FleetspacesClient.Get method. +func (client *FleetspacesClient) Get(ctx context.Context, resourceGroupName string, fleetName string, fleetspaceName string, options *FleetspacesClientGetOptions) (FleetspacesClientGetResponse, error) { + var err error + const operationName = "FleetspacesClient.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, fleetName, fleetspaceName, options) + if err != nil { + return FleetspacesClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return FleetspacesClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return FleetspacesClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *FleetspacesClient) getCreateRequest(ctx context.Context, resourceGroupName string, fleetName string, fleetspaceName string, _ *FleetspacesClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DatabaseFleetManager/fleets/{fleetName}/fleetspaces/{fleetspaceName}" + 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 fleetName == "" { + return nil, errors.New("parameter fleetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{fleetName}", url.PathEscape(fleetName)) + if fleetspaceName == "" { + return nil, errors.New("parameter fleetspaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{fleetspaceName}", url.PathEscape(fleetspaceName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2025-02-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 *FleetspacesClient) getHandleResponse(resp *http.Response) (FleetspacesClientGetResponse, error) { + result := FleetspacesClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Fleetspace); err != nil { + return FleetspacesClientGetResponse{}, err + } + return result, nil +} + +// NewListByFleetPager - Lists fleetspaces in a fleet. +// +// Generated from API version 2025-02-01-preview +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - fleetName - Name of the database fleet. +// - options - FleetspacesClientListByFleetOptions contains the optional parameters for the FleetspacesClient.NewListByFleetPager +// method. +func (client *FleetspacesClient) NewListByFleetPager(resourceGroupName string, fleetName string, options *FleetspacesClientListByFleetOptions) *runtime.Pager[FleetspacesClientListByFleetResponse] { + return runtime.NewPager(runtime.PagingHandler[FleetspacesClientListByFleetResponse]{ + More: func(page FleetspacesClientListByFleetResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *FleetspacesClientListByFleetResponse) (FleetspacesClientListByFleetResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "FleetspacesClient.NewListByFleetPager") + 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.listByFleetCreateRequest(ctx, resourceGroupName, fleetName, options) + }, nil) + if err != nil { + return FleetspacesClientListByFleetResponse{}, err + } + return client.listByFleetHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByFleetCreateRequest creates the ListByFleet request. +func (client *FleetspacesClient) listByFleetCreateRequest(ctx context.Context, resourceGroupName string, fleetName string, options *FleetspacesClientListByFleetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DatabaseFleetManager/fleets/{fleetName}/fleetspaces" + 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 fleetName == "" { + return nil, errors.New("parameter fleetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{fleetName}", url.PathEscape(fleetName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Skip != nil { + reqQP.Set("$skip", strconv.FormatInt(*options.Skip, 10)) + } + if options != nil && options.Skiptoken != nil { + reqQP.Set("$skiptoken", *options.Skiptoken) + } + if options != nil && options.Top != nil { + reqQP.Set("$top", strconv.FormatInt(*options.Top, 10)) + } + reqQP.Set("api-version", "2025-02-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByFleetHandleResponse handles the ListByFleet response. +func (client *FleetspacesClient) listByFleetHandleResponse(resp *http.Response) (FleetspacesClientListByFleetResponse, error) { + result := FleetspacesClientListByFleetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.FleetspaceListResult); err != nil { + return FleetspacesClientListByFleetResponse{}, err + } + return result, nil +} + +// BeginRegisterServer - Migrates an existing logical server into fleet. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2025-02-01-preview +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - fleetName - Name of the database fleet. +// - fleetspaceName - Name of the fleetspace. +// - body - The details of the register server operation. +// - options - FleetspacesClientBeginRegisterServerOptions contains the optional parameters for the FleetspacesClient.BeginRegisterServer +// method. +func (client *FleetspacesClient) BeginRegisterServer(ctx context.Context, resourceGroupName string, fleetName string, fleetspaceName string, body RegisterServerProperties, options *FleetspacesClientBeginRegisterServerOptions) (*runtime.Poller[FleetspacesClientRegisterServerResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.registerServer(ctx, resourceGroupName, fleetName, fleetspaceName, body, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[FleetspacesClientRegisterServerResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[FleetspacesClientRegisterServerResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// RegisterServer - Migrates an existing logical server into fleet. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2025-02-01-preview +func (client *FleetspacesClient) registerServer(ctx context.Context, resourceGroupName string, fleetName string, fleetspaceName string, body RegisterServerProperties, options *FleetspacesClientBeginRegisterServerOptions) (*http.Response, error) { + var err error + const operationName = "FleetspacesClient.BeginRegisterServer" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.registerServerCreateRequest(ctx, resourceGroupName, fleetName, fleetspaceName, body, 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) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// registerServerCreateRequest creates the RegisterServer request. +func (client *FleetspacesClient) registerServerCreateRequest(ctx context.Context, resourceGroupName string, fleetName string, fleetspaceName string, body RegisterServerProperties, _ *FleetspacesClientBeginRegisterServerOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DatabaseFleetManager/fleets/{fleetName}/fleetspaces/{fleetspaceName}/registerServer" + 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 fleetName == "" { + return nil, errors.New("parameter fleetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{fleetName}", url.PathEscape(fleetName)) + if fleetspaceName == "" { + return nil, errors.New("parameter fleetspaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{fleetspaceName}", url.PathEscape(fleetspaceName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2025-02-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// BeginUnregister - Unregisters all databases from a fleetspace +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2025-02-01-preview +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - fleetName - Name of the database fleet. +// - fleetspaceName - Name of the fleetspace. +// - options - FleetspacesClientBeginUnregisterOptions contains the optional parameters for the FleetspacesClient.BeginUnregister +// method. +func (client *FleetspacesClient) BeginUnregister(ctx context.Context, resourceGroupName string, fleetName string, fleetspaceName string, options *FleetspacesClientBeginUnregisterOptions) (*runtime.Poller[FleetspacesClientUnregisterResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.unregister(ctx, resourceGroupName, fleetName, fleetspaceName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[FleetspacesClientUnregisterResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[FleetspacesClientUnregisterResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Unregister - Unregisters all databases from a fleetspace +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2025-02-01-preview +func (client *FleetspacesClient) unregister(ctx context.Context, resourceGroupName string, fleetName string, fleetspaceName string, options *FleetspacesClientBeginUnregisterOptions) (*http.Response, error) { + var err error + const operationName = "FleetspacesClient.BeginUnregister" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.unregisterCreateRequest(ctx, resourceGroupName, fleetName, fleetspaceName, 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) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// unregisterCreateRequest creates the Unregister request. +func (client *FleetspacesClient) unregisterCreateRequest(ctx context.Context, resourceGroupName string, fleetName string, fleetspaceName string, _ *FleetspacesClientBeginUnregisterOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DatabaseFleetManager/fleets/{fleetName}/fleetspaces/{fleetspaceName}/unregister" + 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 fleetName == "" { + return nil, errors.New("parameter fleetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{fleetName}", url.PathEscape(fleetName)) + if fleetspaceName == "" { + return nil, errors.New("parameter fleetspaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{fleetspaceName}", url.PathEscape(fleetspaceName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2025-02-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// BeginUpdate - Modifies a fleetspace resource. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2025-02-01-preview +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - fleetName - Name of the database fleet. +// - fleetspaceName - Name of the fleetspace. +// - properties - The resource properties to be updated. +// - options - FleetspacesClientBeginUpdateOptions contains the optional parameters for the FleetspacesClient.BeginUpdate method. +func (client *FleetspacesClient) BeginUpdate(ctx context.Context, resourceGroupName string, fleetName string, fleetspaceName string, properties Fleetspace, options *FleetspacesClientBeginUpdateOptions) (*runtime.Poller[FleetspacesClientUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.update(ctx, resourceGroupName, fleetName, fleetspaceName, properties, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[FleetspacesClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[FleetspacesClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Update - Modifies a fleetspace resource. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2025-02-01-preview +func (client *FleetspacesClient) update(ctx context.Context, resourceGroupName string, fleetName string, fleetspaceName string, properties Fleetspace, options *FleetspacesClientBeginUpdateOptions) (*http.Response, error) { + var err error + const operationName = "FleetspacesClient.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, fleetName, fleetspaceName, 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 *FleetspacesClient) updateCreateRequest(ctx context.Context, resourceGroupName string, fleetName string, fleetspaceName string, properties Fleetspace, _ *FleetspacesClientBeginUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DatabaseFleetManager/fleets/{fleetName}/fleetspaces/{fleetspaceName}" + 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 fleetName == "" { + return nil, errors.New("parameter fleetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{fleetName}", url.PathEscape(fleetName)) + if fleetspaceName == "" { + return nil, errors.New("parameter fleetspaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{fleetspaceName}", url.PathEscape(fleetspaceName)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2025-02-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, properties); err != nil { + return nil, err + } + return req, nil +} diff --git a/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager/fleetspaces_client_example_test.go b/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager/fleetspaces_client_example_test.go new file mode 100644 index 000000000000..6193cffa4759 --- /dev/null +++ b/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager/fleetspaces_client_example_test.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) Go Code Generator. DO NOT EDIT. + +package armdatabasefleetmanager_test + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/Azure/azure-sdk-for-go/sdk/azidentity" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager" + "log" +) + +// Generated from example definition: 2025-02-01-preview/Fleetspaces_CreateOrUpdate_MaximumSet_Gen.json +func ExampleFleetspacesClient_BeginCreateOrUpdate() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armdatabasefleetmanager.NewClientFactory("C3897315-3847-4D8A-B2FC-7307B066AD63", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + poller, err := clientFactory.NewFleetspacesClient().BeginCreateOrUpdate(ctx, "rgdatabasefleetmanager", "production-fleet", "primary-space", armdatabasefleetmanager.Fleetspace{ + Properties: &armdatabasefleetmanager.FleetspaceProperties{ + CapacityMax: to.Ptr[int32](150000), + MainPrincipal: &armdatabasefleetmanager.MainPrincipal{ + Login: to.Ptr("adminUser"), + ApplicationID: to.Ptr("d2d8b19e-c4f7-4c62-8e8d-7f0f96d94e39"), + ObjectID: to.Ptr("f8b7c2d3-b9c4-4f3b-85cd-3d56c6e49f92"), + TenantID: to.Ptr("bde45d44-ec42-45b8-a5a2-c5b998c65ef6"), + PrincipalType: to.Ptr(armdatabasefleetmanager.PrincipalTypeApplication), + }, + }, + }, nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + res, err := poller.PollUntilDone(ctx, nil) + if err != nil { + log.Fatalf("failed to pull the result: %v", err) + } + // You could use response here. We use blank identifier for just demo purposes. + _ = res + // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // res = armdatabasefleetmanager.FleetspacesClientCreateOrUpdateResponse{ + // Fleetspace: &armdatabasefleetmanager.Fleetspace{ + // Properties: &armdatabasefleetmanager.FleetspaceProperties{ + // ProvisioningState: to.Ptr(armdatabasefleetmanager.AzureProvisioningStateSucceeded), + // CapacityMax: to.Ptr[int32](150000), + // MainPrincipal: &armdatabasefleetmanager.MainPrincipal{ + // Login: to.Ptr("adminUser"), + // ApplicationID: to.Ptr("d2d8b19e-c4f7-4c62-8e8d-7f0f96d94e39"), + // ObjectID: to.Ptr("f8b7c2d3-b9c4-4f3b-85cd-3d56c6e49f92"), + // TenantID: to.Ptr("bde45d44-ec42-45b8-a5a2-c5b998c65ef6"), + // PrincipalType: to.Ptr(armdatabasefleetmanager.PrincipalTypeApplication), + // }, + // }, + // ID: to.Ptr("/subscriptions/C3897315-3847-4D8A-B2FC-7307B066AD63/resourceGroups/rg-database-operations/providers/Microsoft.DatabaseFleetManager/fleet/fleet-01/fleetspace/primary-space"), + // Name: to.Ptr("customer-db-prod"), + // Type: to.Ptr("Microsoft.DatabaseFleetManager/fleets/fleetspaces"), + // SystemData: &armdatabasefleetmanager.SystemData{ + // CreatedBy: to.Ptr("adminUser"), + // CreatedByType: to.Ptr(armdatabasefleetmanager.CreatedByTypeUser), + // CreatedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2024-11-06T09:16:01.802Z"); return t}()), + // LastModifiedBy: to.Ptr("adminUser"), + // LastModifiedByType: to.Ptr(armdatabasefleetmanager.CreatedByTypeUser), + // LastModifiedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2024-11-06T09:16:01.803Z"); return t}()), + // }, + // }, + // } +} + +// Generated from example definition: 2025-02-01-preview/Fleetspaces_Delete_MaximumSet_Gen.json +func ExampleFleetspacesClient_BeginDelete() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armdatabasefleetmanager.NewClientFactory("C3897315-3847-4D8A-B2FC-7307B066AD63", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + poller, err := clientFactory.NewFleetspacesClient().BeginDelete(ctx, "rgdatabasefleetmanager", "production-fleet", "primary-space", nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + _, err = poller.PollUntilDone(ctx, nil) + if err != nil { + log.Fatalf("failed to pull the result: %v", err) + } +} + +// Generated from example definition: 2025-02-01-preview/Fleetspaces_Get_MaximumSet_Gen.json +func ExampleFleetspacesClient_Get() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armdatabasefleetmanager.NewClientFactory("C3897315-3847-4D8A-B2FC-7307B066AD63", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + res, err := clientFactory.NewFleetspacesClient().Get(ctx, "rgdatabasefleetmanager", "production-fleet", "primary-space", nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + // You could use response here. We use blank identifier for just demo purposes. + _ = res + // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // res = armdatabasefleetmanager.FleetspacesClientGetResponse{ + // Fleetspace: &armdatabasefleetmanager.Fleetspace{ + // Properties: &armdatabasefleetmanager.FleetspaceProperties{ + // ProvisioningState: to.Ptr(armdatabasefleetmanager.AzureProvisioningStateSucceeded), + // CapacityMax: to.Ptr[int32](13), + // MainPrincipal: &armdatabasefleetmanager.MainPrincipal{ + // Login: to.Ptr("xijrmaod"), + // ApplicationID: to.Ptr("d2d8b19e-c4f7-4c62-8e8d-7f0f96d94e39"), + // ObjectID: to.Ptr("f8b7c2d3-b9c4-4f3b-85cd-3d56c6e49f92"), + // TenantID: to.Ptr("bde45d44-ec42-45b8-a5a2-c5b998c65ef6"), + // PrincipalType: to.Ptr(armdatabasefleetmanager.PrincipalTypeApplication), + // }, + // }, + // ID: to.Ptr("/subscriptions/C3897315-3847-4D8A-B2FC-7307B066AD63/resourceGroups/rg-database-operations/providers/Microsoft.DatabaseFleetManager/fleet/fleet-01/fleetspace/primary-space"), + // Name: to.Ptr("customer-db-prod"), + // Type: to.Ptr("Microsoft.DatabaseFleetManager/fleets/fleetspaces"), + // SystemData: &armdatabasefleetmanager.SystemData{ + // CreatedBy: to.Ptr("ckmcfjpuwvncpuluhk"), + // CreatedByType: to.Ptr(armdatabasefleetmanager.CreatedByTypeUser), + // CreatedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2024-11-06T09:16:01.802Z"); return t}()), + // LastModifiedBy: to.Ptr("o"), + // LastModifiedByType: to.Ptr(armdatabasefleetmanager.CreatedByTypeUser), + // LastModifiedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2024-11-06T09:16:01.803Z"); return t}()), + // }, + // }, + // } +} + +// Generated from example definition: 2025-02-01-preview/Fleetspaces_ListByFleet_MaximumSet_Gen.json +func ExampleFleetspacesClient_NewListByFleetPager() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armdatabasefleetmanager.NewClientFactory("C3897315-3847-4D8A-B2FC-7307B066AD63", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + pager := clientFactory.NewFleetspacesClient().NewListByFleetPager("rg-database-fleet-manager", "production-fleet", &FleetspacesClientListByFleetOptions{ + Skip: to.Ptr[int64](27), + Top: to.Ptr[int64](7), + Skiptoken: to.Ptr("qaorjlbhvuntmn")}) + for pager.More() { + page, err := pager.NextPage(ctx) + if err != nil { + log.Fatalf("failed to advance page: %v", err) + } + for _, v := range page.Value { + // You could use page here. We use blank identifier for just demo purposes. + _ = v + } + // If the HTTP response code is 200 as defined in example definition, your page structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // page = armdatabasefleetmanager.FleetspacesClientListByFleetResponse{ + // FleetspaceListResult: armdatabasefleetmanager.FleetspaceListResult{ + // Value: []*armdatabasefleetmanager.Fleetspace{ + // { + // Properties: &armdatabasefleetmanager.FleetspaceProperties{ + // ProvisioningState: to.Ptr(armdatabasefleetmanager.AzureProvisioningStateSucceeded), + // CapacityMax: to.Ptr[int32](1000), + // MainPrincipal: &armdatabasefleetmanager.MainPrincipal{ + // Login: to.Ptr("admin-prod"), + // ApplicationID: to.Ptr("d2d8b19e-c4f7-4c62-8e8d-7f0f96d94e39"), + // ObjectID: to.Ptr("f8b7c2d3-b9c4-4f3b-85cd-3d56c6e49f92"), + // TenantID: to.Ptr("bde45d44-ec42-45b8-a5a2-c5b998c65ef6"), + // PrincipalType: to.Ptr(armdatabasefleetmanager.PrincipalTypeApplication), + // }, + // }, + // ID: to.Ptr("/subscriptions/C3897315-3847-4D8A-B2FC-7307B066AD63/resourceGroups/rg-database-operations/providers/Microsoft.DatabaseFleetManager/fleet/fleet-01/fleetspace/primary-space"), + // Name: to.Ptr("customer-db-prod"), + // Type: to.Ptr("Microsoft.DatabaseFleetManager/fleets/fleetspaces"), + // SystemData: &armdatabasefleetmanager.SystemData{ + // CreatedBy: to.Ptr("john.doe@company.com"), + // CreatedByType: to.Ptr(armdatabasefleetmanager.CreatedByTypeUser), + // CreatedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2024-11-06T09:16:01.802Z"); return t}()), + // LastModifiedBy: to.Ptr("jane.smith@company.com"), + // LastModifiedByType: to.Ptr(armdatabasefleetmanager.CreatedByTypeUser), + // LastModifiedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2024-11-06T09:16:01.803Z"); return t}()), + // }, + // }, + // }, + // NextLink: to.Ptr("https://microsoft.com/a"), + // }, + // } + } +} + +// Generated from example definition: 2025-02-01-preview/Fleetspaces_RegisterServer_MaximumSet_Gen.json +func ExampleFleetspacesClient_BeginRegisterServer() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armdatabasefleetmanager.NewClientFactory("C3897315-3847-4D8A-B2FC-7307B066AD63", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + poller, err := clientFactory.NewFleetspacesClient().BeginRegisterServer(ctx, "rg-database-fleet-manager", "production-fleet", "primary-space", armdatabasefleetmanager.RegisterServerProperties{ + TierName: to.Ptr("Standard"), + SourceSubscriptionID: to.Ptr("c76e2b32-46c7-4325-8f4f-476828a5b207"), + SourceResourceGroupName: to.Ptr("rg-source-database"), + SourceServerName: to.Ptr("source-db-server-prod"), + DestinationTierOverrides: []*armdatabasefleetmanager.DestinationTierOverride{ + { + ResourceType: to.Ptr(armdatabasefleetmanager.ResourceTypeDatabase), + TierName: to.Ptr("bronze"), + ResourceName: to.Ptr("source-db-prod"), + }, + }, + }, nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + _, err = poller.PollUntilDone(ctx, nil) + if err != nil { + log.Fatalf("failed to pull the result: %v", err) + } +} + +// Generated from example definition: 2025-02-01-preview/Fleetspaces_Unregister_MaximumSet_Gen.json +func ExampleFleetspacesClient_BeginUnregister() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armdatabasefleetmanager.NewClientFactory("C3897315-3847-4D8A-B2FC-7307B066AD63", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + poller, err := clientFactory.NewFleetspacesClient().BeginUnregister(ctx, "rg-database-fleet-manager", "production-fleet", "primary-space", nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + _, err = poller.PollUntilDone(ctx, nil) + if err != nil { + log.Fatalf("failed to pull the result: %v", err) + } +} + +// Generated from example definition: 2025-02-01-preview/Fleetspaces_Update_MaximumSet_Gen.json +func ExampleFleetspacesClient_BeginUpdate() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armdatabasefleetmanager.NewClientFactory("C3897315-3847-4D8A-B2FC-7307B066AD63", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + poller, err := clientFactory.NewFleetspacesClient().BeginUpdate(ctx, "rg-database-fleet-manager", "production-fleet", "primary-space", armdatabasefleetmanager.Fleetspace{ + Properties: &armdatabasefleetmanager.FleetspaceProperties{ + CapacityMax: to.Ptr[int32](150000), + MainPrincipal: &armdatabasefleetmanager.MainPrincipal{ + Login: to.Ptr("adminUser"), + ApplicationID: to.Ptr("d2d8b19e-c4f7-4c62-8e8d-7f0f96d94e39"), + ObjectID: to.Ptr("f8b7c2d3-b9c4-4f3b-85cd-3d56c6e49f92"), + TenantID: to.Ptr("bde45d44-ec42-45b8-a5a2-c5b998c65ef6"), + PrincipalType: to.Ptr(armdatabasefleetmanager.PrincipalTypeApplication), + }, + }, + }, nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + res, err := poller.PollUntilDone(ctx, nil) + if err != nil { + log.Fatalf("failed to pull the result: %v", err) + } + // You could use response here. We use blank identifier for just demo purposes. + _ = res + // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // res = armdatabasefleetmanager.FleetspacesClientUpdateResponse{ + // Fleetspace: &armdatabasefleetmanager.Fleetspace{ + // Properties: &armdatabasefleetmanager.FleetspaceProperties{ + // ProvisioningState: to.Ptr(armdatabasefleetmanager.AzureProvisioningStateSucceeded), + // CapacityMax: to.Ptr[int32](150000), + // MainPrincipal: &armdatabasefleetmanager.MainPrincipal{ + // Login: to.Ptr("adminUser"), + // ApplicationID: to.Ptr("d2d8b19e-c4f7-4c62-8e8d-7f0f96d94e39"), + // ObjectID: to.Ptr("f8b7c2d3-b9c4-4f3b-85cd-3d56c6e49f92"), + // TenantID: to.Ptr("bde45d44-ec42-45b8-a5a2-c5b998c65ef6"), + // PrincipalType: to.Ptr(armdatabasefleetmanager.PrincipalTypeApplication), + // }, + // }, + // ID: to.Ptr("/subscriptions/C3897315-3847-4D8A-B2FC-7307B066AD63/resourceGroups/rg-database-operations/providers/Microsoft.DatabaseFleetManager/fleet/fleet-01/fleetspace/primary-space"), + // Name: to.Ptr("customer-db-prod"), + // Type: to.Ptr("Microsoft.DatabaseFleetManager/fleets/fleetspaces"), + // SystemData: &armdatabasefleetmanager.SystemData{ + // CreatedBy: to.Ptr("adminUser"), + // CreatedByType: to.Ptr(armdatabasefleetmanager.CreatedByTypeUser), + // CreatedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2024-11-06T09:16:01.802Z"); return t}()), + // LastModifiedBy: to.Ptr("adminUser"), + // LastModifiedByType: to.Ptr(armdatabasefleetmanager.CreatedByTypeUser), + // LastModifiedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2024-11-06T09:16:01.803Z"); return t}()), + // }, + // }, + // } +} diff --git a/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager/fleettiers_client.go b/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager/fleettiers_client.go new file mode 100644 index 000000000000..14386cb5005a --- /dev/null +++ b/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager/fleettiers_client.go @@ -0,0 +1,504 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armdatabasefleetmanager + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strconv" + "strings" +) + +// FleetTiersClient contains the methods for the FleetTiers group. +// Don't use this type directly, use NewFleetTiersClient() instead. +type FleetTiersClient struct { + internal *arm.Client + subscriptionID string +} + +// NewFleetTiersClient creates a new instance of FleetTiersClient 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 NewFleetTiersClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*FleetTiersClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &FleetTiersClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Creates or updates a tier. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2025-02-01-preview +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - fleetName - Name of the database fleet. +// - tierName - Name of the tier. +// - resource - The tier object to create or update. +// - options - FleetTiersClientBeginCreateOrUpdateOptions contains the optional parameters for the FleetTiersClient.BeginCreateOrUpdate +// method. +func (client *FleetTiersClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, fleetName string, tierName string, resource FleetTier, options *FleetTiersClientBeginCreateOrUpdateOptions) (*runtime.Poller[FleetTiersClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, fleetName, tierName, resource, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[FleetTiersClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[FleetTiersClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Creates or updates a tier. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2025-02-01-preview +func (client *FleetTiersClient) createOrUpdate(ctx context.Context, resourceGroupName string, fleetName string, tierName string, resource FleetTier, options *FleetTiersClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "FleetTiersClient.BeginCreateOrUpdate" + 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, fleetName, tierName, 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 +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *FleetTiersClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, fleetName string, tierName string, resource FleetTier, _ *FleetTiersClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DatabaseFleetManager/fleets/{fleetName}/tiers/{tierName}" + 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 fleetName == "" { + return nil, errors.New("parameter fleetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{fleetName}", url.PathEscape(fleetName)) + if tierName == "" { + return nil, errors.New("parameter tierName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{tierName}", url.PathEscape(tierName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2025-02-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, resource); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Deletes a tier. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2025-02-01-preview +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - fleetName - Name of the database fleet. +// - tierName - Name of the tier. +// - options - FleetTiersClientBeginDeleteOptions contains the optional parameters for the FleetTiersClient.BeginDelete method. +func (client *FleetTiersClient) BeginDelete(ctx context.Context, resourceGroupName string, fleetName string, tierName string, options *FleetTiersClientBeginDeleteOptions) (*runtime.Poller[FleetTiersClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, fleetName, tierName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[FleetTiersClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[FleetTiersClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes a tier. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2025-02-01-preview +func (client *FleetTiersClient) deleteOperation(ctx context.Context, resourceGroupName string, fleetName string, tierName string, options *FleetTiersClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "FleetTiersClient.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, fleetName, tierName, 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 *FleetTiersClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, fleetName string, tierName string, _ *FleetTiersClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DatabaseFleetManager/fleets/{fleetName}/tiers/{tierName}" + 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 fleetName == "" { + return nil, errors.New("parameter fleetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{fleetName}", url.PathEscape(fleetName)) + if tierName == "" { + return nil, errors.New("parameter tierName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{tierName}", url.PathEscape(tierName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2025-02-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Disable - Disables a tier. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2025-02-01-preview +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - fleetName - Name of the database fleet. +// - tierName - Name of the tier. +// - options - FleetTiersClientDisableOptions contains the optional parameters for the FleetTiersClient.Disable method. +func (client *FleetTiersClient) Disable(ctx context.Context, resourceGroupName string, fleetName string, tierName string, options *FleetTiersClientDisableOptions) (FleetTiersClientDisableResponse, error) { + var err error + const operationName = "FleetTiersClient.Disable" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.disableCreateRequest(ctx, resourceGroupName, fleetName, tierName, options) + if err != nil { + return FleetTiersClientDisableResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return FleetTiersClientDisableResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return FleetTiersClientDisableResponse{}, err + } + resp, err := client.disableHandleResponse(httpResp) + return resp, err +} + +// disableCreateRequest creates the Disable request. +func (client *FleetTiersClient) disableCreateRequest(ctx context.Context, resourceGroupName string, fleetName string, tierName string, _ *FleetTiersClientDisableOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DatabaseFleetManager/fleets/{fleetName}/tiers/{tierName}/disable" + 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 fleetName == "" { + return nil, errors.New("parameter fleetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{fleetName}", url.PathEscape(fleetName)) + if tierName == "" { + return nil, errors.New("parameter tierName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{tierName}", url.PathEscape(tierName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2025-02-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// disableHandleResponse handles the Disable response. +func (client *FleetTiersClient) disableHandleResponse(resp *http.Response) (FleetTiersClientDisableResponse, error) { + result := FleetTiersClientDisableResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.FleetTier); err != nil { + return FleetTiersClientDisableResponse{}, err + } + return result, nil +} + +// Get - Gets a tier resource. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2025-02-01-preview +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - fleetName - Name of the database fleet. +// - tierName - Name of the tier. +// - options - FleetTiersClientGetOptions contains the optional parameters for the FleetTiersClient.Get method. +func (client *FleetTiersClient) Get(ctx context.Context, resourceGroupName string, fleetName string, tierName string, options *FleetTiersClientGetOptions) (FleetTiersClientGetResponse, error) { + var err error + const operationName = "FleetTiersClient.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, fleetName, tierName, options) + if err != nil { + return FleetTiersClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return FleetTiersClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return FleetTiersClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *FleetTiersClient) getCreateRequest(ctx context.Context, resourceGroupName string, fleetName string, tierName string, _ *FleetTiersClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DatabaseFleetManager/fleets/{fleetName}/tiers/{tierName}" + 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 fleetName == "" { + return nil, errors.New("parameter fleetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{fleetName}", url.PathEscape(fleetName)) + if tierName == "" { + return nil, errors.New("parameter tierName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{tierName}", url.PathEscape(tierName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2025-02-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 *FleetTiersClient) getHandleResponse(resp *http.Response) (FleetTiersClientGetResponse, error) { + result := FleetTiersClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.FleetTier); err != nil { + return FleetTiersClientGetResponse{}, err + } + return result, nil +} + +// NewListByFleetPager - List tiers in a fleet. +// +// Generated from API version 2025-02-01-preview +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - fleetName - Name of the database fleet. +// - options - FleetTiersClientListByFleetOptions contains the optional parameters for the FleetTiersClient.NewListByFleetPager +// method. +func (client *FleetTiersClient) NewListByFleetPager(resourceGroupName string, fleetName string, options *FleetTiersClientListByFleetOptions) *runtime.Pager[FleetTiersClientListByFleetResponse] { + return runtime.NewPager(runtime.PagingHandler[FleetTiersClientListByFleetResponse]{ + More: func(page FleetTiersClientListByFleetResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *FleetTiersClientListByFleetResponse) (FleetTiersClientListByFleetResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "FleetTiersClient.NewListByFleetPager") + 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.listByFleetCreateRequest(ctx, resourceGroupName, fleetName, options) + }, nil) + if err != nil { + return FleetTiersClientListByFleetResponse{}, err + } + return client.listByFleetHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByFleetCreateRequest creates the ListByFleet request. +func (client *FleetTiersClient) listByFleetCreateRequest(ctx context.Context, resourceGroupName string, fleetName string, options *FleetTiersClientListByFleetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DatabaseFleetManager/fleets/{fleetName}/tiers" + 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 fleetName == "" { + return nil, errors.New("parameter fleetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{fleetName}", url.PathEscape(fleetName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Skip != nil { + reqQP.Set("$skip", strconv.FormatInt(*options.Skip, 10)) + } + if options != nil && options.Skiptoken != nil { + reqQP.Set("$skiptoken", *options.Skiptoken) + } + if options != nil && options.Top != nil { + reqQP.Set("$top", strconv.FormatInt(*options.Top, 10)) + } + reqQP.Set("api-version", "2025-02-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByFleetHandleResponse handles the ListByFleet response. +func (client *FleetTiersClient) listByFleetHandleResponse(resp *http.Response) (FleetTiersClientListByFleetResponse, error) { + result := FleetTiersClientListByFleetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.FleetTierListResult); err != nil { + return FleetTiersClientListByFleetResponse{}, err + } + return result, nil +} + +// BeginUpdate - Updates a tier. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2025-02-01-preview +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - fleetName - Name of the database fleet. +// - tierName - Name of the tier. +// - properties - The resource properties to be updated. +// - options - FleetTiersClientBeginUpdateOptions contains the optional parameters for the FleetTiersClient.BeginUpdate method. +func (client *FleetTiersClient) BeginUpdate(ctx context.Context, resourceGroupName string, fleetName string, tierName string, properties FleetTier, options *FleetTiersClientBeginUpdateOptions) (*runtime.Poller[FleetTiersClientUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.update(ctx, resourceGroupName, fleetName, tierName, properties, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[FleetTiersClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[FleetTiersClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Update - Updates a tier. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2025-02-01-preview +func (client *FleetTiersClient) update(ctx context.Context, resourceGroupName string, fleetName string, tierName string, properties FleetTier, options *FleetTiersClientBeginUpdateOptions) (*http.Response, error) { + var err error + const operationName = "FleetTiersClient.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, fleetName, tierName, 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 *FleetTiersClient) updateCreateRequest(ctx context.Context, resourceGroupName string, fleetName string, tierName string, properties FleetTier, _ *FleetTiersClientBeginUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DatabaseFleetManager/fleets/{fleetName}/tiers/{tierName}" + 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 fleetName == "" { + return nil, errors.New("parameter fleetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{fleetName}", url.PathEscape(fleetName)) + if tierName == "" { + return nil, errors.New("parameter tierName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{tierName}", url.PathEscape(tierName)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2025-02-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, properties); err != nil { + return nil, err + } + return req, nil +} diff --git a/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager/fleettiers_client_example_test.go b/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager/fleettiers_client_example_test.go new file mode 100644 index 000000000000..ec17931946dc --- /dev/null +++ b/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager/fleettiers_client_example_test.go @@ -0,0 +1,333 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armdatabasefleetmanager_test + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/Azure/azure-sdk-for-go/sdk/azidentity" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager" + "log" +) + +// Generated from example definition: 2025-02-01-preview/FleetTiers_CreateOrUpdate_MaximumSet_Gen.json +func ExampleFleetTiersClient_BeginCreateOrUpdate() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armdatabasefleetmanager.NewClientFactory("C3897315-3847-4D8A-B2FC-7307B066AD63", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + poller, err := clientFactory.NewFleetTiersClient().BeginCreateOrUpdate(ctx, "rg-database-fleet-manager", "critical-production-fleet", "general-purpose-tier", armdatabasefleetmanager.FleetTier{ + Properties: &armdatabasefleetmanager.FleetTierProperties{ + Serverless: to.Ptr(false), + Pooled: to.Ptr(true), + ServiceTier: to.Ptr("GeneralPurpose"), + Family: to.Ptr("Gen5"), + Capacity: to.Ptr[int32](4), + PoolNumOfDatabasesMax: to.Ptr[int32](10), + HighAvailabilityReplicaCount: to.Ptr[int32](5), + ZoneRedundancy: to.Ptr(armdatabasefleetmanager.ZoneRedundancyDisabled), + DatabaseCapacityMin: to.Ptr[float64](0), + DatabaseCapacityMax: to.Ptr[float64](4), + DatabaseSizeGbMax: to.Ptr[int32](50), + }, + }, nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + res, err := poller.PollUntilDone(ctx, nil) + if err != nil { + log.Fatalf("failed to pull the result: %v", err) + } + // You could use response here. We use blank identifier for just demo purposes. + _ = res + // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // res = armdatabasefleetmanager.FleetTiersClientCreateOrUpdateResponse{ + // FleetTier: &armdatabasefleetmanager.FleetTier{ + // Properties: &armdatabasefleetmanager.FleetTierProperties{ + // Disabled: to.Ptr(false), + // Serverless: to.Ptr(false), + // Pooled: to.Ptr(true), + // ServiceTier: to.Ptr("GeneralPurpose"), + // Family: to.Ptr("Gen5"), + // Capacity: to.Ptr[int32](4), + // PoolNumOfDatabasesMax: to.Ptr[int32](10), + // HighAvailabilityReplicaCount: to.Ptr[int32](5), + // ZoneRedundancy: to.Ptr(armdatabasefleetmanager.ZoneRedundancyDisabled), + // DatabaseCapacityMin: to.Ptr[float64](0), + // DatabaseCapacityMax: to.Ptr[float64](4), + // DatabaseSizeGbMax: to.Ptr[int32](50), + // ProvisioningState: to.Ptr(armdatabasefleetmanager.AzureProvisioningStateSucceeded), + // }, + // ID: to.Ptr("/subscriptions/C3897315-3847-4D8A-B2FC-7307B066AD63/resourceGroups/rg-database-fleet-manager/providers/Microsoft.DatabaseFleetManager/fleets/critical-production-fleet/tiers/general-purpose-tier"), + // Name: to.Ptr("general-purpose-tier"), + // Type: to.Ptr("Microsoft.DatabaseFleetManager/fleets/tiers"), + // SystemData: &armdatabasefleetmanager.SystemData{ + // CreatedBy: to.Ptr("adminuser"), + // CreatedByType: to.Ptr(armdatabasefleetmanager.CreatedByTypeUser), + // CreatedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2024-11-06T09:16:01.802Z"); return t}()), + // LastModifiedBy: to.Ptr("adminuser"), + // LastModifiedByType: to.Ptr(armdatabasefleetmanager.CreatedByTypeUser), + // LastModifiedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2024-11-06T09:16:01.803Z"); return t}()), + // }, + // }, + // } +} + +// Generated from example definition: 2025-02-01-preview/FleetTiers_Delete_MaximumSet_Gen.json +func ExampleFleetTiersClient_BeginDelete() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armdatabasefleetmanager.NewClientFactory("C3897315-3847-4D8A-B2FC-7307B066AD63", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + poller, err := clientFactory.NewFleetTiersClient().BeginDelete(ctx, "rg-database-fleet-manager", "critical-production-fleet", "general-purpose-tier", nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + _, err = poller.PollUntilDone(ctx, nil) + if err != nil { + log.Fatalf("failed to pull the result: %v", err) + } +} + +// Generated from example definition: 2025-02-01-preview/FleetTiers_Disable_MaximumSet_Gen.json +func ExampleFleetTiersClient_Disable() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armdatabasefleetmanager.NewClientFactory("C3897315-3847-4D8A-B2FC-7307B066AD63", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + res, err := clientFactory.NewFleetTiersClient().Disable(ctx, "rg-database-fleet-manager", "critical-production-fleet", "general-purpose-tier", nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + // You could use response here. We use blank identifier for just demo purposes. + _ = res + // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // res = armdatabasefleetmanager.FleetTiersClientDisableResponse{ + // FleetTier: &armdatabasefleetmanager.FleetTier{ + // Properties: &armdatabasefleetmanager.FleetTierProperties{ + // Disabled: to.Ptr(false), + // Serverless: to.Ptr(false), + // Pooled: to.Ptr(true), + // ServiceTier: to.Ptr("GeneralPurpose"), + // Family: to.Ptr("Gen5"), + // Capacity: to.Ptr[int32](4), + // PoolNumOfDatabasesMax: to.Ptr[int32](10), + // HighAvailabilityReplicaCount: to.Ptr[int32](5), + // ZoneRedundancy: to.Ptr(armdatabasefleetmanager.ZoneRedundancyDisabled), + // DatabaseCapacityMin: to.Ptr[float64](0), + // DatabaseCapacityMax: to.Ptr[float64](4), + // DatabaseSizeGbMax: to.Ptr[int32](50), + // ProvisioningState: to.Ptr(armdatabasefleetmanager.AzureProvisioningStateSucceeded), + // }, + // ID: to.Ptr("/subscriptions/C3897315-3847-4D8A-B2FC-7307B066AD63/resourceGroups/rg-database-fleet-manager/providers/Microsoft.DatabaseFleetManager/fleets/critical-production-fleet/tiers/general-purpose-tier"), + // Name: to.Ptr("general-purpose-tier"), + // Type: to.Ptr("Microsoft.DatabaseFleetManager/fleets/tiers"), + // SystemData: &armdatabasefleetmanager.SystemData{ + // CreatedBy: to.Ptr("adminuser"), + // CreatedByType: to.Ptr(armdatabasefleetmanager.CreatedByTypeUser), + // CreatedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2024-11-06T09:16:01.802Z"); return t}()), + // LastModifiedBy: to.Ptr("adminuser"), + // LastModifiedByType: to.Ptr(armdatabasefleetmanager.CreatedByTypeUser), + // LastModifiedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2024-11-06T09:16:01.803Z"); return t}()), + // }, + // }, + // } +} + +// Generated from example definition: 2025-02-01-preview/FleetTiers_Get_MaximumSet_Gen.json +func ExampleFleetTiersClient_Get() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armdatabasefleetmanager.NewClientFactory("C3897315-3847-4D8A-B2FC-7307B066AD63", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + res, err := clientFactory.NewFleetTiersClient().Get(ctx, "rg-database-fleet-manager", "critical-production-fleet", "general-purpose-tier", nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + // You could use response here. We use blank identifier for just demo purposes. + _ = res + // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // res = armdatabasefleetmanager.FleetTiersClientGetResponse{ + // FleetTier: &armdatabasefleetmanager.FleetTier{ + // Properties: &armdatabasefleetmanager.FleetTierProperties{ + // Disabled: to.Ptr(false), + // Serverless: to.Ptr(false), + // Pooled: to.Ptr(true), + // ServiceTier: to.Ptr("GeneralPurpose"), + // Family: to.Ptr("Gen5"), + // Capacity: to.Ptr[int32](4), + // PoolNumOfDatabasesMax: to.Ptr[int32](10), + // HighAvailabilityReplicaCount: to.Ptr[int32](5), + // ZoneRedundancy: to.Ptr(armdatabasefleetmanager.ZoneRedundancyDisabled), + // DatabaseCapacityMin: to.Ptr[float64](0), + // DatabaseCapacityMax: to.Ptr[float64](4), + // DatabaseSizeGbMax: to.Ptr[int32](50), + // ProvisioningState: to.Ptr(armdatabasefleetmanager.AzureProvisioningStateSucceeded), + // }, + // ID: to.Ptr("/subscriptions/C3897315-3847-4D8A-B2FC-7307B066AD63/resourceGroups/rg-database-fleet-manager/providers/Microsoft.DatabaseFleetManager/fleets/critical-production-fleet/tiers/general-purpose-tier"), + // Name: to.Ptr("general-purpose-tier"), + // Type: to.Ptr("Microsoft.DatabaseFleetManager/fleets/tiers"), + // SystemData: &armdatabasefleetmanager.SystemData{ + // CreatedBy: to.Ptr("ckmcfjpuwvncpuluhk"), + // CreatedByType: to.Ptr(armdatabasefleetmanager.CreatedByTypeUser), + // CreatedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2024-11-06T09:16:01.802Z"); return t}()), + // LastModifiedBy: to.Ptr("o"), + // LastModifiedByType: to.Ptr(armdatabasefleetmanager.CreatedByTypeUser), + // LastModifiedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2024-11-06T09:16:01.803Z"); return t}()), + // }, + // }, + // } +} + +// Generated from example definition: 2025-02-01-preview/FleetTiers_ListByFleet_MaximumSet_Gen.json +func ExampleFleetTiersClient_NewListByFleetPager() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armdatabasefleetmanager.NewClientFactory("C3897315-3847-4D8A-B2FC-7307B066AD63", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + pager := clientFactory.NewFleetTiersClient().NewListByFleetPager("rg-database-fleet-manager", "critical-production-fleet", &FleetTiersClientListByFleetOptions{ + Skip: to.Ptr[int64](10), + Top: to.Ptr[int64](1), + Skiptoken: to.Ptr("hfrg")}) + for pager.More() { + page, err := pager.NextPage(ctx) + if err != nil { + log.Fatalf("failed to advance page: %v", err) + } + for _, v := range page.Value { + // You could use page here. We use blank identifier for just demo purposes. + _ = v + } + // If the HTTP response code is 200 as defined in example definition, your page structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // page = armdatabasefleetmanager.FleetTiersClientListByFleetResponse{ + // FleetTierListResult: armdatabasefleetmanager.FleetTierListResult{ + // Value: []*armdatabasefleetmanager.FleetTier{ + // { + // Properties: &armdatabasefleetmanager.FleetTierProperties{ + // Disabled: to.Ptr(false), + // Serverless: to.Ptr(false), + // Pooled: to.Ptr(true), + // ServiceTier: to.Ptr("GeneralPurpose"), + // Family: to.Ptr("Gen5"), + // Capacity: to.Ptr[int32](4), + // PoolNumOfDatabasesMax: to.Ptr[int32](10), + // HighAvailabilityReplicaCount: to.Ptr[int32](5), + // ZoneRedundancy: to.Ptr(armdatabasefleetmanager.ZoneRedundancyDisabled), + // DatabaseCapacityMin: to.Ptr[float64](0), + // DatabaseCapacityMax: to.Ptr[float64](4), + // DatabaseSizeGbMax: to.Ptr[int32](50), + // ProvisioningState: to.Ptr(armdatabasefleetmanager.AzureProvisioningStateSucceeded), + // }, + // ID: to.Ptr("/subscriptions/C3897315-3847-4D8A-B2FC-7307B066AD63/resourceGroups/rg-database-fleet-manager/providers/Microsoft.DatabaseFleetManager/fleets/critical-production-fleet/tiers/general-purpose-tier"), + // Name: to.Ptr("general-purpose-tier"), + // Type: to.Ptr("Microsoft.DatabaseFleetManager/fleets/tiers"), + // SystemData: &armdatabasefleetmanager.SystemData{ + // CreatedBy: to.Ptr("ckmcfjpuwvncpuluhk"), + // CreatedByType: to.Ptr(armdatabasefleetmanager.CreatedByTypeUser), + // CreatedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2024-11-06T09:16:01.802Z"); return t}()), + // LastModifiedBy: to.Ptr("o"), + // LastModifiedByType: to.Ptr(armdatabasefleetmanager.CreatedByTypeUser), + // LastModifiedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2024-11-06T09:16:01.803Z"); return t}()), + // }, + // }, + // }, + // NextLink: to.Ptr("https://microsoft.com/afucor"), + // }, + // } + } +} + +// Generated from example definition: 2025-02-01-preview/FleetTiers_Update_MaximumSet_Gen.json +func ExampleFleetTiersClient_BeginUpdate() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armdatabasefleetmanager.NewClientFactory("C3897315-3847-4D8A-B2FC-7307B066AD63", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + poller, err := clientFactory.NewFleetTiersClient().BeginUpdate(ctx, "rg-database-fleet-manager", "critical-production-fleet", "general-purpose-tier", armdatabasefleetmanager.FleetTier{ + Properties: &armdatabasefleetmanager.FleetTierProperties{ + Serverless: to.Ptr(false), + Pooled: to.Ptr(true), + ServiceTier: to.Ptr("GeneralPurpose"), + Family: to.Ptr("Gen5"), + Capacity: to.Ptr[int32](4), + PoolNumOfDatabasesMax: to.Ptr[int32](10), + HighAvailabilityReplicaCount: to.Ptr[int32](5), + ZoneRedundancy: to.Ptr(armdatabasefleetmanager.ZoneRedundancyDisabled), + DatabaseCapacityMin: to.Ptr[float64](0), + DatabaseCapacityMax: to.Ptr[float64](4), + DatabaseSizeGbMax: to.Ptr[int32](50), + }, + }, nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + res, err := poller.PollUntilDone(ctx, nil) + if err != nil { + log.Fatalf("failed to pull the result: %v", err) + } + // You could use response here. We use blank identifier for just demo purposes. + _ = res + // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // res = armdatabasefleetmanager.FleetTiersClientUpdateResponse{ + // FleetTier: &armdatabasefleetmanager.FleetTier{ + // Properties: &armdatabasefleetmanager.FleetTierProperties{ + // Disabled: to.Ptr(false), + // Serverless: to.Ptr(false), + // Pooled: to.Ptr(true), + // ServiceTier: to.Ptr("GeneralPurpose"), + // Family: to.Ptr("Gen5"), + // Capacity: to.Ptr[int32](4), + // PoolNumOfDatabasesMax: to.Ptr[int32](10), + // HighAvailabilityReplicaCount: to.Ptr[int32](5), + // ZoneRedundancy: to.Ptr(armdatabasefleetmanager.ZoneRedundancyDisabled), + // DatabaseCapacityMin: to.Ptr[float64](0), + // DatabaseCapacityMax: to.Ptr[float64](4), + // DatabaseSizeGbMax: to.Ptr[int32](50), + // ProvisioningState: to.Ptr(armdatabasefleetmanager.AzureProvisioningStateSucceeded), + // }, + // ID: to.Ptr("/subscriptions/C3897315-3847-4D8A-B2FC-7307B066AD63/resourceGroups/rg-database-fleet-manager/providers/Microsoft.DatabaseFleetManager/fleets/critical-production-fleet/tiers/general-purpose-tier"), + // Name: to.Ptr("general-purpose-tier"), + // Type: to.Ptr("Microsoft.DatabaseFleetManager/fleets/tiers"), + // SystemData: &armdatabasefleetmanager.SystemData{ + // CreatedBy: to.Ptr("ckmcfjpuwvncpuluhk"), + // CreatedByType: to.Ptr(armdatabasefleetmanager.CreatedByTypeUser), + // CreatedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2024-11-06T09:16:01.802Z"); return t}()), + // LastModifiedBy: to.Ptr("o"), + // LastModifiedByType: to.Ptr(armdatabasefleetmanager.CreatedByTypeUser), + // LastModifiedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2024-11-06T09:16:01.803Z"); return t}()), + // }, + // }, + // } +} diff --git a/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager/go.mod b/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager/go.mod new file mode 100644 index 000000000000..d2d8c8d8dd91 --- /dev/null +++ b/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager/go.mod @@ -0,0 +1,23 @@ +module github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager + +go 1.23.0 + +toolchain go1.23.8 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.17.1 + github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.7.0 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.10.0 // indirect + github.com/AzureAD/microsoft-authentication-library-for-go v1.2.2 // indirect + github.com/golang-jwt/jwt/v5 v5.2.1 // indirect + github.com/google/uuid v1.6.0 // indirect + github.com/kylelemons/godebug v1.1.0 // indirect + github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c // indirect + golang.org/x/crypto v0.36.0 // indirect + golang.org/x/net v0.37.0 // indirect + golang.org/x/sys v0.31.0 // indirect + golang.org/x/text v0.23.0 // indirect +) diff --git a/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager/go.sum b/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager/go.sum new file mode 100644 index 000000000000..1f92486fbbcf --- /dev/null +++ b/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager/go.sum @@ -0,0 +1,33 @@ +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/azidentity v1.7.0 h1:tfLQ34V6F7tVSwoTf/4lH5sE0o6eCJuNDTmH09nDpbc= +github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.7.0/go.mod h1:9kIvujWAA58nmPmWB1m23fyWic1kYZMxD9CxaWn4Qpg= +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/AzureAD/microsoft-authentication-library-for-go v1.2.2 h1:XHOnouVk1mxXfQidrMEnLlPk9UMeRtyBTnEFtxkV0kU= +github.com/AzureAD/microsoft-authentication-library-for-go v1.2.2/go.mod h1:wP83P5OoQ5p6ip3ScPr0BAq0BvuPAvacpEuSzyouqAI= +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/golang-jwt/jwt/v5 v5.2.1 h1:OuVbFODueb089Lh128TAcimifWaLhJwVflnrgM17wHk= +github.com/golang-jwt/jwt/v5 v5.2.1/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk= +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc= +github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= +github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c h1:+mdjkGKdHQG3305AYmdv1U2eRNDiU2ErMBj1gwrq8eQ= +github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c/go.mod h1:7rwL4CYBLnjLxUqIJNnCWiEdr3bn6IUYi15bNlnbCCU= +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/crypto v0.36.0 h1:AnAEvhDddvBdpY+uR+MyHmuZzzNqXSe/GvuDeob5L34= +golang.org/x/crypto v0.36.0/go.mod h1:Y4J0ReaxCR1IMaabaSMugxJES1EpwhBHhv2bDHklZvc= +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/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.31.0 h1:ioabZlmFYtWhL+TRYpcnNlLwhyxaM9kWTDEmfnprqik= +golang.org/x/sys v0.31.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= +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/databasefleetmanager/armdatabasefleetmanager/models.go b/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager/models.go new file mode 100644 index 000000000000..acd63345999c --- /dev/null +++ b/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager/models.go @@ -0,0 +1,451 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armdatabasefleetmanager + +import "time" + +// DatabaseChangeTierProperties - A database change tier definition. +type DatabaseChangeTierProperties struct { + // A target tier name. + TargetTierName *string +} + +// DatabaseIdentity - Database Identity properties. +type DatabaseIdentity struct { + // Client Id of the database identity. + ClientID *string + + // Principal Id of the database identity. + PrincipalID *string + + // Resource Id of the database identity. + ResourceID *string +} + +// DatabaseRenameProperties - A database rename definition. +type DatabaseRenameProperties struct { + // New database name. + NewName *string +} + +// DestinationTierOverride - A destination tier override. +type DestinationTierOverride struct { + // REQUIRED; Resource name. + ResourceName *string + + // REQUIRED; Resource type. + ResourceType *ResourceType + + // REQUIRED; Destination tier name. + TierName *string +} + +// FirewallRule - A firewall rule. +type FirewallRule struct { + // A Firewall rule properties. + Properties *FirewallRuleProperties + + // READ-ONLY; Name of the firewall rule. + Name *string + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *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 +} + +// FirewallRuleListResult - The response of a FirewallRule list operation. +type FirewallRuleListResult struct { + // REQUIRED; The FirewallRule items on this page + Value []*FirewallRule + + // The link to the next page of items + NextLink *string +} + +// FirewallRuleProperties - A Firewall rule properties. +type FirewallRuleProperties struct { + // End IP address. + EndIPAddress *string + + // Start IP address. + StartIPAddress *string + + // READ-ONLY; Provisioning state. + ProvisioningState *AzureProvisioningState +} + +// Fleet - A Database Fleet. +type Fleet struct { + // REQUIRED; The geo-location where the resource lives + Location *string + + // The fleet properties. + Properties *FleetProperties + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; Name of the database fleet. + Name *string + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *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 +} + +// FleetDatabase - A fleet database. +type FleetDatabase struct { + // Fleet database properties. + Properties *FleetDatabaseProperties + + // READ-ONLY; Name of the database. + Name *string + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *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 +} + +// FleetDatabaseListResult - The response of a FleetDatabase list operation. +type FleetDatabaseListResult struct { + // REQUIRED; The FleetDatabase items on this page + Value []*FleetDatabase + + // The link to the next page of items + NextLink *string +} + +// FleetDatabaseProperties - Fleet database properties. +type FleetDatabaseProperties struct { + // Database collation. + Collation *string + + // Create mode. Available options: Default - Create a database. Copy - Copy the source database (source database name must + // be specified) PointInTimeRestore - Create a database by restoring source database from a point in time (source database + // name and restore from time must be specified) + CreateMode *DatabaseCreateMode + + // Identity property. + Identity *Identity + + // Additional database properties to be applied as the underlying database resource tags. + ResourceTags map[string]*string + + // Restore from time when CreateMode is PointInTimeRestore. + RestoreFromTime *time.Time + + // Source database name used when CreateMode is Copy or PointInTimeRestore. + SourceDatabaseName *string + + // Name of the tier this database belongs to. + TierName *string + + // Transparent Data Encryption properties + TransparentDataEncryption *TransparentDataEncryption + + // READ-ONLY; Backup retention in days. + BackupRetentionDays *int32 + + // READ-ONLY; Connection string to connect to the database with. + ConnectionString *string + + // READ-ONLY; Maximum database size in Gb. + DatabaseSizeGbMax *int32 + + // READ-ONLY; Earliest restore time. + EarliestRestoreTime *time.Time + + // READ-ONLY; Latest restore time. + LatestRestoreTime *time.Time + + // READ-ONLY; Resource identifier for the underlying database resource. + OriginalDatabaseID *string + + // READ-ONLY; Database state. + ProvisioningState *AzureProvisioningState + + // READ-ONLY; If true, database is recoverable. + Recoverable *bool +} + +// FleetListResult - The response of a Fleet list operation. +type FleetListResult struct { + // REQUIRED; The Fleet items on this page + Value []*Fleet + + // The link to the next page of items + NextLink *string +} + +// FleetProperties - The Database Fleet properties. +type FleetProperties struct { + // Fleet description. + Description *string + + // READ-ONLY; Provisioning state. + ProvisioningState *AzureProvisioningState +} + +// FleetTier - A SQL Database Fleet tier. +type FleetTier struct { + // A Fleet tier properties. + Properties *FleetTierProperties + + // READ-ONLY; Name of the tier. + Name *string + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *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 +} + +// FleetTierListResult - The response of a FleetTier list operation. +type FleetTierListResult struct { + // REQUIRED; The FleetTier items on this page + Value []*FleetTier + + // The link to the next page of items + NextLink *string +} + +// FleetTierProperties - A Fleet tier properties. +type FleetTierProperties struct { + // Capacity of provisioned resources in the tier, in units matching the specified service tier, for example vCore for GeneralPurpose. + Capacity *int32 + + // Maximum allocated capacity per database, in units matching the specified service tier. + DatabaseCapacityMax *float64 + + // Minimum allocated capacity per database, in units matching the specified service tier. + DatabaseCapacityMin *float64 + + // Maximum database size in Gb. + DatabaseSizeGbMax *int32 + + // Family of provisioned resources, for example Gen5. + Family *string + + // Number of high availability replicas for databases in this tier. + HighAvailabilityReplicaCount *int32 + + // Maximum number of databases per pool. + PoolNumOfDatabasesMax *int32 + + // If true, databases are pooled. + Pooled *bool + + // If true, serverless resources are provisioned in the tier. + Serverless *bool + + // Service tier of provisioned resources. Supported values: GeneralPurpose, Hyperscale. + ServiceTier *string + + // Enable zone redundancy for all databases in this tier. + ZoneRedundancy *ZoneRedundancy + + // READ-ONLY; If true, tier is disabled. + Disabled *bool + + // READ-ONLY; Provisioning state. + ProvisioningState *AzureProvisioningState +} + +// FleetUpdate - An update to a Database Fleet. +type FleetUpdate struct { + // The Database Fleet properties. + Properties *FleetProperties + + // Resource tags. + Tags map[string]*string +} + +// Fleetspace - A fleetspace. +type Fleetspace struct { + // A Fleetspace properties. + Properties *FleetspaceProperties + + // READ-ONLY; Name of the fleetspace. + Name *string + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *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 +} + +// FleetspaceListResult - The response of a Fleetspace list operation. +type FleetspaceListResult struct { + // REQUIRED; The Fleetspace items on this page + Value []*Fleetspace + + // The link to the next page of items + NextLink *string +} + +// FleetspaceProperties - A Fleetspace properties. +type FleetspaceProperties struct { + // Maximum number of vCores database fleet manager is allowed to provision in the fleetspace. + CapacityMax *int32 + + // Main Microsoft Entra ID principal that has admin access to all databases in the fleetspace. + MainPrincipal *MainPrincipal + + // READ-ONLY; Fleetspace state. + ProvisioningState *AzureProvisioningState +} + +// Identity - Database Identity. +type Identity struct { + // The federated client id for the SQL Database. It is used for cross tenant CMK scenario. + FederatedClientID *string + + // Identity type of the main principal. + IdentityType *IdentityType + + // User identity ids + UserAssignedIdentities []*DatabaseIdentity +} + +// MainPrincipal - A main principal. +type MainPrincipal struct { + // Application Id of the main principal. + ApplicationID *string + + // Login name of the main principal. + Login *string + + // Object Id of the main principal. + ObjectID *string + + // Principal type of the main principal. + PrincipalType *PrincipalType + + // Tenant Id of the main principal. + TenantID *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; Extensible 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 Azure + // Resource Manager/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 and 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 { + // REQUIRED; The Operation items on this page + Value []*Operation + + // The link to the next page of items + NextLink *string +} + +// RegisterServerProperties - Server registration definition. +type RegisterServerProperties struct { + // Destination tier overrides. + DestinationTierOverrides []*DestinationTierOverride + + // Source resource group name. + SourceResourceGroupName *string + + // Source SQL Server name. + SourceServerName *string + + // Source subscription id. + SourceSubscriptionID *string + + // Destination tier name. + TierName *string +} + +// 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 +} + +// TransparentDataEncryption - Transparent Data Encryption properties. +type TransparentDataEncryption struct { + // Enable key auto rotation + EnableAutoRotation *bool + + // Customer Managed Key (CMK) Uri. + KeyURI *string + + // Additional Keys + Keys []*string +} diff --git a/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager/models_serde.go b/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager/models_serde.go new file mode 100644 index 000000000000..e2e93feb5a2b --- /dev/null +++ b/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager/models_serde.go @@ -0,0 +1,1144 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armdatabasefleetmanager + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "reflect" +) + +// MarshalJSON implements the json.Marshaller interface for type DatabaseChangeTierProperties. +func (d DatabaseChangeTierProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "targetTierName", d.TargetTierName) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DatabaseChangeTierProperties. +func (d *DatabaseChangeTierProperties) 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 "targetTierName": + err = unpopulate(val, "TargetTierName", &d.TargetTierName) + 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 DatabaseIdentity. +func (d DatabaseIdentity) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "clientId", d.ClientID) + populate(objectMap, "principalId", d.PrincipalID) + populate(objectMap, "resourceId", d.ResourceID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DatabaseIdentity. +func (d *DatabaseIdentity) 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 "clientId": + err = unpopulate(val, "ClientID", &d.ClientID) + delete(rawMsg, key) + case "principalId": + err = unpopulate(val, "PrincipalID", &d.PrincipalID) + delete(rawMsg, key) + case "resourceId": + err = unpopulate(val, "ResourceID", &d.ResourceID) + 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 DatabaseRenameProperties. +func (d DatabaseRenameProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "newName", d.NewName) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DatabaseRenameProperties. +func (d *DatabaseRenameProperties) 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 "newName": + err = unpopulate(val, "NewName", &d.NewName) + 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 DestinationTierOverride. +func (d DestinationTierOverride) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "resourceName", d.ResourceName) + populate(objectMap, "resourceType", d.ResourceType) + populate(objectMap, "tierName", d.TierName) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DestinationTierOverride. +func (d *DestinationTierOverride) 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 "resourceName": + err = unpopulate(val, "ResourceName", &d.ResourceName) + delete(rawMsg, key) + case "resourceType": + err = unpopulate(val, "ResourceType", &d.ResourceType) + delete(rawMsg, key) + case "tierName": + err = unpopulate(val, "TierName", &d.TierName) + 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 FirewallRule. +func (f FirewallRule) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", f.ID) + populate(objectMap, "name", f.Name) + populate(objectMap, "properties", f.Properties) + populate(objectMap, "systemData", f.SystemData) + populate(objectMap, "type", f.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type FirewallRule. +func (f *FirewallRule) 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", f, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &f.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &f.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &f.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &f.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &f.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type FirewallRuleListResult. +func (f FirewallRuleListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", f.NextLink) + populate(objectMap, "value", f.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type FirewallRuleListResult. +func (f *FirewallRuleListResult) 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", f, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &f.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &f.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type FirewallRuleProperties. +func (f FirewallRuleProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "endIpAddress", f.EndIPAddress) + populate(objectMap, "provisioningState", f.ProvisioningState) + populate(objectMap, "startIpAddress", f.StartIPAddress) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type FirewallRuleProperties. +func (f *FirewallRuleProperties) 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", f, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "endIpAddress": + err = unpopulate(val, "EndIPAddress", &f.EndIPAddress) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &f.ProvisioningState) + delete(rawMsg, key) + case "startIpAddress": + err = unpopulate(val, "StartIPAddress", &f.StartIPAddress) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Fleet. +func (f Fleet) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", f.ID) + populate(objectMap, "location", f.Location) + populate(objectMap, "name", f.Name) + populate(objectMap, "properties", f.Properties) + populate(objectMap, "systemData", f.SystemData) + populate(objectMap, "tags", f.Tags) + populate(objectMap, "type", f.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Fleet. +func (f *Fleet) 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", f, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &f.ID) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &f.Location) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &f.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &f.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &f.SystemData) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &f.Tags) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &f.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type FleetDatabase. +func (f FleetDatabase) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", f.ID) + populate(objectMap, "name", f.Name) + populate(objectMap, "properties", f.Properties) + populate(objectMap, "systemData", f.SystemData) + populate(objectMap, "type", f.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type FleetDatabase. +func (f *FleetDatabase) 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", f, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &f.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &f.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &f.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &f.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &f.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type FleetDatabaseListResult. +func (f FleetDatabaseListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", f.NextLink) + populate(objectMap, "value", f.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type FleetDatabaseListResult. +func (f *FleetDatabaseListResult) 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", f, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &f.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &f.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type FleetDatabaseProperties. +func (f FleetDatabaseProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "backupRetentionDays", f.BackupRetentionDays) + populate(objectMap, "collation", f.Collation) + populate(objectMap, "connectionString", f.ConnectionString) + populate(objectMap, "createMode", f.CreateMode) + populate(objectMap, "databaseSizeGbMax", f.DatabaseSizeGbMax) + populateDateTimeRFC3339(objectMap, "earliestRestoreTime", f.EarliestRestoreTime) + populate(objectMap, "identity", f.Identity) + populateDateTimeRFC3339(objectMap, "latestRestoreTime", f.LatestRestoreTime) + populate(objectMap, "originalDatabaseId", f.OriginalDatabaseID) + populate(objectMap, "provisioningState", f.ProvisioningState) + populate(objectMap, "recoverable", f.Recoverable) + populate(objectMap, "resourceTags", f.ResourceTags) + populateDateTimeRFC3339(objectMap, "restoreFromTime", f.RestoreFromTime) + populate(objectMap, "sourceDatabaseName", f.SourceDatabaseName) + populate(objectMap, "tierName", f.TierName) + populate(objectMap, "transparentDataEncryption", f.TransparentDataEncryption) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type FleetDatabaseProperties. +func (f *FleetDatabaseProperties) 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", f, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "backupRetentionDays": + err = unpopulate(val, "BackupRetentionDays", &f.BackupRetentionDays) + delete(rawMsg, key) + case "collation": + err = unpopulate(val, "Collation", &f.Collation) + delete(rawMsg, key) + case "connectionString": + err = unpopulate(val, "ConnectionString", &f.ConnectionString) + delete(rawMsg, key) + case "createMode": + err = unpopulate(val, "CreateMode", &f.CreateMode) + delete(rawMsg, key) + case "databaseSizeGbMax": + err = unpopulate(val, "DatabaseSizeGbMax", &f.DatabaseSizeGbMax) + delete(rawMsg, key) + case "earliestRestoreTime": + err = unpopulateDateTimeRFC3339(val, "EarliestRestoreTime", &f.EarliestRestoreTime) + delete(rawMsg, key) + case "identity": + err = unpopulate(val, "Identity", &f.Identity) + delete(rawMsg, key) + case "latestRestoreTime": + err = unpopulateDateTimeRFC3339(val, "LatestRestoreTime", &f.LatestRestoreTime) + delete(rawMsg, key) + case "originalDatabaseId": + err = unpopulate(val, "OriginalDatabaseID", &f.OriginalDatabaseID) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &f.ProvisioningState) + delete(rawMsg, key) + case "recoverable": + err = unpopulate(val, "Recoverable", &f.Recoverable) + delete(rawMsg, key) + case "resourceTags": + err = unpopulate(val, "ResourceTags", &f.ResourceTags) + delete(rawMsg, key) + case "restoreFromTime": + err = unpopulateDateTimeRFC3339(val, "RestoreFromTime", &f.RestoreFromTime) + delete(rawMsg, key) + case "sourceDatabaseName": + err = unpopulate(val, "SourceDatabaseName", &f.SourceDatabaseName) + delete(rawMsg, key) + case "tierName": + err = unpopulate(val, "TierName", &f.TierName) + delete(rawMsg, key) + case "transparentDataEncryption": + err = unpopulate(val, "TransparentDataEncryption", &f.TransparentDataEncryption) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type FleetListResult. +func (f FleetListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", f.NextLink) + populate(objectMap, "value", f.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type FleetListResult. +func (f *FleetListResult) 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", f, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &f.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &f.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type FleetProperties. +func (f FleetProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "description", f.Description) + populate(objectMap, "provisioningState", f.ProvisioningState) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type FleetProperties. +func (f *FleetProperties) 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", f, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "description": + err = unpopulate(val, "Description", &f.Description) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &f.ProvisioningState) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type FleetTier. +func (f FleetTier) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", f.ID) + populate(objectMap, "name", f.Name) + populate(objectMap, "properties", f.Properties) + populate(objectMap, "systemData", f.SystemData) + populate(objectMap, "type", f.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type FleetTier. +func (f *FleetTier) 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", f, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &f.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &f.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &f.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &f.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &f.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type FleetTierListResult. +func (f FleetTierListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", f.NextLink) + populate(objectMap, "value", f.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type FleetTierListResult. +func (f *FleetTierListResult) 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", f, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &f.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &f.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type FleetTierProperties. +func (f FleetTierProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "capacity", f.Capacity) + populate(objectMap, "databaseCapacityMax", f.DatabaseCapacityMax) + populate(objectMap, "databaseCapacityMin", f.DatabaseCapacityMin) + populate(objectMap, "databaseSizeGbMax", f.DatabaseSizeGbMax) + populate(objectMap, "disabled", f.Disabled) + populate(objectMap, "family", f.Family) + populate(objectMap, "highAvailabilityReplicaCount", f.HighAvailabilityReplicaCount) + populate(objectMap, "poolNumOfDatabasesMax", f.PoolNumOfDatabasesMax) + populate(objectMap, "pooled", f.Pooled) + populate(objectMap, "provisioningState", f.ProvisioningState) + populate(objectMap, "serverless", f.Serverless) + populate(objectMap, "serviceTier", f.ServiceTier) + populate(objectMap, "zoneRedundancy", f.ZoneRedundancy) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type FleetTierProperties. +func (f *FleetTierProperties) 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", f, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "capacity": + err = unpopulate(val, "Capacity", &f.Capacity) + delete(rawMsg, key) + case "databaseCapacityMax": + err = unpopulate(val, "DatabaseCapacityMax", &f.DatabaseCapacityMax) + delete(rawMsg, key) + case "databaseCapacityMin": + err = unpopulate(val, "DatabaseCapacityMin", &f.DatabaseCapacityMin) + delete(rawMsg, key) + case "databaseSizeGbMax": + err = unpopulate(val, "DatabaseSizeGbMax", &f.DatabaseSizeGbMax) + delete(rawMsg, key) + case "disabled": + err = unpopulate(val, "Disabled", &f.Disabled) + delete(rawMsg, key) + case "family": + err = unpopulate(val, "Family", &f.Family) + delete(rawMsg, key) + case "highAvailabilityReplicaCount": + err = unpopulate(val, "HighAvailabilityReplicaCount", &f.HighAvailabilityReplicaCount) + delete(rawMsg, key) + case "poolNumOfDatabasesMax": + err = unpopulate(val, "PoolNumOfDatabasesMax", &f.PoolNumOfDatabasesMax) + delete(rawMsg, key) + case "pooled": + err = unpopulate(val, "Pooled", &f.Pooled) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &f.ProvisioningState) + delete(rawMsg, key) + case "serverless": + err = unpopulate(val, "Serverless", &f.Serverless) + delete(rawMsg, key) + case "serviceTier": + err = unpopulate(val, "ServiceTier", &f.ServiceTier) + delete(rawMsg, key) + case "zoneRedundancy": + err = unpopulate(val, "ZoneRedundancy", &f.ZoneRedundancy) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type FleetUpdate. +func (f FleetUpdate) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "properties", f.Properties) + populate(objectMap, "tags", f.Tags) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type FleetUpdate. +func (f *FleetUpdate) 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", f, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "properties": + err = unpopulate(val, "Properties", &f.Properties) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &f.Tags) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Fleetspace. +func (f Fleetspace) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", f.ID) + populate(objectMap, "name", f.Name) + populate(objectMap, "properties", f.Properties) + populate(objectMap, "systemData", f.SystemData) + populate(objectMap, "type", f.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Fleetspace. +func (f *Fleetspace) 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", f, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &f.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &f.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &f.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &f.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &f.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type FleetspaceListResult. +func (f FleetspaceListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", f.NextLink) + populate(objectMap, "value", f.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type FleetspaceListResult. +func (f *FleetspaceListResult) 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", f, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &f.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &f.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type FleetspaceProperties. +func (f FleetspaceProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "capacityMax", f.CapacityMax) + populate(objectMap, "mainPrincipal", f.MainPrincipal) + populate(objectMap, "provisioningState", f.ProvisioningState) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type FleetspaceProperties. +func (f *FleetspaceProperties) 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", f, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "capacityMax": + err = unpopulate(val, "CapacityMax", &f.CapacityMax) + delete(rawMsg, key) + case "mainPrincipal": + err = unpopulate(val, "MainPrincipal", &f.MainPrincipal) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &f.ProvisioningState) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Identity. +func (i Identity) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "federatedClientId", i.FederatedClientID) + populate(objectMap, "identityType", i.IdentityType) + populate(objectMap, "userAssignedIdentities", i.UserAssignedIdentities) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Identity. +func (i *Identity) 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 "federatedClientId": + err = unpopulate(val, "FederatedClientID", &i.FederatedClientID) + delete(rawMsg, key) + case "identityType": + err = unpopulate(val, "IdentityType", &i.IdentityType) + delete(rawMsg, key) + case "userAssignedIdentities": + err = unpopulate(val, "UserAssignedIdentities", &i.UserAssignedIdentities) + 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 MainPrincipal. +func (m MainPrincipal) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "applicationId", m.ApplicationID) + populate(objectMap, "login", m.Login) + populate(objectMap, "objectId", m.ObjectID) + populate(objectMap, "principalType", m.PrincipalType) + populate(objectMap, "tenantId", m.TenantID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type MainPrincipal. +func (m *MainPrincipal) 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 "applicationId": + err = unpopulate(val, "ApplicationID", &m.ApplicationID) + delete(rawMsg, key) + case "login": + err = unpopulate(val, "Login", &m.Login) + delete(rawMsg, key) + case "objectId": + err = unpopulate(val, "ObjectID", &m.ObjectID) + delete(rawMsg, key) + case "principalType": + err = unpopulate(val, "PrincipalType", &m.PrincipalType) + delete(rawMsg, key) + case "tenantId": + err = unpopulate(val, "TenantID", &m.TenantID) + 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 RegisterServerProperties. +func (r RegisterServerProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "destinationTierOverrides", r.DestinationTierOverrides) + populate(objectMap, "sourceResourceGroupName", r.SourceResourceGroupName) + populate(objectMap, "sourceServerName", r.SourceServerName) + populate(objectMap, "sourceSubscriptionId", r.SourceSubscriptionID) + populate(objectMap, "tierName", r.TierName) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RegisterServerProperties. +func (r *RegisterServerProperties) 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 "destinationTierOverrides": + err = unpopulate(val, "DestinationTierOverrides", &r.DestinationTierOverrides) + delete(rawMsg, key) + case "sourceResourceGroupName": + err = unpopulate(val, "SourceResourceGroupName", &r.SourceResourceGroupName) + delete(rawMsg, key) + case "sourceServerName": + err = unpopulate(val, "SourceServerName", &r.SourceServerName) + delete(rawMsg, key) + case "sourceSubscriptionId": + err = unpopulate(val, "SourceSubscriptionID", &r.SourceSubscriptionID) + delete(rawMsg, key) + case "tierName": + err = unpopulate(val, "TierName", &r.TierName) + 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 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 TransparentDataEncryption. +func (t TransparentDataEncryption) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "enableAutoRotation", t.EnableAutoRotation) + populate(objectMap, "keyUri", t.KeyURI) + populate(objectMap, "keys", t.Keys) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type TransparentDataEncryption. +func (t *TransparentDataEncryption) 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 "enableAutoRotation": + err = unpopulate(val, "EnableAutoRotation", &t.EnableAutoRotation) + delete(rawMsg, key) + case "keyUri": + err = unpopulate(val, "KeyURI", &t.KeyURI) + delete(rawMsg, key) + case "keys": + err = unpopulate(val, "Keys", &t.Keys) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + } + return nil +} + +func populate(m map[string]any, k string, v any) { + if v == nil { + return + } 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/databasefleetmanager/armdatabasefleetmanager/operations_client.go b/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager/operations_client.go new file mode 100644 index 000000000000..3b90e40923ab --- /dev/null +++ b/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager/operations_client.go @@ -0,0 +1,84 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armdatabasefleetmanager + +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 2025-02-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.DatabaseFleetManager/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", "2025-02-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/databasefleetmanager/armdatabasefleetmanager/operations_client_example_test.go b/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager/operations_client_example_test.go new file mode 100644 index 000000000000..7d2991907687 --- /dev/null +++ b/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager/operations_client_example_test.go @@ -0,0 +1,56 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armdatabasefleetmanager_test + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azidentity" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager" + "log" +) + +// Generated from example definition: 2025-02-01-preview/Operations_List_MaximumSet_Gen.json +func ExampleOperationsClient_NewListPager() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armdatabasefleetmanager.NewClientFactory("", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + pager := clientFactory.NewOperationsClient().NewListPager(nil) + for pager.More() { + page, err := pager.NextPage(ctx) + if err != nil { + log.Fatalf("failed to advance page: %v", err) + } + for _, v := range page.Value { + // You could use page here. We use blank identifier for just demo purposes. + _ = v + } + // If the HTTP response code is 200 as defined in example definition, your page structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // page = armdatabasefleetmanager.OperationsClientListResponse{ + // OperationListResult: armdatabasefleetmanager.OperationListResult{ + // Value: []*armdatabasefleetmanager.Operation{ + // { + // Name: to.Ptr("xalexazqlaltsvcoseubmutjbey"), + // IsDataAction: to.Ptr(true), + // Display: &armdatabasefleetmanager.OperationDisplay{ + // Provider: to.Ptr("bnlenqwsjrsxcflztxtllrep"), + // Resource: to.Ptr("ncu"), + // Operation: to.Ptr("nnbudygrwx"), + // Description: to.Ptr("ulkoxbko"), + // }, + // Origin: to.Ptr(armdatabasefleetmanager.OriginUser), + // ActionType: to.Ptr(armdatabasefleetmanager.ActionTypeInternal), + // }, + // }, + // NextLink: to.Ptr("https://microsoft.com/abgad"), + // }, + // } + } +} diff --git a/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager/options.go b/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager/options.go new file mode 100644 index 000000000000..d1bf9d740627 --- /dev/null +++ b/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager/options.go @@ -0,0 +1,231 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armdatabasefleetmanager + +// FirewallRulesClientBeginCreateOrUpdateOptions contains the optional parameters for the FirewallRulesClient.BeginCreateOrUpdate +// method. +type FirewallRulesClientBeginCreateOrUpdateOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// FirewallRulesClientBeginDeleteOptions contains the optional parameters for the FirewallRulesClient.BeginDelete method. +type FirewallRulesClientBeginDeleteOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// FirewallRulesClientGetOptions contains the optional parameters for the FirewallRulesClient.Get method. +type FirewallRulesClientGetOptions struct { + // placeholder for future optional parameters +} + +// FirewallRulesClientListByFleetspaceOptions contains the optional parameters for the FirewallRulesClient.NewListByFleetspacePager +// method. +type FirewallRulesClientListByFleetspaceOptions struct { + // The number of elements in the collection to skip. + Skip *int64 + + // An opaque token that identifies a starting point in the collection. + Skiptoken *string + + // The number of elements to return from the collection. + Top *int64 +} + +// FleetDatabasesClientBeginChangeTierOptions contains the optional parameters for the FleetDatabasesClient.BeginChangeTier +// method. +type FleetDatabasesClientBeginChangeTierOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// FleetDatabasesClientBeginCreateOrUpdateOptions contains the optional parameters for the FleetDatabasesClient.BeginCreateOrUpdate +// method. +type FleetDatabasesClientBeginCreateOrUpdateOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// FleetDatabasesClientBeginDeleteOptions contains the optional parameters for the FleetDatabasesClient.BeginDelete method. +type FleetDatabasesClientBeginDeleteOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// FleetDatabasesClientBeginRenameOptions contains the optional parameters for the FleetDatabasesClient.BeginRename method. +type FleetDatabasesClientBeginRenameOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// FleetDatabasesClientBeginRevertOptions contains the optional parameters for the FleetDatabasesClient.BeginRevert method. +type FleetDatabasesClientBeginRevertOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// FleetDatabasesClientBeginUpdateOptions contains the optional parameters for the FleetDatabasesClient.BeginUpdate method. +type FleetDatabasesClientBeginUpdateOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// FleetDatabasesClientGetOptions contains the optional parameters for the FleetDatabasesClient.Get method. +type FleetDatabasesClientGetOptions struct { + // placeholder for future optional parameters +} + +// FleetDatabasesClientListByFleetspaceOptions contains the optional parameters for the FleetDatabasesClient.NewListByFleetspacePager +// method. +type FleetDatabasesClientListByFleetspaceOptions struct { + // An OData filter expression that filters elements in the collection. + Filter *string + + // The number of elements in the collection to skip. + Skip *int64 + + // An opaque token that identifies a starting point in the collection. + Skiptoken *string + + // The number of elements to return from the collection. + Top *int64 +} + +// FleetTiersClientBeginCreateOrUpdateOptions contains the optional parameters for the FleetTiersClient.BeginCreateOrUpdate +// method. +type FleetTiersClientBeginCreateOrUpdateOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// FleetTiersClientBeginDeleteOptions contains the optional parameters for the FleetTiersClient.BeginDelete method. +type FleetTiersClientBeginDeleteOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// FleetTiersClientBeginUpdateOptions contains the optional parameters for the FleetTiersClient.BeginUpdate method. +type FleetTiersClientBeginUpdateOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// FleetTiersClientDisableOptions contains the optional parameters for the FleetTiersClient.Disable method. +type FleetTiersClientDisableOptions struct { + // placeholder for future optional parameters +} + +// FleetTiersClientGetOptions contains the optional parameters for the FleetTiersClient.Get method. +type FleetTiersClientGetOptions struct { + // placeholder for future optional parameters +} + +// FleetTiersClientListByFleetOptions contains the optional parameters for the FleetTiersClient.NewListByFleetPager method. +type FleetTiersClientListByFleetOptions struct { + // The number of elements in the collection to skip. + Skip *int64 + + // An opaque token that identifies a starting point in the collection. + Skiptoken *string + + // The number of elements to return from the collection. + Top *int64 +} + +// FleetsClientBeginCreateOrUpdateOptions contains the optional parameters for the FleetsClient.BeginCreateOrUpdate method. +type FleetsClientBeginCreateOrUpdateOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// FleetsClientBeginDeleteOptions contains the optional parameters for the FleetsClient.BeginDelete method. +type FleetsClientBeginDeleteOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// FleetsClientBeginUpdateOptions contains the optional parameters for the FleetsClient.BeginUpdate method. +type FleetsClientBeginUpdateOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// FleetsClientGetOptions contains the optional parameters for the FleetsClient.Get method. +type FleetsClientGetOptions struct { + // placeholder for future optional parameters +} + +// FleetsClientListByResourceGroupOptions contains the optional parameters for the FleetsClient.NewListByResourceGroupPager +// method. +type FleetsClientListByResourceGroupOptions struct { + // The number of elements in the collection to skip. + Skip *int64 + + // An opaque token that identifies a starting point in the collection. + Skiptoken *string + + // The number of elements to return from the collection. + Top *int64 +} + +// FleetsClientListOptions contains the optional parameters for the FleetsClient.NewListPager method. +type FleetsClientListOptions struct { + // placeholder for future optional parameters +} + +// FleetspacesClientBeginCreateOrUpdateOptions contains the optional parameters for the FleetspacesClient.BeginCreateOrUpdate +// method. +type FleetspacesClientBeginCreateOrUpdateOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// FleetspacesClientBeginDeleteOptions contains the optional parameters for the FleetspacesClient.BeginDelete method. +type FleetspacesClientBeginDeleteOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// FleetspacesClientBeginRegisterServerOptions contains the optional parameters for the FleetspacesClient.BeginRegisterServer +// method. +type FleetspacesClientBeginRegisterServerOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// FleetspacesClientBeginUnregisterOptions contains the optional parameters for the FleetspacesClient.BeginUnregister method. +type FleetspacesClientBeginUnregisterOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// FleetspacesClientBeginUpdateOptions contains the optional parameters for the FleetspacesClient.BeginUpdate method. +type FleetspacesClientBeginUpdateOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// FleetspacesClientGetOptions contains the optional parameters for the FleetspacesClient.Get method. +type FleetspacesClientGetOptions struct { + // placeholder for future optional parameters +} + +// FleetspacesClientListByFleetOptions contains the optional parameters for the FleetspacesClient.NewListByFleetPager method. +type FleetspacesClientListByFleetOptions struct { + // The number of elements in the collection to skip. + Skip *int64 + + // An opaque token that identifies a starting point in the collection. + Skiptoken *string + + // The number of elements to return from the collection. + Top *int64 +} + +// OperationsClientListOptions contains the optional parameters for the OperationsClient.NewListPager method. +type OperationsClientListOptions struct { + // placeholder for future optional parameters +} diff --git a/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager/responses.go b/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager/responses.go new file mode 100644 index 000000000000..84fabeb067ae --- /dev/null +++ b/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager/responses.go @@ -0,0 +1,187 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armdatabasefleetmanager + +// FirewallRulesClientCreateOrUpdateResponse contains the response from method FirewallRulesClient.BeginCreateOrUpdate. +type FirewallRulesClientCreateOrUpdateResponse struct { + // A firewall rule. + FirewallRule +} + +// FirewallRulesClientDeleteResponse contains the response from method FirewallRulesClient.BeginDelete. +type FirewallRulesClientDeleteResponse struct { + // placeholder for future response values +} + +// FirewallRulesClientGetResponse contains the response from method FirewallRulesClient.Get. +type FirewallRulesClientGetResponse struct { + // A firewall rule. + FirewallRule +} + +// FirewallRulesClientListByFleetspaceResponse contains the response from method FirewallRulesClient.NewListByFleetspacePager. +type FirewallRulesClientListByFleetspaceResponse struct { + // The response of a FirewallRule list operation. + FirewallRuleListResult +} + +// FleetDatabasesClientChangeTierResponse contains the response from method FleetDatabasesClient.BeginChangeTier. +type FleetDatabasesClientChangeTierResponse struct { + // placeholder for future response values +} + +// FleetDatabasesClientCreateOrUpdateResponse contains the response from method FleetDatabasesClient.BeginCreateOrUpdate. +type FleetDatabasesClientCreateOrUpdateResponse struct { + // A fleet database. + FleetDatabase +} + +// FleetDatabasesClientDeleteResponse contains the response from method FleetDatabasesClient.BeginDelete. +type FleetDatabasesClientDeleteResponse struct { + // placeholder for future response values +} + +// FleetDatabasesClientGetResponse contains the response from method FleetDatabasesClient.Get. +type FleetDatabasesClientGetResponse struct { + // A fleet database. + FleetDatabase +} + +// FleetDatabasesClientListByFleetspaceResponse contains the response from method FleetDatabasesClient.NewListByFleetspacePager. +type FleetDatabasesClientListByFleetspaceResponse struct { + // The response of a FleetDatabase list operation. + FleetDatabaseListResult +} + +// FleetDatabasesClientRenameResponse contains the response from method FleetDatabasesClient.BeginRename. +type FleetDatabasesClientRenameResponse struct { + // placeholder for future response values +} + +// FleetDatabasesClientRevertResponse contains the response from method FleetDatabasesClient.BeginRevert. +type FleetDatabasesClientRevertResponse struct { + // placeholder for future response values +} + +// FleetDatabasesClientUpdateResponse contains the response from method FleetDatabasesClient.BeginUpdate. +type FleetDatabasesClientUpdateResponse struct { + // A fleet database. + FleetDatabase +} + +// FleetTiersClientCreateOrUpdateResponse contains the response from method FleetTiersClient.BeginCreateOrUpdate. +type FleetTiersClientCreateOrUpdateResponse struct { + // A SQL Database Fleet tier. + FleetTier +} + +// FleetTiersClientDeleteResponse contains the response from method FleetTiersClient.BeginDelete. +type FleetTiersClientDeleteResponse struct { + // placeholder for future response values +} + +// FleetTiersClientDisableResponse contains the response from method FleetTiersClient.Disable. +type FleetTiersClientDisableResponse struct { + // A SQL Database Fleet tier. + FleetTier +} + +// FleetTiersClientGetResponse contains the response from method FleetTiersClient.Get. +type FleetTiersClientGetResponse struct { + // A SQL Database Fleet tier. + FleetTier +} + +// FleetTiersClientListByFleetResponse contains the response from method FleetTiersClient.NewListByFleetPager. +type FleetTiersClientListByFleetResponse struct { + // The response of a FleetTier list operation. + FleetTierListResult +} + +// FleetTiersClientUpdateResponse contains the response from method FleetTiersClient.BeginUpdate. +type FleetTiersClientUpdateResponse struct { + // A SQL Database Fleet tier. + FleetTier +} + +// FleetsClientCreateOrUpdateResponse contains the response from method FleetsClient.BeginCreateOrUpdate. +type FleetsClientCreateOrUpdateResponse struct { + // A Database Fleet. + Fleet +} + +// FleetsClientDeleteResponse contains the response from method FleetsClient.BeginDelete. +type FleetsClientDeleteResponse struct { + // placeholder for future response values +} + +// FleetsClientGetResponse contains the response from method FleetsClient.Get. +type FleetsClientGetResponse struct { + // A Database Fleet. + Fleet +} + +// FleetsClientListByResourceGroupResponse contains the response from method FleetsClient.NewListByResourceGroupPager. +type FleetsClientListByResourceGroupResponse struct { + // The response of a Fleet list operation. + FleetListResult +} + +// FleetsClientListResponse contains the response from method FleetsClient.NewListPager. +type FleetsClientListResponse struct { + // The response of a Fleet list operation. + FleetListResult +} + +// FleetsClientUpdateResponse contains the response from method FleetsClient.BeginUpdate. +type FleetsClientUpdateResponse struct { + // A Database Fleet. + Fleet +} + +// FleetspacesClientCreateOrUpdateResponse contains the response from method FleetspacesClient.BeginCreateOrUpdate. +type FleetspacesClientCreateOrUpdateResponse struct { + // A fleetspace. + Fleetspace +} + +// FleetspacesClientDeleteResponse contains the response from method FleetspacesClient.BeginDelete. +type FleetspacesClientDeleteResponse struct { + // placeholder for future response values +} + +// FleetspacesClientGetResponse contains the response from method FleetspacesClient.Get. +type FleetspacesClientGetResponse struct { + // A fleetspace. + Fleetspace +} + +// FleetspacesClientListByFleetResponse contains the response from method FleetspacesClient.NewListByFleetPager. +type FleetspacesClientListByFleetResponse struct { + // The response of a Fleetspace list operation. + FleetspaceListResult +} + +// FleetspacesClientRegisterServerResponse contains the response from method FleetspacesClient.BeginRegisterServer. +type FleetspacesClientRegisterServerResponse struct { + // placeholder for future response values +} + +// FleetspacesClientUnregisterResponse contains the response from method FleetspacesClient.BeginUnregister. +type FleetspacesClientUnregisterResponse struct { + // placeholder for future response values +} + +// FleetspacesClientUpdateResponse contains the response from method FleetspacesClient.BeginUpdate. +type FleetspacesClientUpdateResponse struct { + // A fleetspace. + Fleetspace +} + +// 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 +} diff --git a/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager/time_rfc3339.go b/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager/time_rfc3339.go new file mode 100644 index 000000000000..6a6d0db9efb0 --- /dev/null +++ b/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager/time_rfc3339.go @@ -0,0 +1,109 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armdatabasefleetmanager + +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 +} diff --git a/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager/tsp-location.yaml b/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager/tsp-location.yaml new file mode 100644 index 000000000000..b6228ddd3c84 --- /dev/null +++ b/sdk/resourcemanager/databasefleetmanager/armdatabasefleetmanager/tsp-location.yaml @@ -0,0 +1,4 @@ +directory: specification/databasefleetmanager/DatabaseFleetManager.Management +commit: 1f578543d267d08febc1bebf4e33ffe14363ddfc +repo: Azure/azure-rest-api-specs +additionalDirectories: diff --git a/sdk/resourcemanager/databasewatcher/armdatabasewatcher/CHANGELOG.md b/sdk/resourcemanager/databasewatcher/armdatabasewatcher/CHANGELOG.md index 6fa14395aaea..97fd61c55c84 100644 --- a/sdk/resourcemanager/databasewatcher/armdatabasewatcher/CHANGELOG.md +++ b/sdk/resourcemanager/databasewatcher/armdatabasewatcher/CHANGELOG.md @@ -1,5 +1,9 @@ # Release History +## 1.0.0 (2025-04-27) +### Other Changes + + ## 0.1.0 (2025-02-26) ### Other Changes diff --git a/sdk/resourcemanager/databasewatcher/armdatabasewatcher/constants.go b/sdk/resourcemanager/databasewatcher/armdatabasewatcher/constants.go index fb14d4b4600b..f61060f010e2 100644 --- a/sdk/resourcemanager/databasewatcher/armdatabasewatcher/constants.go +++ b/sdk/resourcemanager/databasewatcher/armdatabasewatcher/constants.go @@ -6,7 +6,7 @@ package armdatabasewatcher const ( moduleName = "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/databasewatcher/armdatabasewatcher" - moduleVersion = "v0.1.0" + moduleVersion = "v1.0.0" ) // ActionType - Extensible enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. diff --git a/sdk/resourcemanager/databasewatcher/armdatabasewatcher/healthvalidations_client_example_test.go b/sdk/resourcemanager/databasewatcher/armdatabasewatcher/healthvalidations_client_example_test.go index f721a6d8e59f..30dfef35aca7 100644 --- a/sdk/resourcemanager/databasewatcher/armdatabasewatcher/healthvalidations_client_example_test.go +++ b/sdk/resourcemanager/databasewatcher/armdatabasewatcher/healthvalidations_client_example_test.go @@ -155,6 +155,7 @@ func ExampleHealthValidationsClient_BeginStartValidation() { // Status: to.Ptr(armdatabasewatcher.ValidationStatusRunning), // Issues: []*armdatabasewatcher.ValidationIssue{ // }, + // ProvisioningState: to.Ptr(armdatabasewatcher.ResourceProvisioningState("Accepted")), // }, // ID: to.Ptr("/subscriptions/469DD77C-C8DB-47B7-B9E1-72D29F8C878Be/resourceGroups/rgWatcher/providers/microsoft.databasewatcher/watchers/testWatcher/healthValidations/testHealthValidation"), // Name: to.Ptr("testHealthValidation"), diff --git a/sdk/resourcemanager/databasewatcher/armdatabasewatcher/sharedprivatelinkresources_client_example_test.go b/sdk/resourcemanager/databasewatcher/armdatabasewatcher/sharedprivatelinkresources_client_example_test.go index 2df401e2e1f4..09fdae71c453 100644 --- a/sdk/resourcemanager/databasewatcher/armdatabasewatcher/sharedprivatelinkresources_client_example_test.go +++ b/sdk/resourcemanager/databasewatcher/armdatabasewatcher/sharedprivatelinkresources_client_example_test.go @@ -50,6 +50,7 @@ func ExampleSharedPrivateLinkResourcesClient_BeginCreate() { // RequestMessage: to.Ptr("request message"), // DNSZone: to.Ptr("ec3ae9d410ba"), // Status: to.Ptr(armdatabasewatcher.SharedPrivateLinkResourceStatusPending), + // ProvisioningState: to.Ptr(armdatabasewatcher.ResourceProvisioningState("Completed")), // }, // ID: to.Ptr("/subscriptions/49e0fbd3-75e8-44e7-96fd-5b64d9ad818d/resourceGroups/apiTest-ddat4p/providers/Microsoft.DatabaseWatcher/watchers/databasemo3ej9ih/sharedPrivateLinkResources/monitoringh22eed"), // Name: to.Ptr("monitoringh22eed"), @@ -113,6 +114,7 @@ func ExampleSharedPrivateLinkResourcesClient_Get() { // RequestMessage: to.Ptr("request message"), // DNSZone: to.Ptr("ec3ae9d410ba"), // Status: to.Ptr(armdatabasewatcher.SharedPrivateLinkResourceStatusPending), + // ProvisioningState: to.Ptr(armdatabasewatcher.ResourceProvisioningState("Completed")), // }, // ID: to.Ptr("/subscriptions/49e0fbd3-75e8-44e7-96fd-5b64d9ad818d/resourceGroups/apiTest-ddat4p/providers/Microsoft.DatabaseWatcher/watchers/databasemo3ej9ih/sharedPrivateLinkResources/monitoringh22eed"), // Name: to.Ptr("monitoringh22eed"), @@ -164,6 +166,7 @@ func ExampleSharedPrivateLinkResourcesClient_NewListByWatcherPager() { // RequestMessage: to.Ptr("request message"), // DNSZone: to.Ptr("ec3ae9d410ba"), // Status: to.Ptr(armdatabasewatcher.SharedPrivateLinkResourceStatusPending), + // ProvisioningState: to.Ptr(armdatabasewatcher.ResourceProvisioningState("Completed")), // }, // SystemData: &armdatabasewatcher.SystemData{ // CreatedBy: to.Ptr("enbpvlpqbwd"), diff --git a/sdk/resourcemanager/databasewatcher/armdatabasewatcher/tsp-location.yaml b/sdk/resourcemanager/databasewatcher/armdatabasewatcher/tsp-location.yaml index b49ef053e4e1..fdf8fb9c3e5e 100644 --- a/sdk/resourcemanager/databasewatcher/armdatabasewatcher/tsp-location.yaml +++ b/sdk/resourcemanager/databasewatcher/armdatabasewatcher/tsp-location.yaml @@ -1,4 +1,4 @@ directory: specification/databasewatcher/DatabaseWatcher.Management -commit: 80a1036678da5411d44a18bc24c66cc6e14e3605 +commit: 1f578543d267d08febc1bebf4e33ffe14363ddfc repo: Azure/azure-rest-api-specs -additionalDirectories: \ No newline at end of file +additionalDirectories: diff --git a/sdk/resourcemanager/databasewatcher/armdatabasewatcher/watchers_client_example_test.go b/sdk/resourcemanager/databasewatcher/armdatabasewatcher/watchers_client_example_test.go index dfeb47ba5b7a..03d0bea0c60e 100644 --- a/sdk/resourcemanager/databasewatcher/armdatabasewatcher/watchers_client_example_test.go +++ b/sdk/resourcemanager/databasewatcher/armdatabasewatcher/watchers_client_example_test.go @@ -150,6 +150,7 @@ func ExampleWatchersClient_Get() { // ProvisioningState: to.Ptr(armdatabasewatcher.ProvisioningStateSucceeded), // }, // Identity: &armdatabasewatcher.ManagedServiceIdentityV4{ + // Type: to.Ptr(armdatabasewatcher.ManagedServiceIdentityType("SystemAssignedIdentity")), // UserAssignedIdentities: map[string]*armdatabasewatcher.UserAssignedIdentity{ // }, // PrincipalID: to.Ptr("49e0fbd3-75e8-44e7-96fd-5b64d9ad818d"), @@ -206,6 +207,7 @@ func ExampleWatchersClient_NewListByResourceGroupPager() { // Tags: map[string]*string{ // }, // Identity: &armdatabasewatcher.ManagedServiceIdentityV4{ + // Type: to.Ptr(armdatabasewatcher.ManagedServiceIdentityType("SystemAssignedIdentity")), // UserAssignedIdentities: map[string]*armdatabasewatcher.UserAssignedIdentity{ // }, // PrincipalID: to.Ptr("49e0fbd3-75e8-44e7-96fd-5b64d9ad818d"), @@ -254,6 +256,7 @@ func ExampleWatchersClient_NewListByResourceGroupPager() { // }, // }, // Identity: &armdatabasewatcher.ManagedServiceIdentityV4{ + // Type: to.Ptr(armdatabasewatcher.ManagedServiceIdentityType("SystemAssignedIdentity")), // UserAssignedIdentities: map[string]*armdatabasewatcher.UserAssignedIdentity{ // }, // PrincipalID: to.Ptr("49e0fbd3-75e8-44e7-96fd-5b64d9ad818d"), @@ -290,6 +293,7 @@ func ExampleWatchersClient_NewListByResourceGroupPager() { // }, // }, // Identity: &armdatabasewatcher.ManagedServiceIdentityV4{ + // Type: to.Ptr(armdatabasewatcher.ManagedServiceIdentityType("SystemAssignedIdentity")), // UserAssignedIdentities: map[string]*armdatabasewatcher.UserAssignedIdentity{ // }, // PrincipalID: to.Ptr("49e0fbd3-75e8-44e7-96fd-5b64d9ad818d"), @@ -326,6 +330,7 @@ func ExampleWatchersClient_NewListByResourceGroupPager() { // }, // }, // Identity: &armdatabasewatcher.ManagedServiceIdentityV4{ + // Type: to.Ptr(armdatabasewatcher.ManagedServiceIdentityType("SystemAssignedIdentity")), // UserAssignedIdentities: map[string]*armdatabasewatcher.UserAssignedIdentity{ // }, // PrincipalID: to.Ptr("49e0fbd3-75e8-44e7-96fd-5b64d9ad818d"), @@ -362,6 +367,7 @@ func ExampleWatchersClient_NewListByResourceGroupPager() { // }, // }, // Identity: &armdatabasewatcher.ManagedServiceIdentityV4{ + // Type: to.Ptr(armdatabasewatcher.ManagedServiceIdentityType("SystemAssignedIdentity")), // UserAssignedIdentities: map[string]*armdatabasewatcher.UserAssignedIdentity{ // }, // PrincipalID: to.Ptr("49e0fbd3-75e8-44e7-96fd-5b64d9ad818d"), @@ -406,6 +412,7 @@ func ExampleWatchersClient_NewListByResourceGroupPager() { // }, // }, // Identity: &armdatabasewatcher.ManagedServiceIdentityV4{ + // Type: to.Ptr(armdatabasewatcher.ManagedServiceIdentityType("SystemAssignedIdentity")), // UserAssignedIdentities: map[string]*armdatabasewatcher.UserAssignedIdentity{ // }, // PrincipalID: to.Ptr("49e0fbd3-75e8-44e7-96fd-5b64d9ad818d"), @@ -434,6 +441,7 @@ func ExampleWatchersClient_NewListByResourceGroupPager() { // }, // }, // Identity: &armdatabasewatcher.ManagedServiceIdentityV4{ + // Type: to.Ptr(armdatabasewatcher.ManagedServiceIdentityType("SystemAssignedIdentity")), // UserAssignedIdentities: map[string]*armdatabasewatcher.UserAssignedIdentity{ // }, // PrincipalID: to.Ptr("49e0fbd3-75e8-44e7-96fd-5b64d9ad818d"), @@ -535,6 +543,7 @@ func ExampleWatchersClient_NewListBySubscriptionPager() { // }, // }, // Identity: &armdatabasewatcher.ManagedServiceIdentityV4{ + // Type: to.Ptr(armdatabasewatcher.ManagedServiceIdentityType("SystemAssignedIdentity")), // UserAssignedIdentities: map[string]*armdatabasewatcher.UserAssignedIdentity{ // }, // PrincipalID: to.Ptr("49e0fbd3-75e8-44e7-96fd-5b64d9ad818d"), @@ -571,6 +580,7 @@ func ExampleWatchersClient_NewListBySubscriptionPager() { // }, // }, // Identity: &armdatabasewatcher.ManagedServiceIdentityV4{ + // Type: to.Ptr(armdatabasewatcher.ManagedServiceIdentityType("SystemAssignedIdentity")), // UserAssignedIdentities: map[string]*armdatabasewatcher.UserAssignedIdentity{ // }, // PrincipalID: to.Ptr("49e0fbd3-75e8-44e7-96fd-5b64d9ad818d"), @@ -607,6 +617,7 @@ func ExampleWatchersClient_NewListBySubscriptionPager() { // }, // }, // Identity: &armdatabasewatcher.ManagedServiceIdentityV4{ + // Type: to.Ptr(armdatabasewatcher.ManagedServiceIdentityType("SystemAssignedIdentity")), // UserAssignedIdentities: map[string]*armdatabasewatcher.UserAssignedIdentity{ // }, // PrincipalID: to.Ptr("49e0fbd3-75e8-44e7-96fd-5b64d9ad818d"), @@ -643,6 +654,7 @@ func ExampleWatchersClient_NewListBySubscriptionPager() { // }, // }, // Identity: &armdatabasewatcher.ManagedServiceIdentityV4{ + // Type: to.Ptr(armdatabasewatcher.ManagedServiceIdentityType("SystemAssignedIdentity")), // UserAssignedIdentities: map[string]*armdatabasewatcher.UserAssignedIdentity{ // }, // PrincipalID: to.Ptr("49e0fbd3-75e8-44e7-96fd-5b64d9ad818d"), @@ -687,6 +699,7 @@ func ExampleWatchersClient_NewListBySubscriptionPager() { // }, // }, // Identity: &armdatabasewatcher.ManagedServiceIdentityV4{ + // Type: to.Ptr(armdatabasewatcher.ManagedServiceIdentityType("SystemAssignedIdentity")), // UserAssignedIdentities: map[string]*armdatabasewatcher.UserAssignedIdentity{ // }, // PrincipalID: to.Ptr("49e0fbd3-75e8-44e7-96fd-5b64d9ad818d"), @@ -715,6 +728,7 @@ func ExampleWatchersClient_NewListBySubscriptionPager() { // }, // }, // Identity: &armdatabasewatcher.ManagedServiceIdentityV4{ + // Type: to.Ptr(armdatabasewatcher.ManagedServiceIdentityType("SystemAssignedIdentity")), // UserAssignedIdentities: map[string]*armdatabasewatcher.UserAssignedIdentity{ // }, // PrincipalID: to.Ptr("49e0fbd3-75e8-44e7-96fd-5b64d9ad818d"), diff --git a/sdk/resourcemanager/dependencymap/armdependencymap/CHANGELOG.md b/sdk/resourcemanager/dependencymap/armdependencymap/CHANGELOG.md index 5bdcef29e4ed..7a333569d63d 100644 --- a/sdk/resourcemanager/dependencymap/armdependencymap/CHANGELOG.md +++ b/sdk/resourcemanager/dependencymap/armdependencymap/CHANGELOG.md @@ -1,5 +1,9 @@ # Release History +## 0.1.1 (2025-04-27) +### Other Changes + + ## 0.1.0 (2025-04-15) ### Other Changes diff --git a/sdk/resourcemanager/dependencymap/armdependencymap/constants.go b/sdk/resourcemanager/dependencymap/armdependencymap/constants.go index 05a2396fa0e1..737503e24f13 100644 --- a/sdk/resourcemanager/dependencymap/armdependencymap/constants.go +++ b/sdk/resourcemanager/dependencymap/armdependencymap/constants.go @@ -6,7 +6,7 @@ package armdependencymap const ( moduleName = "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/dependencymap/armdependencymap" - moduleVersion = "v0.1.0" + moduleVersion = "v0.1.1" ) // ActionType - Extensible enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. diff --git a/sdk/resourcemanager/dependencymap/armdependencymap/tsp-location.yaml b/sdk/resourcemanager/dependencymap/armdependencymap/tsp-location.yaml index fa293b2599f5..6545bd114ec4 100644 --- a/sdk/resourcemanager/dependencymap/armdependencymap/tsp-location.yaml +++ b/sdk/resourcemanager/dependencymap/armdependencymap/tsp-location.yaml @@ -1,4 +1,4 @@ directory: specification/azuredependencymap/DependencyMap.Management -commit: a730aea13a0bb551748ab41f5d36f00956f0a4f6 +commit: 1f578543d267d08febc1bebf4e33ffe14363ddfc repo: Azure/azure-rest-api-specs -additionalDirectories: \ No newline at end of file +additionalDirectories: diff --git a/sdk/resourcemanager/deviceregistry/armdeviceregistry/CHANGELOG.md b/sdk/resourcemanager/deviceregistry/armdeviceregistry/CHANGELOG.md index 4d58f300b978..46f3fced849d 100644 --- a/sdk/resourcemanager/deviceregistry/armdeviceregistry/CHANGELOG.md +++ b/sdk/resourcemanager/deviceregistry/armdeviceregistry/CHANGELOG.md @@ -1,5 +1,9 @@ # Release History +## 1.0.1 (2025-04-27) +### Other Changes + + ## 1.0.0 (2025-02-10) ### Features Added diff --git a/sdk/resourcemanager/deviceregistry/armdeviceregistry/constants.go b/sdk/resourcemanager/deviceregistry/armdeviceregistry/constants.go index 1a7e44fb45bc..6da3f4ded1d5 100644 --- a/sdk/resourcemanager/deviceregistry/armdeviceregistry/constants.go +++ b/sdk/resourcemanager/deviceregistry/armdeviceregistry/constants.go @@ -6,7 +6,7 @@ package armdeviceregistry const ( moduleName = "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/deviceregistry/armdeviceregistry" - moduleVersion = "v1.0.0" + moduleVersion = "v1.0.1" ) // ActionType - Extensible enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. diff --git a/sdk/resourcemanager/deviceregistry/armdeviceregistry/tsp-location.yaml b/sdk/resourcemanager/deviceregistry/armdeviceregistry/tsp-location.yaml index f6af95165e4f..de2bce07645a 100644 --- a/sdk/resourcemanager/deviceregistry/armdeviceregistry/tsp-location.yaml +++ b/sdk/resourcemanager/deviceregistry/armdeviceregistry/tsp-location.yaml @@ -1,4 +1,4 @@ directory: specification/deviceregistry/DeviceRegistry.Management -commit: 53b2029545881f27d0f0fad3892065f39b1b9e83 +commit: 1f578543d267d08febc1bebf4e33ffe14363ddfc repo: Azure/azure-rest-api-specs -additionalDirectories: \ No newline at end of file +additionalDirectories: diff --git a/sdk/resourcemanager/devopsinfrastructure/armdevopsinfrastructure/CHANGELOG.md b/sdk/resourcemanager/devopsinfrastructure/armdevopsinfrastructure/CHANGELOG.md index ff3cd4b4c66f..f608cd98a4b5 100644 --- a/sdk/resourcemanager/devopsinfrastructure/armdevopsinfrastructure/CHANGELOG.md +++ b/sdk/resourcemanager/devopsinfrastructure/armdevopsinfrastructure/CHANGELOG.md @@ -1,5 +1,21 @@ # Release History +## 1.1.0 (2025-04-27) +### Features Added + +- New enum type `AvailabilityStatus` with values `AvailabilityStatusAvailable`, `AvailabilityStatusUnavailable` +- New enum type `CertificateStoreNameOption` with values `CertificateStoreNameOptionMy`, `CertificateStoreNameOptionRoot` +- New enum type `CheckNameAvailabilityReason` with values `CheckNameAvailabilityReasonAlreadyExists`, `CheckNameAvailabilityReasonInvalid` +- New enum type `EphemeralType` with values `EphemeralTypeAutomatic`, `EphemeralTypeCacheDisk`, `EphemeralTypeResourceDisk` +- New enum type `ResourceType` with values `ResourceTypeMicrosoftDevOpsInfrastructurePools` +- New function `*PoolsClient.CheckNameAvailability(context.Context, CheckNameAvailability, *PoolsClientCheckNameAvailabilityOptions) (PoolsClientCheckNameAvailabilityResponse, error)` +- New struct `CheckNameAvailability` +- New struct `CheckNameAvailabilityResult` +- New field `OpenAccess` in struct `Organization` +- New field `EphemeralType` in struct `PoolImage` +- New field `CertificateStoreName` in struct `SecretsManagementSettings` + + ## 1.0.0 (2024-11-20) ### Breaking Changes diff --git a/sdk/resourcemanager/devopsinfrastructure/armdevopsinfrastructure/constants.go b/sdk/resourcemanager/devopsinfrastructure/armdevopsinfrastructure/constants.go index 982aced6c92c..410fabd9e209 100644 --- a/sdk/resourcemanager/devopsinfrastructure/armdevopsinfrastructure/constants.go +++ b/sdk/resourcemanager/devopsinfrastructure/armdevopsinfrastructure/constants.go @@ -6,7 +6,7 @@ package armdevopsinfrastructure const ( moduleName = "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/devopsinfrastructure/armdevopsinfrastructure" - moduleVersion = "v1.0.0" + moduleVersion = "v1.1.0" ) // ActionType - Extensible enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. @@ -24,6 +24,24 @@ func PossibleActionTypeValues() []ActionType { } } +// AvailabilityStatus - AvailabilityStatus of a name. +type AvailabilityStatus string + +const ( + // AvailabilityStatusAvailable - The name is available. + AvailabilityStatusAvailable AvailabilityStatus = "Available" + // AvailabilityStatusUnavailable - The name is unavailable + AvailabilityStatusUnavailable AvailabilityStatus = "Unavailable" +) + +// PossibleAvailabilityStatusValues returns the possible values for the AvailabilityStatus const type. +func PossibleAvailabilityStatusValues() []AvailabilityStatus { + return []AvailabilityStatus{ + AvailabilityStatusAvailable, + AvailabilityStatusUnavailable, + } +} + // AzureDevOpsPermissionType - Determines who has admin permissions to the Azure DevOps pool. type AzureDevOpsPermissionType string @@ -66,6 +84,42 @@ func PossibleCachingTypeValues() []CachingType { } } +// CertificateStoreNameOption - The certificate store name type +type CertificateStoreNameOption string + +const ( + // CertificateStoreNameOptionMy - The X.509 certificate store for personal certificates. + CertificateStoreNameOptionMy CertificateStoreNameOption = "My" + // CertificateStoreNameOptionRoot - The X.509 certificate store for trusted root certificate authorities (CAs). + CertificateStoreNameOptionRoot CertificateStoreNameOption = "Root" +) + +// PossibleCertificateStoreNameOptionValues returns the possible values for the CertificateStoreNameOption const type. +func PossibleCertificateStoreNameOptionValues() []CertificateStoreNameOption { + return []CertificateStoreNameOption{ + CertificateStoreNameOptionMy, + CertificateStoreNameOptionRoot, + } +} + +// CheckNameAvailabilityReason - The reason code explaining why the name is unavailable. Will be null if the name is available. +type CheckNameAvailabilityReason string + +const ( + // CheckNameAvailabilityReasonAlreadyExists - The name already exists. + CheckNameAvailabilityReasonAlreadyExists CheckNameAvailabilityReason = "AlreadyExists" + // CheckNameAvailabilityReasonInvalid - The name is invalid. + CheckNameAvailabilityReasonInvalid CheckNameAvailabilityReason = "Invalid" +) + +// PossibleCheckNameAvailabilityReasonValues returns the possible values for the CheckNameAvailabilityReason const type. +func PossibleCheckNameAvailabilityReasonValues() []CheckNameAvailabilityReason { + return []CheckNameAvailabilityReason{ + CheckNameAvailabilityReasonAlreadyExists, + CheckNameAvailabilityReasonInvalid, + } +} + // CreatedByType - The kind of entity that created the resource. type CreatedByType string @@ -90,6 +144,27 @@ func PossibleCreatedByTypeValues() []CreatedByType { } } +// EphemeralType - The type of Ephemeral option the pool will use on underlying VMs when loading this image. +type EphemeralType string + +const ( + // EphemeralTypeAutomatic - Ephemeral is handled by Managed DevOps Pools service. + EphemeralTypeAutomatic EphemeralType = "Automatic" + // EphemeralTypeCacheDisk - CacheDisk ephemeral only, requires that the SKU has a cache that is large enough for the image. + EphemeralTypeCacheDisk EphemeralType = "CacheDisk" + // EphemeralTypeResourceDisk - ResourceDisk ephemeral only, requires only that the SKU supports it. + EphemeralTypeResourceDisk EphemeralType = "ResourceDisk" +) + +// PossibleEphemeralTypeValues returns the possible values for the EphemeralType const type. +func PossibleEphemeralTypeValues() []EphemeralType { + return []EphemeralType{ + EphemeralTypeAutomatic, + EphemeralTypeCacheDisk, + EphemeralTypeResourceDisk, + } +} + // LogonType - Determines how the service should be run. type LogonType string @@ -334,6 +409,21 @@ func PossibleResourceStatusValues() []ResourceStatus { } } +// ResourceType - The type of resource. +type ResourceType string + +const ( + // ResourceTypeMicrosoftDevOpsInfrastructurePools - DevOpsInfrastructure pool resource. + ResourceTypeMicrosoftDevOpsInfrastructurePools ResourceType = "Microsoft.DevOpsInfrastructure/pools" +) + +// PossibleResourceTypeValues returns the possible values for the ResourceType const type. +func PossibleResourceTypeValues() []ResourceType { + return []ResourceType{ + ResourceTypeMicrosoftDevOpsInfrastructurePools, + } +} + // StorageAccountType - StorageAccountType enums type StorageAccountType string diff --git a/sdk/resourcemanager/devopsinfrastructure/armdevopsinfrastructure/fake/pools_server.go b/sdk/resourcemanager/devopsinfrastructure/armdevopsinfrastructure/fake/pools_server.go index 170370591c3f..88c1b88d6e3a 100644 --- a/sdk/resourcemanager/devopsinfrastructure/armdevopsinfrastructure/fake/pools_server.go +++ b/sdk/resourcemanager/devopsinfrastructure/armdevopsinfrastructure/fake/pools_server.go @@ -20,6 +20,10 @@ import ( // PoolsServer is a fake server for instances of the armdevopsinfrastructure.PoolsClient type. type PoolsServer struct { + // CheckNameAvailability is the fake for method PoolsClient.CheckNameAvailability + // HTTP status codes to indicate success: http.StatusOK + CheckNameAvailability func(ctx context.Context, body armdevopsinfrastructure.CheckNameAvailability, options *armdevopsinfrastructure.PoolsClientCheckNameAvailabilityOptions) (resp azfake.Responder[armdevopsinfrastructure.PoolsClientCheckNameAvailabilityResponse], errResp azfake.ErrorResponder) + // BeginCreateOrUpdate is the fake for method PoolsClient.BeginCreateOrUpdate // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated BeginCreateOrUpdate func(ctx context.Context, resourceGroupName string, poolName string, resource armdevopsinfrastructure.Pool, options *armdevopsinfrastructure.PoolsClientBeginCreateOrUpdateOptions) (resp azfake.PollerResponder[armdevopsinfrastructure.PoolsClientCreateOrUpdateResponse], errResp azfake.ErrorResponder) @@ -93,6 +97,8 @@ func (p *PoolsServerTransport) dispatchToMethodFake(req *http.Request, method st } if !intercepted { switch method { + case "PoolsClient.CheckNameAvailability": + res.resp, res.err = p.dispatchCheckNameAvailability(req) case "PoolsClient.BeginCreateOrUpdate": res.resp, res.err = p.dispatchBeginCreateOrUpdate(req) case "PoolsClient.BeginDelete": @@ -124,6 +130,35 @@ func (p *PoolsServerTransport) dispatchToMethodFake(req *http.Request, method st } } +func (p *PoolsServerTransport) dispatchCheckNameAvailability(req *http.Request) (*http.Response, error) { + if p.srv.CheckNameAvailability == nil { + return nil, &nonRetriableError{errors.New("fake for method CheckNameAvailability not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DevOpsInfrastructure/checkNameAvailability` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if matches == nil || len(matches) < 1 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armdevopsinfrastructure.CheckNameAvailability](req) + if err != nil { + return nil, err + } + respr, errRespr := p.srv.CheckNameAvailability(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).CheckNameAvailabilityResult, req) + if err != nil { + return nil, err + } + return resp, nil +} + func (p *PoolsServerTransport) dispatchBeginCreateOrUpdate(req *http.Request) (*http.Response, error) { if p.srv.BeginCreateOrUpdate == nil { return nil, &nonRetriableError{errors.New("fake for method BeginCreateOrUpdate not implemented")} diff --git a/sdk/resourcemanager/devopsinfrastructure/armdevopsinfrastructure/imageversions_client.go b/sdk/resourcemanager/devopsinfrastructure/armdevopsinfrastructure/imageversions_client.go index e67fb049e3a9..81e28d410246 100644 --- a/sdk/resourcemanager/devopsinfrastructure/armdevopsinfrastructure/imageversions_client.go +++ b/sdk/resourcemanager/devopsinfrastructure/armdevopsinfrastructure/imageversions_client.go @@ -41,7 +41,7 @@ func NewImageVersionsClient(subscriptionID string, credential azcore.TokenCreden // NewListByImagePager - List ImageVersion resources by Image // -// Generated from API version 2024-10-19 +// Generated from API version 2025-01-21 // - resourceGroupName - The name of the resource group. The name is case insensitive. // - imageName - Name of the image. // - options - ImageVersionsClientListByImageOptions contains the optional parameters for the ImageVersionsClient.NewListByImagePager @@ -89,7 +89,7 @@ func (client *ImageVersionsClient) listByImageCreateRequest(ctx context.Context, return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2024-10-19") + reqQP.Set("api-version", "2025-01-21") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil diff --git a/sdk/resourcemanager/devopsinfrastructure/armdevopsinfrastructure/imageversions_client_example_test.go b/sdk/resourcemanager/devopsinfrastructure/armdevopsinfrastructure/imageversions_client_example_test.go index 7b5921223ee3..06abc8a1f545 100644 --- a/sdk/resourcemanager/devopsinfrastructure/armdevopsinfrastructure/imageversions_client_example_test.go +++ b/sdk/resourcemanager/devopsinfrastructure/armdevopsinfrastructure/imageversions_client_example_test.go @@ -11,7 +11,7 @@ import ( "log" ) -// Generated from example definition: 2024-10-19/ImageVersions_ListByImage.json +// Generated from example definition: 2025-01-21/ImageVersions_ListByImage.json func ExampleImageVersionsClient_NewListByImagePager() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { diff --git a/sdk/resourcemanager/devopsinfrastructure/armdevopsinfrastructure/models.go b/sdk/resourcemanager/devopsinfrastructure/armdevopsinfrastructure/models.go index 6ae02c449a5e..774b38db97c5 100644 --- a/sdk/resourcemanager/devopsinfrastructure/armdevopsinfrastructure/models.go +++ b/sdk/resourcemanager/devopsinfrastructure/armdevopsinfrastructure/models.go @@ -70,6 +70,30 @@ type AzureDevOpsPermissionProfile struct { Users []*string } +// CheckNameAvailability - The parameters used to check the availability of a resource. +type CheckNameAvailability struct { + // REQUIRED; The name of the resource. + Name *string + + // REQUIRED; The type of resource that is used as the scope of the availability check. + Type *ResourceType +} + +// CheckNameAvailabilityResult - The CheckNameAvailability operation response. +type CheckNameAvailabilityResult struct { + // REQUIRED; Availability status of the name. + Available *AvailabilityStatus + + // REQUIRED; A message explaining why the name is unavailable. Will be null if the name is available. + Message *string + + // REQUIRED; The name whose availability was checked. + Name *string + + // REQUIRED; The reason code explaining why the name is unavailable. Will be null if the name is available. + Reason *CheckNameAvailabilityReason +} + // DataDisk - The data disk of the VMSS. type DataDisk struct { // The type of caching to be enabled for the data disks. The default value for caching is readwrite. For information about @@ -198,12 +222,12 @@ type NetworkProfile struct { // Operation - Details of a REST API operation, returned from the Resource Provider Operations API type Operation struct { - // Extensible enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. - ActionType *ActionType - - // READ-ONLY; Localized display information for this particular operation. + // Localized display information for this particular operation. Display *OperationDisplay + // READ-ONLY; Extensible 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 Azure // Resource Manager/control-plane operations. IsDataAction *bool @@ -250,6 +274,9 @@ type Organization struct { // REQUIRED; The Azure DevOps organization URL in which the pool should be created. URL *string + // Determines if the pool should have open access to all projects in this organization. + OpenAccess *bool + // How many machines can be created at maximum in this organization out of the maximumConcurrency of the pool. Parallelism *int32 @@ -319,6 +346,9 @@ type PoolImage struct { // The percentage of the buffer to be allocated to this image. Buffer *string + // The ephemeral type of the image. + EphemeralType *EphemeralType + // The resource id of the image. ResourceID *string @@ -589,6 +619,9 @@ type SecretsManagementSettings struct { // Where to store certificates on the machine. CertificateStoreLocation *string + + // Name of the certificate store to use on the machine, currently 'My' and 'Root' are supported. + CertificateStoreName *CertificateStoreNameOption } // Stateful profile meaning that the machines will be returned to the pool after running a job. diff --git a/sdk/resourcemanager/devopsinfrastructure/armdevopsinfrastructure/models_serde.go b/sdk/resourcemanager/devopsinfrastructure/armdevopsinfrastructure/models_serde.go index 507dc3d52167..259b1d3c84f7 100644 --- a/sdk/resourcemanager/devopsinfrastructure/armdevopsinfrastructure/models_serde.go +++ b/sdk/resourcemanager/devopsinfrastructure/armdevopsinfrastructure/models_serde.go @@ -147,6 +147,76 @@ func (a *AzureDevOpsPermissionProfile) UnmarshalJSON(data []byte) error { return nil } +// MarshalJSON implements the json.Marshaller interface for type CheckNameAvailability. +func (c CheckNameAvailability) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", c.Name) + populate(objectMap, "type", c.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CheckNameAvailability. +func (c *CheckNameAvailability) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &c.Name) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &c.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CheckNameAvailabilityResult. +func (c CheckNameAvailabilityResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "available", c.Available) + populate(objectMap, "message", c.Message) + populate(objectMap, "name", c.Name) + populate(objectMap, "reason", c.Reason) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CheckNameAvailabilityResult. +func (c *CheckNameAvailabilityResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "available": + err = unpopulate(val, "Available", &c.Available) + delete(rawMsg, key) + case "message": + err = unpopulate(val, "Message", &c.Message) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &c.Name) + delete(rawMsg, key) + case "reason": + err = unpopulate(val, "Reason", &c.Reason) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + // MarshalJSON implements the json.Marshaller interface for type DataDisk. func (d DataDisk) MarshalJSON() ([]byte, error) { objectMap := make(map[string]any) @@ -612,6 +682,7 @@ func (o *OperationListResult) UnmarshalJSON(data []byte) error { // MarshalJSON implements the json.Marshaller interface for type Organization. func (o Organization) MarshalJSON() ([]byte, error) { objectMap := make(map[string]any) + populate(objectMap, "openAccess", o.OpenAccess) populate(objectMap, "parallelism", o.Parallelism) populate(objectMap, "projects", o.Projects) populate(objectMap, "url", o.URL) @@ -627,6 +698,9 @@ func (o *Organization) UnmarshalJSON(data []byte) error { for key, val := range rawMsg { var err error switch key { + case "openAccess": + err = unpopulate(val, "OpenAccess", &o.OpenAccess) + delete(rawMsg, key) case "parallelism": err = unpopulate(val, "Parallelism", &o.Parallelism) delete(rawMsg, key) @@ -793,6 +867,7 @@ func (p PoolImage) MarshalJSON() ([]byte, error) { objectMap := make(map[string]any) populate(objectMap, "aliases", p.Aliases) populate(objectMap, "buffer", p.Buffer) + populate(objectMap, "ephemeralType", p.EphemeralType) populate(objectMap, "resourceId", p.ResourceID) populate(objectMap, "wellKnownImageName", p.WellKnownImageName) return json.Marshal(objectMap) @@ -813,6 +888,9 @@ func (p *PoolImage) UnmarshalJSON(data []byte) error { case "buffer": err = unpopulate(val, "Buffer", &p.Buffer) delete(rawMsg, key) + case "ephemeralType": + err = unpopulate(val, "EphemeralType", &p.EphemeralType) + delete(rawMsg, key) case "resourceId": err = unpopulate(val, "ResourceID", &p.ResourceID) delete(rawMsg, key) @@ -1497,6 +1575,7 @@ func (r *ResourceSKUZoneDetails) UnmarshalJSON(data []byte) error { func (s SecretsManagementSettings) MarshalJSON() ([]byte, error) { objectMap := make(map[string]any) populate(objectMap, "certificateStoreLocation", s.CertificateStoreLocation) + populate(objectMap, "certificateStoreName", s.CertificateStoreName) populate(objectMap, "keyExportable", s.KeyExportable) populate(objectMap, "observedCertificates", s.ObservedCertificates) return json.Marshal(objectMap) @@ -1514,6 +1593,9 @@ func (s *SecretsManagementSettings) UnmarshalJSON(data []byte) error { case "certificateStoreLocation": err = unpopulate(val, "CertificateStoreLocation", &s.CertificateStoreLocation) delete(rawMsg, key) + case "certificateStoreName": + err = unpopulate(val, "CertificateStoreName", &s.CertificateStoreName) + delete(rawMsg, key) case "keyExportable": err = unpopulate(val, "KeyExportable", &s.KeyExportable) delete(rawMsg, key) diff --git a/sdk/resourcemanager/devopsinfrastructure/armdevopsinfrastructure/operations_client.go b/sdk/resourcemanager/devopsinfrastructure/armdevopsinfrastructure/operations_client.go index ed41fb299331..dcc7f2d33a53 100644 --- a/sdk/resourcemanager/devopsinfrastructure/armdevopsinfrastructure/operations_client.go +++ b/sdk/resourcemanager/devopsinfrastructure/armdevopsinfrastructure/operations_client.go @@ -35,7 +35,7 @@ func NewOperationsClient(credential azcore.TokenCredential, options *arm.ClientO // NewListPager - List the operations for the provider // -// Generated from API version 2024-10-19 +// Generated from API version 2025-01-21 // - 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]{ @@ -68,7 +68,7 @@ func (client *OperationsClient) listCreateRequest(ctx context.Context, _ *Operat return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2024-10-19") + reqQP.Set("api-version", "2025-01-21") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil diff --git a/sdk/resourcemanager/devopsinfrastructure/armdevopsinfrastructure/operations_client_example_test.go b/sdk/resourcemanager/devopsinfrastructure/armdevopsinfrastructure/operations_client_example_test.go index 3808c6d3cfac..cabc7014187d 100644 --- a/sdk/resourcemanager/devopsinfrastructure/armdevopsinfrastructure/operations_client_example_test.go +++ b/sdk/resourcemanager/devopsinfrastructure/armdevopsinfrastructure/operations_client_example_test.go @@ -11,7 +11,7 @@ import ( "log" ) -// Generated from example definition: 2024-10-19/ListOperations.json +// Generated from example definition: 2025-01-21/ListOperations.json func ExampleOperationsClient_NewListPager() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { diff --git a/sdk/resourcemanager/devopsinfrastructure/armdevopsinfrastructure/options.go b/sdk/resourcemanager/devopsinfrastructure/armdevopsinfrastructure/options.go index 2da748c0acfc..8043e77cc7fd 100644 --- a/sdk/resourcemanager/devopsinfrastructure/armdevopsinfrastructure/options.go +++ b/sdk/resourcemanager/devopsinfrastructure/armdevopsinfrastructure/options.go @@ -33,6 +33,11 @@ type PoolsClientBeginUpdateOptions struct { ResumeToken string } +// PoolsClientCheckNameAvailabilityOptions contains the optional parameters for the PoolsClient.CheckNameAvailability method. +type PoolsClientCheckNameAvailabilityOptions struct { + // placeholder for future optional parameters +} + // PoolsClientGetOptions contains the optional parameters for the PoolsClient.Get method. type PoolsClientGetOptions struct { // placeholder for future optional parameters diff --git a/sdk/resourcemanager/devopsinfrastructure/armdevopsinfrastructure/pools_client.go b/sdk/resourcemanager/devopsinfrastructure/armdevopsinfrastructure/pools_client.go index 94873e863f47..6deb49e7a07a 100644 --- a/sdk/resourcemanager/devopsinfrastructure/armdevopsinfrastructure/pools_client.go +++ b/sdk/resourcemanager/devopsinfrastructure/armdevopsinfrastructure/pools_client.go @@ -39,10 +39,70 @@ func NewPoolsClient(subscriptionID string, credential azcore.TokenCredential, op return client, nil } +// CheckNameAvailability - Checks that the pool name is valid and is not already in use. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2025-01-21 +// - body - The CheckAvailability request +// - options - PoolsClientCheckNameAvailabilityOptions contains the optional parameters for the PoolsClient.CheckNameAvailability +// method. +func (client *PoolsClient) CheckNameAvailability(ctx context.Context, body CheckNameAvailability, options *PoolsClientCheckNameAvailabilityOptions) (PoolsClientCheckNameAvailabilityResponse, error) { + var err error + const operationName = "PoolsClient.CheckNameAvailability" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.checkNameAvailabilityCreateRequest(ctx, body, options) + if err != nil { + return PoolsClientCheckNameAvailabilityResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return PoolsClientCheckNameAvailabilityResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return PoolsClientCheckNameAvailabilityResponse{}, err + } + resp, err := client.checkNameAvailabilityHandleResponse(httpResp) + return resp, err +} + +// checkNameAvailabilityCreateRequest creates the CheckNameAvailability request. +func (client *PoolsClient) checkNameAvailabilityCreateRequest(ctx context.Context, body CheckNameAvailability, _ *PoolsClientCheckNameAvailabilityOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.DevOpsInfrastructure/checkNameAvailability" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2025-01-21") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// checkNameAvailabilityHandleResponse handles the CheckNameAvailability response. +func (client *PoolsClient) checkNameAvailabilityHandleResponse(resp *http.Response) (PoolsClientCheckNameAvailabilityResponse, error) { + result := PoolsClientCheckNameAvailabilityResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.CheckNameAvailabilityResult); err != nil { + return PoolsClientCheckNameAvailabilityResponse{}, err + } + return result, nil +} + // BeginCreateOrUpdate - Create a Pool // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2024-10-19 +// Generated from API version 2025-01-21 // - resourceGroupName - The name of the resource group. The name is case insensitive. // - poolName - Name of the pool. It needs to be globally unique. // - resource - Resource create parameters. @@ -69,7 +129,7 @@ func (client *PoolsClient) BeginCreateOrUpdate(ctx context.Context, resourceGrou // CreateOrUpdate - Create a Pool // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2024-10-19 +// Generated from API version 2025-01-21 func (client *PoolsClient) createOrUpdate(ctx context.Context, resourceGroupName string, poolName string, resource Pool, options *PoolsClientBeginCreateOrUpdateOptions) (*http.Response, error) { var err error const operationName = "PoolsClient.BeginCreateOrUpdate" @@ -111,7 +171,7 @@ func (client *PoolsClient) createOrUpdateCreateRequest(ctx context.Context, reso return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2024-10-19") + reqQP.Set("api-version", "2025-01-21") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} req.Raw().Header["Content-Type"] = []string{"application/json"} @@ -124,7 +184,7 @@ func (client *PoolsClient) createOrUpdateCreateRequest(ctx context.Context, reso // BeginDelete - Delete a Pool // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2024-10-19 +// Generated from API version 2025-01-21 // - resourceGroupName - The name of the resource group. The name is case insensitive. // - poolName - Name of the pool. It needs to be globally unique. // - options - PoolsClientBeginDeleteOptions contains the optional parameters for the PoolsClient.BeginDelete method. @@ -148,7 +208,7 @@ func (client *PoolsClient) BeginDelete(ctx context.Context, resourceGroupName st // Delete - Delete a Pool // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2024-10-19 +// Generated from API version 2025-01-21 func (client *PoolsClient) deleteOperation(ctx context.Context, resourceGroupName string, poolName string, options *PoolsClientBeginDeleteOptions) (*http.Response, error) { var err error const operationName = "PoolsClient.BeginDelete" @@ -190,7 +250,7 @@ func (client *PoolsClient) deleteCreateRequest(ctx context.Context, resourceGrou return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2024-10-19") + reqQP.Set("api-version", "2025-01-21") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -199,7 +259,7 @@ func (client *PoolsClient) deleteCreateRequest(ctx context.Context, resourceGrou // Get - Get a Pool // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2024-10-19 +// Generated from API version 2025-01-21 // - resourceGroupName - The name of the resource group. The name is case insensitive. // - poolName - Name of the pool. It needs to be globally unique. // - options - PoolsClientGetOptions contains the optional parameters for the PoolsClient.Get method. @@ -245,7 +305,7 @@ func (client *PoolsClient) getCreateRequest(ctx context.Context, resourceGroupNa return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2024-10-19") + reqQP.Set("api-version", "2025-01-21") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -262,7 +322,7 @@ func (client *PoolsClient) getHandleResponse(resp *http.Response) (PoolsClientGe // NewListByResourceGroupPager - List Pool resources by resource group // -// Generated from API version 2024-10-19 +// Generated from API version 2025-01-21 // - resourceGroupName - The name of the resource group. The name is case insensitive. // - options - PoolsClientListByResourceGroupOptions contains the optional parameters for the PoolsClient.NewListByResourceGroupPager // method. @@ -305,7 +365,7 @@ func (client *PoolsClient) listByResourceGroupCreateRequest(ctx context.Context, return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2024-10-19") + reqQP.Set("api-version", "2025-01-21") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -322,7 +382,7 @@ func (client *PoolsClient) listByResourceGroupHandleResponse(resp *http.Response // NewListBySubscriptionPager - List Pool resources by subscription ID // -// Generated from API version 2024-10-19 +// Generated from API version 2025-01-21 // - options - PoolsClientListBySubscriptionOptions contains the optional parameters for the PoolsClient.NewListBySubscriptionPager // method. func (client *PoolsClient) NewListBySubscriptionPager(options *PoolsClientListBySubscriptionOptions) *runtime.Pager[PoolsClientListBySubscriptionResponse] { @@ -360,7 +420,7 @@ func (client *PoolsClient) listBySubscriptionCreateRequest(ctx context.Context, return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2024-10-19") + reqQP.Set("api-version", "2025-01-21") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -378,7 +438,7 @@ func (client *PoolsClient) listBySubscriptionHandleResponse(resp *http.Response) // BeginUpdate - Update a Pool // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2024-10-19 +// Generated from API version 2025-01-21 // - resourceGroupName - The name of the resource group. The name is case insensitive. // - poolName - Name of the pool. It needs to be globally unique. // - properties - The resource properties to be updated. @@ -403,7 +463,7 @@ func (client *PoolsClient) BeginUpdate(ctx context.Context, resourceGroupName st // Update - Update a Pool // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2024-10-19 +// Generated from API version 2025-01-21 func (client *PoolsClient) update(ctx context.Context, resourceGroupName string, poolName string, properties PoolUpdate, options *PoolsClientBeginUpdateOptions) (*http.Response, error) { var err error const operationName = "PoolsClient.BeginUpdate" @@ -445,7 +505,7 @@ func (client *PoolsClient) updateCreateRequest(ctx context.Context, resourceGrou return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2024-10-19") + reqQP.Set("api-version", "2025-01-21") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} req.Raw().Header["Content-Type"] = []string{"application/json"} diff --git a/sdk/resourcemanager/devopsinfrastructure/armdevopsinfrastructure/pools_client_example_test.go b/sdk/resourcemanager/devopsinfrastructure/armdevopsinfrastructure/pools_client_example_test.go index 7212fff354d0..4e09902a6239 100644 --- a/sdk/resourcemanager/devopsinfrastructure/armdevopsinfrastructure/pools_client_example_test.go +++ b/sdk/resourcemanager/devopsinfrastructure/armdevopsinfrastructure/pools_client_example_test.go @@ -12,7 +12,38 @@ import ( "log" ) -// Generated from example definition: 2024-10-19/CreateOrUpdatePool.json +// Generated from example definition: 2025-01-21/Pools_CheckNameAvailability.json +func ExamplePoolsClient_CheckNameAvailability() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armdevopsinfrastructure.NewClientFactory("a2e95d27-c161-4b61-bda4-11512c14c2c2", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + res, err := clientFactory.NewPoolsClient().CheckNameAvailability(ctx, armdevopsinfrastructure.CheckNameAvailability{ + Name: to.Ptr("mydevopspool"), + Type: to.Ptr(armdevopsinfrastructure.ResourceTypeMicrosoftDevOpsInfrastructurePools), + }, nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + // You could use response here. We use blank identifier for just demo purposes. + _ = res + // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // res = armdevopsinfrastructure.PoolsClientCheckNameAvailabilityResponse{ + // CheckNameAvailabilityResult: &armdevopsinfrastructure.CheckNameAvailabilityResult{ + // Available: to.Ptr(armdevopsinfrastructure.AvailabilityStatusUnavailable), + // Message: to.Ptr("Managed DevOps pool mydevopspool is already in use. Please choose a pool name that has not been taken."), + // Name: to.Ptr("mydevopspool"), + // Reason: to.Ptr(armdevopsinfrastructure.CheckNameAvailabilityReasonAlreadyExists), + // }, + // } +} + +// Generated from example definition: 2025-01-21/CreateOrUpdatePool.json func ExamplePoolsClient_BeginCreateOrUpdate() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { @@ -33,7 +64,8 @@ func ExamplePoolsClient_BeginCreateOrUpdate() { Kind: to.Ptr("AzureDevOps"), Organizations: []*armdevopsinfrastructure.Organization{ { - URL: to.Ptr("https://mseng.visualstudio.com"), + URL: to.Ptr("https://mseng.visualstudio.com"), + OpenAccess: to.Ptr(true), }, }, }, @@ -47,7 +79,17 @@ func ExamplePoolsClient_BeginCreateOrUpdate() { }, Images: []*armdevopsinfrastructure.PoolImage{ { - ResourceID: to.Ptr("/MicrosoftWindowsServer/WindowsServer/2019-Datacenter/latest"), + ResourceID: to.Ptr("/MicrosoftWindowsServer/WindowsServer/2019-Datacenter/latest"), + EphemeralType: to.Ptr(armdevopsinfrastructure.EphemeralTypeAutomatic), + }, + }, + OSProfile: &armdevopsinfrastructure.OsProfile{ + SecretsManagementSettings: &armdevopsinfrastructure.SecretsManagementSettings{ + CertificateStoreName: to.Ptr(armdevopsinfrastructure.CertificateStoreNameOptionRoot), + ObservedCertificates: []*string{ + to.Ptr("https://abc.vault.azure.net/secrets/one"), + }, + KeyExportable: to.Ptr(false), }, }, }, @@ -90,6 +132,15 @@ func ExamplePoolsClient_BeginCreateOrUpdate() { // ResourceID: to.Ptr("/MicrosoftWindowsServer/WindowsServer/2019-Datacenter/latest"), // }, // }, + // OSProfile: &armdevopsinfrastructure.OsProfile{ + // SecretsManagementSettings: &armdevopsinfrastructure.SecretsManagementSettings{ + // CertificateStoreName: to.Ptr(armdevopsinfrastructure.CertificateStoreNameOptionRoot), + // ObservedCertificates: []*string{ + // to.Ptr("https://abc.vault.azure.net/secrets/one"), + // }, + // KeyExportable: to.Ptr(false), + // }, + // }, // }, // }, // ID: to.Ptr("/subscriptions/a2e95d27-c161-4b61-bda4-11512c14c2c2/resourceGroups/rg/providers/Microsoft.DevOpsInfrastructure/Pools/pool"), @@ -98,7 +149,7 @@ func ExamplePoolsClient_BeginCreateOrUpdate() { // } } -// Generated from example definition: 2024-10-19/DeletePool.json +// Generated from example definition: 2025-01-21/DeletePool.json func ExamplePoolsClient_BeginDelete() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { @@ -119,7 +170,7 @@ func ExamplePoolsClient_BeginDelete() { } } -// Generated from example definition: 2024-10-19/GetPool.json +// Generated from example definition: 2025-01-21/GetPool.json func ExamplePoolsClient_Get() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { @@ -172,7 +223,7 @@ func ExamplePoolsClient_Get() { // } } -// Generated from example definition: 2024-10-19/ListPoolsBySubscriptionAndResourceGroup.json +// Generated from example definition: 2025-01-21/ListPoolsBySubscriptionAndResourceGroup.json func ExamplePoolsClient_NewListByResourceGroupPager() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { @@ -207,7 +258,7 @@ func ExamplePoolsClient_NewListByResourceGroupPager() { } } -// Generated from example definition: 2024-10-19/ListPoolsBySubscription.json +// Generated from example definition: 2025-01-21/ListPoolsBySubscription.json func ExamplePoolsClient_NewListBySubscriptionPager() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { @@ -242,7 +293,7 @@ func ExamplePoolsClient_NewListBySubscriptionPager() { } } -// Generated from example definition: 2024-10-19/UpdatePool.json +// Generated from example definition: 2025-01-21/UpdatePool.json func ExamplePoolsClient_BeginUpdate() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { diff --git a/sdk/resourcemanager/devopsinfrastructure/armdevopsinfrastructure/resourcedetails_client.go b/sdk/resourcemanager/devopsinfrastructure/armdevopsinfrastructure/resourcedetails_client.go index a6f45ca24b4d..6cef375578f4 100644 --- a/sdk/resourcemanager/devopsinfrastructure/armdevopsinfrastructure/resourcedetails_client.go +++ b/sdk/resourcemanager/devopsinfrastructure/armdevopsinfrastructure/resourcedetails_client.go @@ -41,7 +41,7 @@ func NewResourceDetailsClient(subscriptionID string, credential azcore.TokenCred // NewListByPoolPager - List ResourceDetailsObject resources by Pool // -// Generated from API version 2024-10-19 +// Generated from API version 2025-01-21 // - resourceGroupName - The name of the resource group. The name is case insensitive. // - poolName - Name of the pool. It needs to be globally unique. // - options - ResourceDetailsClientListByPoolOptions contains the optional parameters for the ResourceDetailsClient.NewListByPoolPager @@ -89,7 +89,7 @@ func (client *ResourceDetailsClient) listByPoolCreateRequest(ctx context.Context return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2024-10-19") + reqQP.Set("api-version", "2025-01-21") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil diff --git a/sdk/resourcemanager/devopsinfrastructure/armdevopsinfrastructure/resourcedetails_client_example_test.go b/sdk/resourcemanager/devopsinfrastructure/armdevopsinfrastructure/resourcedetails_client_example_test.go index 958a8be7c85a..5987c15e59a6 100644 --- a/sdk/resourcemanager/devopsinfrastructure/armdevopsinfrastructure/resourcedetails_client_example_test.go +++ b/sdk/resourcemanager/devopsinfrastructure/armdevopsinfrastructure/resourcedetails_client_example_test.go @@ -11,7 +11,7 @@ import ( "log" ) -// Generated from example definition: 2024-10-19/ResourceDetails_ListByPool.json +// Generated from example definition: 2025-01-21/ResourceDetails_ListByPool.json func ExampleResourceDetailsClient_NewListByPoolPager() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { diff --git a/sdk/resourcemanager/devopsinfrastructure/armdevopsinfrastructure/responses.go b/sdk/resourcemanager/devopsinfrastructure/armdevopsinfrastructure/responses.go index ca74a46c3c40..c23ebf41bc71 100644 --- a/sdk/resourcemanager/devopsinfrastructure/armdevopsinfrastructure/responses.go +++ b/sdk/resourcemanager/devopsinfrastructure/armdevopsinfrastructure/responses.go @@ -16,6 +16,12 @@ type OperationsClientListResponse struct { OperationListResult } +// PoolsClientCheckNameAvailabilityResponse contains the response from method PoolsClient.CheckNameAvailability. +type PoolsClientCheckNameAvailabilityResponse struct { + // The CheckNameAvailability operation response. + CheckNameAvailabilityResult +} + // PoolsClientCreateOrUpdateResponse contains the response from method PoolsClient.BeginCreateOrUpdate. type PoolsClientCreateOrUpdateResponse struct { // Concrete tracked resource types can be created by aliasing this type using a specific property type. diff --git a/sdk/resourcemanager/devopsinfrastructure/armdevopsinfrastructure/sku_client.go b/sdk/resourcemanager/devopsinfrastructure/armdevopsinfrastructure/sku_client.go index 1b3a6762c841..a0eb66968680 100644 --- a/sdk/resourcemanager/devopsinfrastructure/armdevopsinfrastructure/sku_client.go +++ b/sdk/resourcemanager/devopsinfrastructure/armdevopsinfrastructure/sku_client.go @@ -41,7 +41,7 @@ func NewSKUClient(subscriptionID string, credential azcore.TokenCredential, opti // NewListByLocationPager - List ResourceSku resources by subscription ID // -// Generated from API version 2024-10-19 +// Generated from API version 2025-01-21 // - locationName - Name of the location. // - options - SKUClientListByLocationOptions contains the optional parameters for the SKUClient.NewListByLocationPager method. func (client *SKUClient) NewListByLocationPager(locationName string, options *SKUClientListByLocationOptions) *runtime.Pager[SKUClientListByLocationResponse] { @@ -83,7 +83,7 @@ func (client *SKUClient) listByLocationCreateRequest(ctx context.Context, locati return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2024-10-19") + reqQP.Set("api-version", "2025-01-21") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil diff --git a/sdk/resourcemanager/devopsinfrastructure/armdevopsinfrastructure/sku_client_example_test.go b/sdk/resourcemanager/devopsinfrastructure/armdevopsinfrastructure/sku_client_example_test.go index 13f94b53335b..85d7e4dfba21 100644 --- a/sdk/resourcemanager/devopsinfrastructure/armdevopsinfrastructure/sku_client_example_test.go +++ b/sdk/resourcemanager/devopsinfrastructure/armdevopsinfrastructure/sku_client_example_test.go @@ -11,7 +11,7 @@ import ( "log" ) -// Generated from example definition: 2024-10-19/Sku_ListByLocation.json +// Generated from example definition: 2025-01-21/Sku_ListByLocation.json func ExampleSKUClient_NewListByLocationPager() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { diff --git a/sdk/resourcemanager/devopsinfrastructure/armdevopsinfrastructure/subscriptionusages_client.go b/sdk/resourcemanager/devopsinfrastructure/armdevopsinfrastructure/subscriptionusages_client.go index f65ab469bb3e..f5ec7c90ba72 100644 --- a/sdk/resourcemanager/devopsinfrastructure/armdevopsinfrastructure/subscriptionusages_client.go +++ b/sdk/resourcemanager/devopsinfrastructure/armdevopsinfrastructure/subscriptionusages_client.go @@ -41,7 +41,7 @@ func NewSubscriptionUsagesClient(subscriptionID string, credential azcore.TokenC // NewUsagesPager - List Quota resources by subscription ID // -// Generated from API version 2024-10-19 +// Generated from API version 2025-01-21 // - location - The name of the Azure region. // - options - SubscriptionUsagesClientUsagesOptions contains the optional parameters for the SubscriptionUsagesClient.NewUsagesPager // method. @@ -84,7 +84,7 @@ func (client *SubscriptionUsagesClient) usagesCreateRequest(ctx context.Context, return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2024-10-19") + reqQP.Set("api-version", "2025-01-21") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil diff --git a/sdk/resourcemanager/devopsinfrastructure/armdevopsinfrastructure/subscriptionusages_client_example_test.go b/sdk/resourcemanager/devopsinfrastructure/armdevopsinfrastructure/subscriptionusages_client_example_test.go index 89ea9b79654c..a78a73d9d59b 100644 --- a/sdk/resourcemanager/devopsinfrastructure/armdevopsinfrastructure/subscriptionusages_client_example_test.go +++ b/sdk/resourcemanager/devopsinfrastructure/armdevopsinfrastructure/subscriptionusages_client_example_test.go @@ -11,7 +11,7 @@ import ( "log" ) -// Generated from example definition: 2024-10-19/SubscriptionUsages_Usages.json +// Generated from example definition: 2025-01-21/SubscriptionUsages_Usages.json func ExampleSubscriptionUsagesClient_NewUsagesPager() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { diff --git a/sdk/resourcemanager/devopsinfrastructure/armdevopsinfrastructure/tsp-location.yaml b/sdk/resourcemanager/devopsinfrastructure/armdevopsinfrastructure/tsp-location.yaml index 77686a6437bb..23cc03291c63 100644 --- a/sdk/resourcemanager/devopsinfrastructure/armdevopsinfrastructure/tsp-location.yaml +++ b/sdk/resourcemanager/devopsinfrastructure/armdevopsinfrastructure/tsp-location.yaml @@ -1,4 +1,4 @@ directory: specification/devopsinfrastructure/Microsoft.DevOpsInfrastructure.Management -commit: d477c7caa09bf82e22c419be0a99d170552b5892 +commit: 1f578543d267d08febc1bebf4e33ffe14363ddfc repo: Azure/azure-rest-api-specs additionalDirectories: diff --git a/sdk/resourcemanager/durabletask/armdurabletask/CHANGELOG.md b/sdk/resourcemanager/durabletask/armdurabletask/CHANGELOG.md index f098324d1648..403ce002f58f 100644 --- a/sdk/resourcemanager/durabletask/armdurabletask/CHANGELOG.md +++ b/sdk/resourcemanager/durabletask/armdurabletask/CHANGELOG.md @@ -1,5 +1,9 @@ # Release History +## 0.2.1 (2025-04-27) +### Other Changes + + ## 0.2.0 (2025-04-15) ### Features Added diff --git a/sdk/resourcemanager/durabletask/armdurabletask/constants.go b/sdk/resourcemanager/durabletask/armdurabletask/constants.go index 77ab322ab146..7c1717d06c2f 100644 --- a/sdk/resourcemanager/durabletask/armdurabletask/constants.go +++ b/sdk/resourcemanager/durabletask/armdurabletask/constants.go @@ -6,7 +6,7 @@ package armdurabletask const ( moduleName = "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/durabletask/armdurabletask" - moduleVersion = "v0.2.0" + moduleVersion = "v0.2.1" ) // ActionType - Extensible enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. @@ -107,7 +107,7 @@ func PossibleProvisioningStateValues() []ProvisioningState { type PurgeableOrchestrationState string const ( - // PurgeableOrchestrationStateCanceled - The orchestration is terminated + // PurgeableOrchestrationStateCanceled - The orchestration is canceled PurgeableOrchestrationStateCanceled PurgeableOrchestrationState = "Canceled" // PurgeableOrchestrationStateCompleted - The orchestration is completed PurgeableOrchestrationStateCompleted PurgeableOrchestrationState = "Completed" diff --git a/sdk/resourcemanager/durabletask/armdurabletask/tsp-location.yaml b/sdk/resourcemanager/durabletask/armdurabletask/tsp-location.yaml index 569d0255b202..b33a7389cfdf 100644 --- a/sdk/resourcemanager/durabletask/armdurabletask/tsp-location.yaml +++ b/sdk/resourcemanager/durabletask/armdurabletask/tsp-location.yaml @@ -1,4 +1,4 @@ directory: specification/durabletask/DurableTask.Management -commit: 95eda2b9a673690afab68824d5d68b09c026dcdd +commit: 1f578543d267d08febc1bebf4e33ffe14363ddfc repo: Azure/azure-rest-api-specs -additionalDirectories: \ No newline at end of file +additionalDirectories: diff --git a/sdk/resourcemanager/edgezones/armedgezones/CHANGELOG.md b/sdk/resourcemanager/edgezones/armedgezones/CHANGELOG.md index ca1869b2b5e7..ee4f219bf53e 100644 --- a/sdk/resourcemanager/edgezones/armedgezones/CHANGELOG.md +++ b/sdk/resourcemanager/edgezones/armedgezones/CHANGELOG.md @@ -1,5 +1,9 @@ # Release History +## 0.1.1 (2025-04-27) +### Other Changes + + ## 0.1.0 (2024-07-08) ### Other Changes diff --git a/sdk/resourcemanager/edgezones/armedgezones/constants.go b/sdk/resourcemanager/edgezones/armedgezones/constants.go index 63895bc68229..252cf1ee0675 100644 --- a/sdk/resourcemanager/edgezones/armedgezones/constants.go +++ b/sdk/resourcemanager/edgezones/armedgezones/constants.go @@ -6,7 +6,7 @@ package armedgezones const ( moduleName = "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/edgezones/armedgezones" - moduleVersion = "v0.1.0" + moduleVersion = "v0.1.1" ) // ActionType - Extensible enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. diff --git a/sdk/resourcemanager/edgezones/armedgezones/extendedzones_client_example_test.go b/sdk/resourcemanager/edgezones/armedgezones/extendedzones_client_example_test.go new file mode 100644 index 000000000000..fd5ddbe17eca --- /dev/null +++ b/sdk/resourcemanager/edgezones/armedgezones/extendedzones_client_example_test.go @@ -0,0 +1,199 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armedgezones_test + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azidentity" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/edgezones/armedgezones" + "log" +) + +// Generated from example definition: 2024-04-01-preview/ExtendedZones_Get.json +func ExampleExtendedZonesClient_Get() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armedgezones.NewClientFactory("a1ffc958-d2c7-493e-9f1e-125a0477f536", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + res, err := clientFactory.NewExtendedZonesClient().Get(ctx, "losangeles", nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + // You could use response here. We use blank identifier for just demo purposes. + _ = res + // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // res = armedgezones.ExtendedZonesClientGetResponse{ + // ExtendedZone: &armedgezones.ExtendedZone{ + // ID: to.Ptr("/subscriptions/a1ffc958-d2c7-493e-9f1e-125a0477f536/providers/Microsoft.EdgeZones/extendedZones/losangeles"), + // Name: to.Ptr("losangeles"), + // Type: to.Ptr("Microsoft.EdgeZones/extendedZones"), + // Properties: &armedgezones.ExtendedZoneProperties{ + // ProvisioningState: to.Ptr(armedgezones.ProvisioningStateSucceeded), + // RegistrationState: to.Ptr(armedgezones.RegistrationStateNotRegistered), + // DisplayName: to.Ptr("Los Angeles"), + // RegionalDisplayName: to.Ptr("(US) Los Angeles"), + // RegionType: to.Ptr("Physical"), + // RegionCategory: to.Ptr("Other"), + // Geography: to.Ptr("usa"), + // GeographyGroup: to.Ptr("US"), + // Longitude: to.Ptr("-118.23537"), + // Latitude: to.Ptr("34.058414"), + // HomeLocation: to.Ptr("westus"), + // }, + // }, + // } +} + +// Generated from example definition: 2024-04-01-preview/ExtendedZones_ListBySubscription.json +func ExampleExtendedZonesClient_NewListBySubscriptionPager() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armedgezones.NewClientFactory("a1ffc958-d2c7-493e-9f1e-125a0477f536", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + pager := clientFactory.NewExtendedZonesClient().NewListBySubscriptionPager(nil) + for pager.More() { + page, err := pager.NextPage(ctx) + if err != nil { + log.Fatalf("failed to advance page: %v", err) + } + for _, v := range page.Value { + // You could use page here. We use blank identifier for just demo purposes. + _ = v + } + // If the HTTP response code is 200 as defined in example definition, your page structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // page = armedgezones.ExtendedZonesClientListBySubscriptionResponse{ + // ExtendedZoneListResult: armedgezones.ExtendedZoneListResult{ + // Value: []*armedgezones.ExtendedZone{ + // { + // ID: to.Ptr("/subscriptions/a1ffc958-d2c7-493e-9f1e-125a0477f536/providers/Microsoft.EdgeZones/extendedZones/redmond"), + // Name: to.Ptr("redmond"), + // Type: to.Ptr("Microsoft.EdgeZones/extendedZones"), + // Properties: &armedgezones.ExtendedZoneProperties{ + // ProvisioningState: to.Ptr(armedgezones.ProvisioningStateSucceeded), + // RegistrationState: to.Ptr(armedgezones.RegistrationStateNotRegistered), + // DisplayName: to.Ptr("Redmond"), + // RegionalDisplayName: to.Ptr("(US) Redmond"), + // RegionType: to.Ptr("Physical"), + // RegionCategory: to.Ptr("Other"), + // Geography: to.Ptr("usa"), + // GeographyGroup: to.Ptr("US"), + // Longitude: to.Ptr("-122.03197"), + // Latitude: to.Ptr("47.69106"), + // HomeLocation: to.Ptr("westus"), + // }, + // }, + // { + // ID: to.Ptr("/subscriptions/a1ffc958-d2c7-493e-9f1e-125a0477f536/providers/Microsoft.EdgeZones/extendedZones/losangeles"), + // Name: to.Ptr("losangeles"), + // Type: to.Ptr("Microsoft.EdgeZones/extendedZones"), + // Properties: &armedgezones.ExtendedZoneProperties{ + // ProvisioningState: to.Ptr(armedgezones.ProvisioningStateSucceeded), + // RegistrationState: to.Ptr(armedgezones.RegistrationStateNotRegistered), + // DisplayName: to.Ptr("Los Angeles"), + // RegionalDisplayName: to.Ptr("(US) Los Angeles"), + // RegionType: to.Ptr("Physical"), + // RegionCategory: to.Ptr("Other"), + // Geography: to.Ptr("usa"), + // GeographyGroup: to.Ptr("US"), + // Longitude: to.Ptr("-118.23537"), + // Latitude: to.Ptr("34.058414"), + // HomeLocation: to.Ptr("westus"), + // }, + // }, + // }, + // }, + // } + } +} + +// Generated from example definition: 2024-04-01-preview/ExtendedZones_Register.json +func ExampleExtendedZonesClient_Register() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armedgezones.NewClientFactory("a1ffc958-d2c7-493e-9f1e-125a0477f536", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + res, err := clientFactory.NewExtendedZonesClient().Register(ctx, "losangeles", nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + // You could use response here. We use blank identifier for just demo purposes. + _ = res + // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // res = armedgezones.ExtendedZonesClientRegisterResponse{ + // ExtendedZone: &armedgezones.ExtendedZone{ + // ID: to.Ptr("/subscriptions/a1ffc958-d2c7-493e-9f1e-125a0477f536/providers/Microsoft.EdgeZones/extendedZones/losangeles"), + // Name: to.Ptr("losangeles"), + // Type: to.Ptr("Microsoft.EdgeZones/extendedZones"), + // Properties: &armedgezones.ExtendedZoneProperties{ + // ProvisioningState: to.Ptr(armedgezones.ProvisioningStateSucceeded), + // RegistrationState: to.Ptr(armedgezones.RegistrationStatePendingRegister), + // DisplayName: to.Ptr("Los Angeles"), + // RegionalDisplayName: to.Ptr("(US) Los Angeles"), + // RegionType: to.Ptr("Physical"), + // RegionCategory: to.Ptr("Other"), + // Geography: to.Ptr("usa"), + // GeographyGroup: to.Ptr("US"), + // Longitude: to.Ptr("-118.23537"), + // Latitude: to.Ptr("34.058414"), + // HomeLocation: to.Ptr("westus"), + // }, + // }, + // } +} + +// Generated from example definition: 2024-04-01-preview/ExtendedZones_Unregister.json +func ExampleExtendedZonesClient_Unregister() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armedgezones.NewClientFactory("a1ffc958-d2c7-493e-9f1e-125a0477f536", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + res, err := clientFactory.NewExtendedZonesClient().Unregister(ctx, "losangeles", nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + // You could use response here. We use blank identifier for just demo purposes. + _ = res + // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // res = armedgezones.ExtendedZonesClientUnregisterResponse{ + // ExtendedZone: &armedgezones.ExtendedZone{ + // ID: to.Ptr("/subscriptions/a1ffc958-d2c7-493e-9f1e-125a0477f536/providers/Microsoft.EdgeZones/extendedZones/losangeles"), + // Name: to.Ptr("losangeles"), + // Type: to.Ptr("Microsoft.EdgeZones/extendedZones"), + // Properties: &armedgezones.ExtendedZoneProperties{ + // ProvisioningState: to.Ptr(armedgezones.ProvisioningStateSucceeded), + // RegistrationState: to.Ptr(armedgezones.RegistrationStatePendingUnregister), + // DisplayName: to.Ptr("Los Angeles"), + // RegionalDisplayName: to.Ptr("(US) Los Angeles"), + // RegionType: to.Ptr("Physical"), + // RegionCategory: to.Ptr("Other"), + // Geography: to.Ptr("usa"), + // GeographyGroup: to.Ptr("US"), + // Longitude: to.Ptr("-118.23537"), + // Latitude: to.Ptr("34.058414"), + // HomeLocation: to.Ptr("westus"), + // }, + // }, + // } +} diff --git a/sdk/resourcemanager/edgezones/armedgezones/fake/extendedzones_server.go b/sdk/resourcemanager/edgezones/armedgezones/fake/extendedzones_server.go index a7afa6c3916b..d11517be93d7 100644 --- a/sdk/resourcemanager/edgezones/armedgezones/fake/extendedzones_server.go +++ b/sdk/resourcemanager/edgezones/armedgezones/fake/extendedzones_server.go @@ -66,23 +66,42 @@ func (e *ExtendedZonesServerTransport) Do(req *http.Request) (*http.Response, er } func (e *ExtendedZonesServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { - var resp *http.Response - var err error - - switch method { - case "ExtendedZonesClient.Get": - resp, err = e.dispatchGet(req) - case "ExtendedZonesClient.NewListBySubscriptionPager": - resp, err = e.dispatchNewListBySubscriptionPager(req) - case "ExtendedZonesClient.Register": - resp, err = e.dispatchRegister(req) - case "ExtendedZonesClient.Unregister": - resp, err = e.dispatchUnregister(req) - default: - err = fmt.Errorf("unhandled API %s", method) - } - - return resp, err + resultChan := make(chan result) + defer close(resultChan) + + go func() { + var intercepted bool + var res result + if extendedZonesServerTransportInterceptor != nil { + res.resp, res.err, intercepted = extendedZonesServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ExtendedZonesClient.Get": + res.resp, res.err = e.dispatchGet(req) + case "ExtendedZonesClient.NewListBySubscriptionPager": + res.resp, res.err = e.dispatchNewListBySubscriptionPager(req) + case "ExtendedZonesClient.Register": + res.resp, res.err = e.dispatchRegister(req) + case "ExtendedZonesClient.Unregister": + res.resp, res.err = e.dispatchUnregister(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 *ExtendedZonesServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { @@ -204,3 +223,9 @@ func (e *ExtendedZonesServerTransport) dispatchUnregister(req *http.Request) (*h } return resp, nil } + +// set this to conditionally intercept incoming requests to ExtendedZonesServerTransport +var extendedZonesServerTransportInterceptor 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/edgezones/armedgezones/fake/internal.go b/sdk/resourcemanager/edgezones/armedgezones/fake/internal.go index 56a8f624f5f3..7425b6a669e2 100644 --- a/sdk/resourcemanager/edgezones/armedgezones/fake/internal.go +++ b/sdk/resourcemanager/edgezones/armedgezones/fake/internal.go @@ -10,6 +10,11 @@ import ( "sync" ) +type result struct { + resp *http.Response + err error +} + type nonRetriableError struct { error } diff --git a/sdk/resourcemanager/edgezones/armedgezones/fake/operations_server.go b/sdk/resourcemanager/edgezones/armedgezones/fake/operations_server.go index ce9c5fa14931..63dddb8e075e 100644 --- a/sdk/resourcemanager/edgezones/armedgezones/fake/operations_server.go +++ b/sdk/resourcemanager/edgezones/armedgezones/fake/operations_server.go @@ -51,17 +51,36 @@ func (o *OperationsServerTransport) Do(req *http.Request) (*http.Response, error } func (o *OperationsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { - var resp *http.Response - var err error + resultChan := make(chan result) + defer close(resultChan) - switch method { - case "OperationsClient.NewListPager": - resp, err = o.dispatchNewListPager(req) - default: - err = fmt.Errorf("unhandled API %s", method) - } + 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(): + } + }() - return resp, err + 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) { @@ -90,3 +109,9 @@ func (o *OperationsServerTransport) dispatchNewListPager(req *http.Request) (*ht } return resp, nil } + +// set this to conditionally intercept incoming requests to OperationsServerTransport +var operationsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/sdk/resourcemanager/edgezones/armedgezones/go.mod b/sdk/resourcemanager/edgezones/armedgezones/go.mod index 6562f785cbce..453dfbb41304 100644 --- a/sdk/resourcemanager/edgezones/armedgezones/go.mod +++ b/sdk/resourcemanager/edgezones/armedgezones/go.mod @@ -4,13 +4,13 @@ go 1.23.0 require ( github.com/Azure/azure-sdk-for-go/sdk/azcore v1.17.1 + github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.8.2 github.com/Azure/azure-sdk-for-go/sdk/internal v1.11.1 github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/internal/v3 v3.1.0 github.com/stretchr/testify v1.10.0 ) require ( - github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.8.2 // indirect github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/resources/armresources v1.2.0 // indirect github.com/AzureAD/microsoft-authentication-library-for-go v1.4.2 // indirect github.com/davecgh/go-spew v1.1.1 // indirect diff --git a/sdk/resourcemanager/edgezones/armedgezones/models.go b/sdk/resourcemanager/edgezones/armedgezones/models.go index 8545bdd4066e..bce8dae64b02 100644 --- a/sdk/resourcemanager/edgezones/armedgezones/models.go +++ b/sdk/resourcemanager/edgezones/armedgezones/models.go @@ -71,12 +71,12 @@ type ExtendedZoneProperties struct { // Operation - Details of a REST API operation, returned from the Resource Provider Operations API type Operation struct { - // Extensible enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. - ActionType *ActionType - // Localized display information for this particular operation. Display *OperationDisplay + // READ-ONLY; Extensible 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 Azure // Resource Manager/control-plane operations. IsDataAction *bool @@ -92,17 +92,19 @@ type Operation struct { // OperationDisplay - Localized display information for and operation. type OperationDisplay struct { - // The short, localized friendly description of the operation; suitable for tool tips and detailed views. + // READ-ONLY; The short, localized friendly description of the operation; suitable for tool tips and detailed views. Description *string - // The concise, localized friendly name for the operation; suitable for dropdowns. E.g. "Create or Update Virtual Machine", - // "Restart Virtual Machine". + // 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 - // The localized friendly form of the resource provider name, e.g. "Microsoft Monitoring Insights" or "Microsoft Compute". + // READ-ONLY; The localized friendly form of the resource provider name, e.g. "Microsoft Monitoring Insights" or "Microsoft + // Compute". Provider *string - // The localized friendly name of the resource type related to this operation. E.g. "Virtual Machines" or "Job Schedule Collections". + // READ-ONLY; The localized friendly name of the resource type related to this operation. E.g. "Virtual Machines" or "Job + // Schedule Collections". Resource *string } diff --git a/sdk/resourcemanager/edgezones/armedgezones/operations_client_example_test.go b/sdk/resourcemanager/edgezones/armedgezones/operations_client_example_test.go new file mode 100644 index 000000000000..bee1cac63758 --- /dev/null +++ b/sdk/resourcemanager/edgezones/armedgezones/operations_client_example_test.go @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armedgezones_test + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azidentity" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/edgezones/armedgezones" + "log" +) + +// Generated from example definition: 2024-04-01-preview/Operations_List.json +func ExampleOperationsClient_NewListPager() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armedgezones.NewClientFactory("", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + pager := clientFactory.NewOperationsClient().NewListPager(nil) + for pager.More() { + page, err := pager.NextPage(ctx) + if err != nil { + log.Fatalf("failed to advance page: %v", err) + } + for _, v := range page.Value { + // You could use page here. We use blank identifier for just demo purposes. + _ = v + } + // If the HTTP response code is 200 as defined in example definition, your page structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // page = armedgezones.OperationsClientListResponse{ + // OperationListResult: armedgezones.OperationListResult{ + // Value: []*armedgezones.Operation{ + // { + // Name: to.Ptr("Microsoft.EdgeZones/extendedZones/read"), + // Display: &armedgezones.OperationDisplay{ + // Provider: to.Ptr("Microsoft.EdgeZones"), + // Resource: to.Ptr("extendedZones"), + // Operation: to.Ptr("read"), + // }, + // }, + // }, + // }, + // } + } +} diff --git a/sdk/resourcemanager/edgezones/armedgezones/tsp-location.yaml b/sdk/resourcemanager/edgezones/armedgezones/tsp-location.yaml index 5f0bfa9f57a2..4ed7be5c7625 100644 --- a/sdk/resourcemanager/edgezones/armedgezones/tsp-location.yaml +++ b/sdk/resourcemanager/edgezones/armedgezones/tsp-location.yaml @@ -1,4 +1,4 @@ directory: specification/edgezones/EdgeZones.Management -commit: ab064e0047ec560a700d6b501097d99471ad817b -repo: https://github.com/Azure/azure-rest-api-specs -additionalDirectories: +commit: 1f578543d267d08febc1bebf4e33ffe14363ddfc +repo: Azure/azure-rest-api-specs +additionalDirectories: diff --git a/sdk/resourcemanager/lambdatesthyperexecute/armlambdatesthyperexecute/CHANGELOG.md b/sdk/resourcemanager/lambdatesthyperexecute/armlambdatesthyperexecute/CHANGELOG.md new file mode 100644 index 000000000000..2376433f9be2 --- /dev/null +++ b/sdk/resourcemanager/lambdatesthyperexecute/armlambdatesthyperexecute/CHANGELOG.md @@ -0,0 +1,8 @@ +# Release History + +## 0.1.0 (2025-04-27) +### Other Changes + +The package of `github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/lambdatesthyperexecute/armlambdatesthyperexecute` 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/lambdatesthyperexecute/armlambdatesthyperexecute/LICENSE.txt b/sdk/resourcemanager/lambdatesthyperexecute/armlambdatesthyperexecute/LICENSE.txt new file mode 100644 index 000000000000..dc0c2ffb3dc1 --- /dev/null +++ b/sdk/resourcemanager/lambdatesthyperexecute/armlambdatesthyperexecute/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/lambdatesthyperexecute/armlambdatesthyperexecute/README.md b/sdk/resourcemanager/lambdatesthyperexecute/armlambdatesthyperexecute/README.md new file mode 100644 index 000000000000..48fb02087f6f --- /dev/null +++ b/sdk/resourcemanager/lambdatesthyperexecute/armlambdatesthyperexecute/README.md @@ -0,0 +1,90 @@ +# Azure Lambdatesthyperexecute Module for Go + +The `armlambdatesthyperexecute` module provides operations for working with Azure Lambdatesthyperexecute. + +[Source code](https://github.com/Azure/azure-sdk-for-go/tree/main/sdk/resourcemanager/lambdatesthyperexecute/armlambdatesthyperexecute) + +# 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 Lambdatesthyperexecute module: + +```sh +go get github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/lambdatesthyperexecute/armlambdatesthyperexecute +``` + +## Authorization + +When creating a client, you will need to provide a credential for authenticating with Azure Lambdatesthyperexecute. 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 Lambdatesthyperexecute 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 := armlambdatesthyperexecute.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 := armlambdatesthyperexecute.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.NewOrganizationsClient() +``` + +## 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 `Lambdatesthyperexecute` 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/lambdatesthyperexecute/armlambdatesthyperexecute/ci.yml b/sdk/resourcemanager/lambdatesthyperexecute/armlambdatesthyperexecute/ci.yml new file mode 100644 index 000000000000..6cbd9411a2e7 --- /dev/null +++ b/sdk/resourcemanager/lambdatesthyperexecute/armlambdatesthyperexecute/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/lambdatesthyperexecute/armlambdatesthyperexecute/ + +pr: + branches: + include: + - main + - feature/* + - hotfix/* + - release/* + paths: + include: + - sdk/resourcemanager/lambdatesthyperexecute/armlambdatesthyperexecute/ + +extends: + template: /eng/pipelines/templates/jobs/archetype-sdk-client.yml + parameters: + ServiceDirectory: 'resourcemanager/lambdatesthyperexecute/armlambdatesthyperexecute' diff --git a/sdk/resourcemanager/lambdatesthyperexecute/armlambdatesthyperexecute/client_factory.go b/sdk/resourcemanager/lambdatesthyperexecute/armlambdatesthyperexecute/client_factory.go new file mode 100644 index 000000000000..dba50bdb0c46 --- /dev/null +++ b/sdk/resourcemanager/lambdatesthyperexecute/armlambdatesthyperexecute/client_factory.go @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armlambdatesthyperexecute + +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 +} + +// NewOperationsClient creates a new instance of OperationsClient. +func (c *ClientFactory) NewOperationsClient() *OperationsClient { + return &OperationsClient{ + internal: c.internal, + } +} + +// NewOrganizationsClient creates a new instance of OrganizationsClient. +func (c *ClientFactory) NewOrganizationsClient() *OrganizationsClient { + return &OrganizationsClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} diff --git a/sdk/resourcemanager/lambdatesthyperexecute/armlambdatesthyperexecute/constants.go b/sdk/resourcemanager/lambdatesthyperexecute/armlambdatesthyperexecute/constants.go new file mode 100644 index 000000000000..e5226b0e702a --- /dev/null +++ b/sdk/resourcemanager/lambdatesthyperexecute/armlambdatesthyperexecute/constants.go @@ -0,0 +1,180 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armlambdatesthyperexecute + +const ( + moduleName = "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/lambdatesthyperexecute/armlambdatesthyperexecute" + moduleVersion = "v0.1.0" +) + +// ActionType - Extensible enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. +type ActionType string + +const ( + // ActionTypeInternal - Actions are for internal-only APIs. + ActionTypeInternal ActionType = "Internal" +) + +// PossibleActionTypeValues returns the possible values for the ActionType const type. +func PossibleActionTypeValues() []ActionType { + return []ActionType{ + ActionTypeInternal, + } +} + +// CreatedByType - The kind of entity that created the resource. +type CreatedByType string + +const ( + // CreatedByTypeApplication - The entity was created by an application. + CreatedByTypeApplication CreatedByType = "Application" + // CreatedByTypeKey - The entity was created by a key. + CreatedByTypeKey CreatedByType = "Key" + // CreatedByTypeManagedIdentity - The entity was created by a managed identity. + CreatedByTypeManagedIdentity CreatedByType = "ManagedIdentity" + // CreatedByTypeUser - The entity was created by a user. + CreatedByTypeUser CreatedByType = "User" +) + +// PossibleCreatedByTypeValues returns the possible values for the CreatedByType const type. +func PossibleCreatedByTypeValues() []CreatedByType { + return []CreatedByType{ + CreatedByTypeApplication, + CreatedByTypeKey, + CreatedByTypeManagedIdentity, + CreatedByTypeUser, + } +} + +// ManagedServiceIdentityType - Type of managed service identity (where both SystemAssigned and UserAssigned types are allowed). +type ManagedServiceIdentityType string + +const ( + // ManagedServiceIdentityTypeNone - No managed identity. + ManagedServiceIdentityTypeNone ManagedServiceIdentityType = "None" + // ManagedServiceIdentityTypeSystemAssigned - System assigned managed identity. + ManagedServiceIdentityTypeSystemAssigned ManagedServiceIdentityType = "SystemAssigned" + // ManagedServiceIdentityTypeSystemAssignedUserAssigned - System and user assigned managed identity. + ManagedServiceIdentityTypeSystemAssignedUserAssigned ManagedServiceIdentityType = "SystemAssigned,UserAssigned" + // ManagedServiceIdentityTypeUserAssigned - User assigned managed identity. + ManagedServiceIdentityTypeUserAssigned ManagedServiceIdentityType = "UserAssigned" +) + +// PossibleManagedServiceIdentityTypeValues returns the possible values for the ManagedServiceIdentityType const type. +func PossibleManagedServiceIdentityTypeValues() []ManagedServiceIdentityType { + return []ManagedServiceIdentityType{ + ManagedServiceIdentityTypeNone, + ManagedServiceIdentityTypeSystemAssigned, + ManagedServiceIdentityTypeSystemAssignedUserAssigned, + ManagedServiceIdentityTypeUserAssigned, + } +} + +// MarketplaceSubscriptionStatus - Marketplace subscription status of a resource. +type MarketplaceSubscriptionStatus string + +const ( + // MarketplaceSubscriptionStatusPendingFulfillmentStart - Purchased but not yet activated + MarketplaceSubscriptionStatusPendingFulfillmentStart MarketplaceSubscriptionStatus = "PendingFulfillmentStart" + // MarketplaceSubscriptionStatusSubscribed - Marketplace subscription is activated + MarketplaceSubscriptionStatusSubscribed MarketplaceSubscriptionStatus = "Subscribed" + // MarketplaceSubscriptionStatusSuspended - This state indicates that a customer's payment for the Marketplace service was + // not received + MarketplaceSubscriptionStatusSuspended MarketplaceSubscriptionStatus = "Suspended" + // MarketplaceSubscriptionStatusUnsubscribed - Customer has cancelled the subscription + MarketplaceSubscriptionStatusUnsubscribed MarketplaceSubscriptionStatus = "Unsubscribed" +) + +// PossibleMarketplaceSubscriptionStatusValues returns the possible values for the MarketplaceSubscriptionStatus const type. +func PossibleMarketplaceSubscriptionStatusValues() []MarketplaceSubscriptionStatus { + return []MarketplaceSubscriptionStatus{ + MarketplaceSubscriptionStatusPendingFulfillmentStart, + MarketplaceSubscriptionStatusSubscribed, + MarketplaceSubscriptionStatusSuspended, + MarketplaceSubscriptionStatusUnsubscribed, + } +} + +// 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 - Indicates the operation is initiated by a system. + OriginSystem Origin = "system" + // OriginUser - Indicates the operation is initiated by a user. + OriginUser Origin = "user" + // OriginUserSystem - Indicates the operation is initiated by a user or system. + OriginUserSystem Origin = "user,system" +) + +// PossibleOriginValues returns the possible values for the Origin const type. +func PossibleOriginValues() []Origin { + return []Origin{ + OriginSystem, + OriginUser, + OriginUserSystem, + } +} + +// ResourceProvisioningState - The provisioning state of a resource type. +type ResourceProvisioningState string + +const ( + // ResourceProvisioningStateCanceled - Resource creation was canceled. + ResourceProvisioningStateCanceled ResourceProvisioningState = "Canceled" + // ResourceProvisioningStateFailed - Resource creation failed. + ResourceProvisioningStateFailed ResourceProvisioningState = "Failed" + // ResourceProvisioningStateSucceeded - Resource has been created. + ResourceProvisioningStateSucceeded ResourceProvisioningState = "Succeeded" +) + +// PossibleResourceProvisioningStateValues returns the possible values for the ResourceProvisioningState const type. +func PossibleResourceProvisioningStateValues() []ResourceProvisioningState { + return []ResourceProvisioningState{ + ResourceProvisioningStateCanceled, + ResourceProvisioningStateFailed, + ResourceProvisioningStateSucceeded, + } +} + +// SingleSignOnStates - Various states of the SSO resource +type SingleSignOnStates string + +const ( + // SingleSignOnStatesDisable - State of the SSO resource when it is disabled + SingleSignOnStatesDisable SingleSignOnStates = "Disable" + // SingleSignOnStatesEnable - State of the SSO resource when it is enabled + SingleSignOnStatesEnable SingleSignOnStates = "Enable" + // SingleSignOnStatesInitial - Initial state of the SSO resource + SingleSignOnStatesInitial SingleSignOnStates = "Initial" +) + +// PossibleSingleSignOnStatesValues returns the possible values for the SingleSignOnStates const type. +func PossibleSingleSignOnStatesValues() []SingleSignOnStates { + return []SingleSignOnStates{ + SingleSignOnStatesDisable, + SingleSignOnStatesEnable, + SingleSignOnStatesInitial, + } +} + +// SingleSignOnType - Defines the type of Single Sign-On (SSO) mechanism being used +type SingleSignOnType string + +const ( + // SingleSignOnTypeOpenID - OpenID Connect based Single Sign-On. + SingleSignOnTypeOpenID SingleSignOnType = "OpenId" + // SingleSignOnTypeSaml - Security Assertion Markup Language (SAML) based Single Sign-On + SingleSignOnTypeSaml SingleSignOnType = "Saml" +) + +// PossibleSingleSignOnTypeValues returns the possible values for the SingleSignOnType const type. +func PossibleSingleSignOnTypeValues() []SingleSignOnType { + return []SingleSignOnType{ + SingleSignOnTypeOpenID, + SingleSignOnTypeSaml, + } +} diff --git a/sdk/resourcemanager/lambdatesthyperexecute/armlambdatesthyperexecute/fake/internal.go b/sdk/resourcemanager/lambdatesthyperexecute/armlambdatesthyperexecute/fake/internal.go new file mode 100644 index 000000000000..7425b6a669e2 --- /dev/null +++ b/sdk/resourcemanager/lambdatesthyperexecute/armlambdatesthyperexecute/fake/internal.go @@ -0,0 +1,65 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "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 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/lambdatesthyperexecute/armlambdatesthyperexecute/fake/operations_server.go b/sdk/resourcemanager/lambdatesthyperexecute/armlambdatesthyperexecute/fake/operations_server.go new file mode 100644 index 000000000000..7b45eb907295 --- /dev/null +++ b/sdk/resourcemanager/lambdatesthyperexecute/armlambdatesthyperexecute/fake/operations_server.go @@ -0,0 +1,117 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/lambdatesthyperexecute/armlambdatesthyperexecute" + "net/http" +) + +// OperationsServer is a fake server for instances of the armlambdatesthyperexecute.OperationsClient type. +type OperationsServer struct { + // NewListPager is the fake for method OperationsClient.NewListPager + // HTTP status codes to indicate success: http.StatusOK + NewListPager func(options *armlambdatesthyperexecute.OperationsClientListOptions) (resp azfake.PagerResponder[armlambdatesthyperexecute.OperationsClientListResponse]) +} + +// NewOperationsServerTransport creates a new instance of OperationsServerTransport with the provided implementation. +// The returned OperationsServerTransport instance is connected to an instance of armlambdatesthyperexecute.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[armlambdatesthyperexecute.OperationsClientListResponse]](), + } +} + +// OperationsServerTransport connects instances of armlambdatesthyperexecute.OperationsClient to instances of OperationsServer. +// Don't use this type directly, use NewOperationsServerTransport instead. +type OperationsServerTransport struct { + srv *OperationsServer + newListPager *tracker[azfake.PagerResponder[armlambdatesthyperexecute.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 *armlambdatesthyperexecute.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/lambdatesthyperexecute/armlambdatesthyperexecute/fake/organizations_server.go b/sdk/resourcemanager/lambdatesthyperexecute/armlambdatesthyperexecute/fake/organizations_server.go new file mode 100644 index 000000000000..33f02a1df295 --- /dev/null +++ b/sdk/resourcemanager/lambdatesthyperexecute/armlambdatesthyperexecute/fake/organizations_server.go @@ -0,0 +1,361 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/lambdatesthyperexecute/armlambdatesthyperexecute" + "net/http" + "net/url" + "regexp" +) + +// OrganizationsServer is a fake server for instances of the armlambdatesthyperexecute.OrganizationsClient type. +type OrganizationsServer struct { + // BeginCreateOrUpdate is the fake for method OrganizationsClient.BeginCreateOrUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + BeginCreateOrUpdate func(ctx context.Context, resourceGroupName string, organizationname string, resource armlambdatesthyperexecute.OrganizationResource, options *armlambdatesthyperexecute.OrganizationsClientBeginCreateOrUpdateOptions) (resp azfake.PollerResponder[armlambdatesthyperexecute.OrganizationsClientCreateOrUpdateResponse], errResp azfake.ErrorResponder) + + // BeginDelete is the fake for method OrganizationsClient.BeginDelete + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent + BeginDelete func(ctx context.Context, resourceGroupName string, organizationname string, options *armlambdatesthyperexecute.OrganizationsClientBeginDeleteOptions) (resp azfake.PollerResponder[armlambdatesthyperexecute.OrganizationsClientDeleteResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method OrganizationsClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceGroupName string, organizationname string, options *armlambdatesthyperexecute.OrganizationsClientGetOptions) (resp azfake.Responder[armlambdatesthyperexecute.OrganizationsClientGetResponse], errResp azfake.ErrorResponder) + + // NewListByResourceGroupPager is the fake for method OrganizationsClient.NewListByResourceGroupPager + // HTTP status codes to indicate success: http.StatusOK + NewListByResourceGroupPager func(resourceGroupName string, options *armlambdatesthyperexecute.OrganizationsClientListByResourceGroupOptions) (resp azfake.PagerResponder[armlambdatesthyperexecute.OrganizationsClientListByResourceGroupResponse]) + + // NewListBySubscriptionPager is the fake for method OrganizationsClient.NewListBySubscriptionPager + // HTTP status codes to indicate success: http.StatusOK + NewListBySubscriptionPager func(options *armlambdatesthyperexecute.OrganizationsClientListBySubscriptionOptions) (resp azfake.PagerResponder[armlambdatesthyperexecute.OrganizationsClientListBySubscriptionResponse]) + + // Update is the fake for method OrganizationsClient.Update + // HTTP status codes to indicate success: http.StatusOK + Update func(ctx context.Context, resourceGroupName string, organizationname string, properties armlambdatesthyperexecute.OrganizationResourceUpdate, options *armlambdatesthyperexecute.OrganizationsClientUpdateOptions) (resp azfake.Responder[armlambdatesthyperexecute.OrganizationsClientUpdateResponse], errResp azfake.ErrorResponder) +} + +// NewOrganizationsServerTransport creates a new instance of OrganizationsServerTransport with the provided implementation. +// The returned OrganizationsServerTransport instance is connected to an instance of armlambdatesthyperexecute.OrganizationsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewOrganizationsServerTransport(srv *OrganizationsServer) *OrganizationsServerTransport { + return &OrganizationsServerTransport{ + srv: srv, + beginCreateOrUpdate: newTracker[azfake.PollerResponder[armlambdatesthyperexecute.OrganizationsClientCreateOrUpdateResponse]](), + beginDelete: newTracker[azfake.PollerResponder[armlambdatesthyperexecute.OrganizationsClientDeleteResponse]](), + newListByResourceGroupPager: newTracker[azfake.PagerResponder[armlambdatesthyperexecute.OrganizationsClientListByResourceGroupResponse]](), + newListBySubscriptionPager: newTracker[azfake.PagerResponder[armlambdatesthyperexecute.OrganizationsClientListBySubscriptionResponse]](), + } +} + +// OrganizationsServerTransport connects instances of armlambdatesthyperexecute.OrganizationsClient to instances of OrganizationsServer. +// Don't use this type directly, use NewOrganizationsServerTransport instead. +type OrganizationsServerTransport struct { + srv *OrganizationsServer + beginCreateOrUpdate *tracker[azfake.PollerResponder[armlambdatesthyperexecute.OrganizationsClientCreateOrUpdateResponse]] + beginDelete *tracker[azfake.PollerResponder[armlambdatesthyperexecute.OrganizationsClientDeleteResponse]] + newListByResourceGroupPager *tracker[azfake.PagerResponder[armlambdatesthyperexecute.OrganizationsClientListByResourceGroupResponse]] + newListBySubscriptionPager *tracker[azfake.PagerResponder[armlambdatesthyperexecute.OrganizationsClientListBySubscriptionResponse]] +} + +// Do implements the policy.Transporter interface for OrganizationsServerTransport. +func (o *OrganizationsServerTransport) 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 *OrganizationsServerTransport) 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 organizationsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = organizationsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "OrganizationsClient.BeginCreateOrUpdate": + res.resp, res.err = o.dispatchBeginCreateOrUpdate(req) + case "OrganizationsClient.BeginDelete": + res.resp, res.err = o.dispatchBeginDelete(req) + case "OrganizationsClient.Get": + res.resp, res.err = o.dispatchGet(req) + case "OrganizationsClient.NewListByResourceGroupPager": + res.resp, res.err = o.dispatchNewListByResourceGroupPager(req) + case "OrganizationsClient.NewListBySubscriptionPager": + res.resp, res.err = o.dispatchNewListBySubscriptionPager(req) + case "OrganizationsClient.Update": + res.resp, res.err = o.dispatchUpdate(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 *OrganizationsServerTransport) dispatchBeginCreateOrUpdate(req *http.Request) (*http.Response, error) { + if o.srv.BeginCreateOrUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginCreateOrUpdate not implemented")} + } + beginCreateOrUpdate := o.beginCreateOrUpdate.get(req) + if beginCreateOrUpdate == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/LambdaTest\.HyperExecute/organizations/(?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[armlambdatesthyperexecute.OrganizationResource](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + organizationnameParam, err := url.PathUnescape(matches[regex.SubexpIndex("organizationname")]) + if err != nil { + return nil, err + } + respr, errRespr := o.srv.BeginCreateOrUpdate(req.Context(), resourceGroupNameParam, organizationnameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginCreateOrUpdate = &respr + o.beginCreateOrUpdate.add(req, beginCreateOrUpdate) + } + + resp, err := server.PollerResponderNext(beginCreateOrUpdate, req) + if err != nil { + return nil, err + } + + if !contains([]int{http.StatusOK, http.StatusCreated}, resp.StatusCode) { + o.beginCreateOrUpdate.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", resp.StatusCode)} + } + if !server.PollerResponderMore(beginCreateOrUpdate) { + o.beginCreateOrUpdate.remove(req) + } + + return resp, nil +} + +func (o *OrganizationsServerTransport) dispatchBeginDelete(req *http.Request) (*http.Response, error) { + if o.srv.BeginDelete == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginDelete not implemented")} + } + beginDelete := o.beginDelete.get(req) + if beginDelete == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/LambdaTest\.HyperExecute/organizations/(?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 + } + organizationnameParam, err := url.PathUnescape(matches[regex.SubexpIndex("organizationname")]) + if err != nil { + return nil, err + } + respr, errRespr := o.srv.BeginDelete(req.Context(), resourceGroupNameParam, organizationnameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginDelete = &respr + o.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) { + o.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) { + o.beginDelete.remove(req) + } + + return resp, nil +} + +func (o *OrganizationsServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if o.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/LambdaTest\.HyperExecute/organizations/(?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 + } + organizationnameParam, err := url.PathUnescape(matches[regex.SubexpIndex("organizationname")]) + if err != nil { + return nil, err + } + respr, errRespr := o.srv.Get(req.Context(), resourceGroupNameParam, organizationnameParam, 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).OrganizationResource, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (o *OrganizationsServerTransport) dispatchNewListByResourceGroupPager(req *http.Request) (*http.Response, error) { + if o.srv.NewListByResourceGroupPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListByResourceGroupPager not implemented")} + } + newListByResourceGroupPager := o.newListByResourceGroupPager.get(req) + if newListByResourceGroupPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/LambdaTest\.HyperExecute/organizations` + 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 := o.srv.NewListByResourceGroupPager(resourceGroupNameParam, nil) + newListByResourceGroupPager = &resp + o.newListByResourceGroupPager.add(req, newListByResourceGroupPager) + server.PagerResponderInjectNextLinks(newListByResourceGroupPager, req, func(page *armlambdatesthyperexecute.OrganizationsClientListByResourceGroupResponse, 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) { + o.newListByResourceGroupPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListByResourceGroupPager) { + o.newListByResourceGroupPager.remove(req) + } + return resp, nil +} + +func (o *OrganizationsServerTransport) dispatchNewListBySubscriptionPager(req *http.Request) (*http.Response, error) { + if o.srv.NewListBySubscriptionPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListBySubscriptionPager not implemented")} + } + newListBySubscriptionPager := o.newListBySubscriptionPager.get(req) + if newListBySubscriptionPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/LambdaTest\.HyperExecute/organizations` + 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 := o.srv.NewListBySubscriptionPager(nil) + newListBySubscriptionPager = &resp + o.newListBySubscriptionPager.add(req, newListBySubscriptionPager) + server.PagerResponderInjectNextLinks(newListBySubscriptionPager, req, func(page *armlambdatesthyperexecute.OrganizationsClientListBySubscriptionResponse, 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) { + o.newListBySubscriptionPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListBySubscriptionPager) { + o.newListBySubscriptionPager.remove(req) + } + return resp, nil +} + +func (o *OrganizationsServerTransport) dispatchUpdate(req *http.Request) (*http.Response, error) { + if o.srv.Update == nil { + return nil, &nonRetriableError{errors.New("fake for method Update not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/LambdaTest\.HyperExecute/organizations/(?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[armlambdatesthyperexecute.OrganizationResourceUpdate](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + organizationnameParam, err := url.PathUnescape(matches[regex.SubexpIndex("organizationname")]) + if err != nil { + return nil, err + } + respr, errRespr := o.srv.Update(req.Context(), resourceGroupNameParam, organizationnameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).OrganizationResource, req) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to OrganizationsServerTransport +var organizationsServerTransportInterceptor 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/lambdatesthyperexecute/armlambdatesthyperexecute/fake/server_factory.go b/sdk/resourcemanager/lambdatesthyperexecute/armlambdatesthyperexecute/fake/server_factory.go new file mode 100644 index 000000000000..032866a203fc --- /dev/null +++ b/sdk/resourcemanager/lambdatesthyperexecute/armlambdatesthyperexecute/fake/server_factory.go @@ -0,0 +1,81 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "errors" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" + "sync" +) + +// ServerFactory is a fake server for instances of the armlambdatesthyperexecute.ClientFactory type. +type ServerFactory struct { + // OperationsServer contains the fakes for client OperationsClient + OperationsServer OperationsServer + + // OrganizationsServer contains the fakes for client OrganizationsClient + OrganizationsServer OrganizationsServer +} + +// NewServerFactoryTransport creates a new instance of ServerFactoryTransport with the provided implementation. +// The returned ServerFactoryTransport instance is connected to an instance of armlambdatesthyperexecute.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 armlambdatesthyperexecute.ClientFactory to instances of ServerFactory. +// Don't use this type directly, use NewServerFactoryTransport instead. +type ServerFactoryTransport struct { + srv *ServerFactory + trMu sync.Mutex + trOperationsServer *OperationsServerTransport + trOrganizationsServer *OrganizationsServerTransport +} + +// 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 "OperationsClient": + initServer(s, &s.trOperationsServer, func() *OperationsServerTransport { return NewOperationsServerTransport(&s.srv.OperationsServer) }) + resp, err = s.trOperationsServer.Do(req) + case "OrganizationsClient": + initServer(s, &s.trOrganizationsServer, func() *OrganizationsServerTransport { + return NewOrganizationsServerTransport(&s.srv.OrganizationsServer) + }) + resp, err = s.trOrganizationsServer.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/lambdatesthyperexecute/armlambdatesthyperexecute/fake/time_rfc3339.go b/sdk/resourcemanager/lambdatesthyperexecute/armlambdatesthyperexecute/fake/time_rfc3339.go new file mode 100644 index 000000000000..87ee11e83b32 --- /dev/null +++ b/sdk/resourcemanager/lambdatesthyperexecute/armlambdatesthyperexecute/fake/time_rfc3339.go @@ -0,0 +1,109 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "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 +} diff --git a/sdk/resourcemanager/lambdatesthyperexecute/armlambdatesthyperexecute/go.mod b/sdk/resourcemanager/lambdatesthyperexecute/armlambdatesthyperexecute/go.mod new file mode 100644 index 000000000000..f2b2ff6eccc7 --- /dev/null +++ b/sdk/resourcemanager/lambdatesthyperexecute/armlambdatesthyperexecute/go.mod @@ -0,0 +1,23 @@ +module github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/lambdatesthyperexecute/armlambdatesthyperexecute + +go 1.23.0 + +toolchain go1.23.8 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.17.1 + github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.7.0 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.10.0 // indirect + github.com/AzureAD/microsoft-authentication-library-for-go v1.2.2 // indirect + github.com/golang-jwt/jwt/v5 v5.2.1 // indirect + github.com/google/uuid v1.6.0 // indirect + github.com/kylelemons/godebug v1.1.0 // indirect + github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c // indirect + golang.org/x/crypto v0.36.0 // indirect + golang.org/x/net v0.37.0 // indirect + golang.org/x/sys v0.31.0 // indirect + golang.org/x/text v0.23.0 // indirect +) diff --git a/sdk/resourcemanager/lambdatesthyperexecute/armlambdatesthyperexecute/go.sum b/sdk/resourcemanager/lambdatesthyperexecute/armlambdatesthyperexecute/go.sum new file mode 100644 index 000000000000..1f92486fbbcf --- /dev/null +++ b/sdk/resourcemanager/lambdatesthyperexecute/armlambdatesthyperexecute/go.sum @@ -0,0 +1,33 @@ +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/azidentity v1.7.0 h1:tfLQ34V6F7tVSwoTf/4lH5sE0o6eCJuNDTmH09nDpbc= +github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.7.0/go.mod h1:9kIvujWAA58nmPmWB1m23fyWic1kYZMxD9CxaWn4Qpg= +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/AzureAD/microsoft-authentication-library-for-go v1.2.2 h1:XHOnouVk1mxXfQidrMEnLlPk9UMeRtyBTnEFtxkV0kU= +github.com/AzureAD/microsoft-authentication-library-for-go v1.2.2/go.mod h1:wP83P5OoQ5p6ip3ScPr0BAq0BvuPAvacpEuSzyouqAI= +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/golang-jwt/jwt/v5 v5.2.1 h1:OuVbFODueb089Lh128TAcimifWaLhJwVflnrgM17wHk= +github.com/golang-jwt/jwt/v5 v5.2.1/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk= +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc= +github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= +github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c h1:+mdjkGKdHQG3305AYmdv1U2eRNDiU2ErMBj1gwrq8eQ= +github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c/go.mod h1:7rwL4CYBLnjLxUqIJNnCWiEdr3bn6IUYi15bNlnbCCU= +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/crypto v0.36.0 h1:AnAEvhDddvBdpY+uR+MyHmuZzzNqXSe/GvuDeob5L34= +golang.org/x/crypto v0.36.0/go.mod h1:Y4J0ReaxCR1IMaabaSMugxJES1EpwhBHhv2bDHklZvc= +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/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.31.0 h1:ioabZlmFYtWhL+TRYpcnNlLwhyxaM9kWTDEmfnprqik= +golang.org/x/sys v0.31.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= +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/lambdatesthyperexecute/armlambdatesthyperexecute/models.go b/sdk/resourcemanager/lambdatesthyperexecute/armlambdatesthyperexecute/models.go new file mode 100644 index 000000000000..ea042c6ac833 --- /dev/null +++ b/sdk/resourcemanager/lambdatesthyperexecute/armlambdatesthyperexecute/models.go @@ -0,0 +1,240 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armlambdatesthyperexecute + +import "time" + +// ManagedServiceIdentity - Managed service identity (system assigned and/or user assigned identities) +type ManagedServiceIdentity struct { + // REQUIRED; The type of managed identity assigned to this resource. + Type *ManagedServiceIdentityType + + // The identities assigned to this resource by the user. + 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 +} + +// MarketplaceDetails - Marketplace details for an organization +type MarketplaceDetails struct { + // REQUIRED; Offer details for the marketplace that is selected by the user + OfferDetails *OfferDetails + + // Azure subscription id for the the marketplace offer is purchased from + SubscriptionID *string + + // READ-ONLY; Marketplace subscription status + SubscriptionStatus *MarketplaceSubscriptionStatus +} + +// OfferDetails - Offer details for the marketplace that is selected by the user +type OfferDetails struct { + // REQUIRED; Offer Id for the marketplace offer + OfferID *string + + // REQUIRED; Plan Id for the marketplace offer + PlanID *string + + // REQUIRED; Publisher Id for the marketplace offer + PublisherID *string + + // Plan Name for the marketplace offer + PlanName *string + + // Plan Display Name for the marketplace offer + TermID *string + + // Plan Display Name for the marketplace offer + TermUnit *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; Extensible 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 Azure + // Resource Manager/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 and 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 { + // REQUIRED; The Operation items on this page + Value []*Operation + + // The link to the next page of items + NextLink *string +} + +// OrganizationProperties - Properties specific to Organization +type OrganizationProperties struct { + // REQUIRED; Marketplace details of the resource. + Marketplace *MarketplaceDetails + + // REQUIRED; partner properties + PartnerProperties *PartnerProperties + + // REQUIRED; Details of the user. + User *UserDetails + + // Single sign-on properties + SingleSignOnProperties *SingleSignOnPropertiesV2 + + // READ-ONLY; Provisioning state of the resource. + ProvisioningState *ResourceProvisioningState +} + +// OrganizationResource - Concrete tracked resource types can be created by aliasing this type using a specific property type. +type OrganizationResource struct { + // REQUIRED; The geo-location where the resource lives + Location *string + + // READ-ONLY; Name of the Organization resource + Name *string + + // The managed service identities assigned to this resource. + Identity *ManagedServiceIdentity + + // The resource-specific properties for this resource. + Properties *OrganizationProperties + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; 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 +} + +// OrganizationResourceListResult - The response of a OrganizationResource list operation. +type OrganizationResourceListResult struct { + // REQUIRED; The OrganizationResource items on this page + Value []*OrganizationResource + + // The link to the next page of items + NextLink *string +} + +// OrganizationResourceUpdate - The type used for update operations of the Organization Resource. +type OrganizationResourceUpdate struct { + // The managed service identities assigned to this resource. + Identity *ManagedServiceIdentity + + // Resource tags. + Tags map[string]*string +} + +// PartnerProperties - Partner's specific Properties +type PartnerProperties struct { + // REQUIRED; The number of licenses subscribed + LicensesSubscribed *int32 +} + +// SingleSignOnPropertiesV2 - Properties specific to Single Sign On Resource +type SingleSignOnPropertiesV2 struct { + // REQUIRED; Type of Single Sign-On mechanism being used + Type *SingleSignOnType + + // List of AAD domains fetched from Microsoft Graph for user. + AADDomains []*string + + // AAD enterprise application Id used to setup SSO + EnterpriseAppID *string + + // State of the Single Sign On for the resource + State *SingleSignOnStates + + // URL for SSO to be used by the partner to redirect the user to their system + URL *string +} + +// 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 +} + +// 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 +} + +// UserDetails - User details for an organization +type UserDetails struct { + // Email address of the user + EmailAddress *string + + // First name of the user + FirstName *string + + // Last name of the user + LastName *string + + // User's phone number + PhoneNumber *string + + // User's principal name + Upn *string +} diff --git a/sdk/resourcemanager/lambdatesthyperexecute/armlambdatesthyperexecute/models_serde.go b/sdk/resourcemanager/lambdatesthyperexecute/armlambdatesthyperexecute/models_serde.go new file mode 100644 index 000000000000..5fbd3b46561c --- /dev/null +++ b/sdk/resourcemanager/lambdatesthyperexecute/armlambdatesthyperexecute/models_serde.go @@ -0,0 +1,617 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armlambdatesthyperexecute + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "reflect" +) + +// 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 MarketplaceDetails. +func (m MarketplaceDetails) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "offerDetails", m.OfferDetails) + populate(objectMap, "subscriptionId", m.SubscriptionID) + populate(objectMap, "subscriptionStatus", m.SubscriptionStatus) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type MarketplaceDetails. +func (m *MarketplaceDetails) 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 "offerDetails": + err = unpopulate(val, "OfferDetails", &m.OfferDetails) + delete(rawMsg, key) + case "subscriptionId": + err = unpopulate(val, "SubscriptionID", &m.SubscriptionID) + delete(rawMsg, key) + case "subscriptionStatus": + err = unpopulate(val, "SubscriptionStatus", &m.SubscriptionStatus) + 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 OfferDetails. +func (o OfferDetails) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "offerId", o.OfferID) + populate(objectMap, "planId", o.PlanID) + populate(objectMap, "planName", o.PlanName) + populate(objectMap, "publisherId", o.PublisherID) + populate(objectMap, "termId", o.TermID) + populate(objectMap, "termUnit", o.TermUnit) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OfferDetails. +func (o *OfferDetails) 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 "offerId": + err = unpopulate(val, "OfferID", &o.OfferID) + delete(rawMsg, key) + case "planId": + err = unpopulate(val, "PlanID", &o.PlanID) + delete(rawMsg, key) + case "planName": + err = unpopulate(val, "PlanName", &o.PlanName) + delete(rawMsg, key) + case "publisherId": + err = unpopulate(val, "PublisherID", &o.PublisherID) + delete(rawMsg, key) + case "termId": + err = unpopulate(val, "TermID", &o.TermID) + delete(rawMsg, key) + case "termUnit": + err = unpopulate(val, "TermUnit", &o.TermUnit) + 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 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 OrganizationProperties. +func (o OrganizationProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "marketplace", o.Marketplace) + populate(objectMap, "partnerProperties", o.PartnerProperties) + populate(objectMap, "provisioningState", o.ProvisioningState) + populate(objectMap, "singleSignOnProperties", o.SingleSignOnProperties) + populate(objectMap, "user", o.User) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OrganizationProperties. +func (o *OrganizationProperties) 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 "marketplace": + err = unpopulate(val, "Marketplace", &o.Marketplace) + delete(rawMsg, key) + case "partnerProperties": + err = unpopulate(val, "PartnerProperties", &o.PartnerProperties) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &o.ProvisioningState) + delete(rawMsg, key) + case "singleSignOnProperties": + err = unpopulate(val, "SingleSignOnProperties", &o.SingleSignOnProperties) + delete(rawMsg, key) + case "user": + err = unpopulate(val, "User", &o.User) + 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 OrganizationResource. +func (o OrganizationResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", o.ID) + populate(objectMap, "identity", o.Identity) + populate(objectMap, "location", o.Location) + populate(objectMap, "name", o.Name) + populate(objectMap, "properties", o.Properties) + populate(objectMap, "systemData", o.SystemData) + populate(objectMap, "tags", o.Tags) + populate(objectMap, "type", o.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OrganizationResource. +func (o *OrganizationResource) 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 "id": + err = unpopulate(val, "ID", &o.ID) + delete(rawMsg, key) + case "identity": + err = unpopulate(val, "Identity", &o.Identity) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &o.Location) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &o.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &o.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &o.SystemData) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &o.Tags) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &o.Type) + 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 OrganizationResourceListResult. +func (o OrganizationResourceListResult) 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 OrganizationResourceListResult. +func (o *OrganizationResourceListResult) 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 OrganizationResourceUpdate. +func (o OrganizationResourceUpdate) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "identity", o.Identity) + populate(objectMap, "tags", o.Tags) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OrganizationResourceUpdate. +func (o *OrganizationResourceUpdate) 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 "identity": + err = unpopulate(val, "Identity", &o.Identity) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &o.Tags) + 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 PartnerProperties. +func (p PartnerProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "licensesSubscribed", p.LicensesSubscribed) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PartnerProperties. +func (p *PartnerProperties) 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 "licensesSubscribed": + err = unpopulate(val, "LicensesSubscribed", &p.LicensesSubscribed) + 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 SingleSignOnPropertiesV2. +func (s SingleSignOnPropertiesV2) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "aadDomains", s.AADDomains) + populate(objectMap, "enterpriseAppId", s.EnterpriseAppID) + populate(objectMap, "state", s.State) + populate(objectMap, "type", s.Type) + populate(objectMap, "url", s.URL) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SingleSignOnPropertiesV2. +func (s *SingleSignOnPropertiesV2) 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 "aadDomains": + err = unpopulate(val, "AADDomains", &s.AADDomains) + delete(rawMsg, key) + case "enterpriseAppId": + err = unpopulate(val, "EnterpriseAppID", &s.EnterpriseAppID) + delete(rawMsg, key) + case "state": + err = unpopulate(val, "State", &s.State) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &s.Type) + delete(rawMsg, key) + case "url": + err = unpopulate(val, "URL", &s.URL) + 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 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 +} + +// MarshalJSON implements the json.Marshaller interface for type UserDetails. +func (u UserDetails) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "emailAddress", u.EmailAddress) + populate(objectMap, "firstName", u.FirstName) + populate(objectMap, "lastName", u.LastName) + populate(objectMap, "phoneNumber", u.PhoneNumber) + populate(objectMap, "upn", u.Upn) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type UserDetails. +func (u *UserDetails) 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 "emailAddress": + err = unpopulate(val, "EmailAddress", &u.EmailAddress) + delete(rawMsg, key) + case "firstName": + err = unpopulate(val, "FirstName", &u.FirstName) + delete(rawMsg, key) + case "lastName": + err = unpopulate(val, "LastName", &u.LastName) + delete(rawMsg, key) + case "phoneNumber": + err = unpopulate(val, "PhoneNumber", &u.PhoneNumber) + delete(rawMsg, key) + case "upn": + err = unpopulate(val, "Upn", &u.Upn) + 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/lambdatesthyperexecute/armlambdatesthyperexecute/operations_client.go b/sdk/resourcemanager/lambdatesthyperexecute/armlambdatesthyperexecute/operations_client.go new file mode 100644 index 000000000000..b75ea0efdd99 --- /dev/null +++ b/sdk/resourcemanager/lambdatesthyperexecute/armlambdatesthyperexecute/operations_client.go @@ -0,0 +1,84 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armlambdatesthyperexecute + +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 2024-02-01 +// - options - OperationsClientListOptions contains the optional parameters for the OperationsClient.NewListPager method. +func (client *OperationsClient) NewListPager(options *OperationsClientListOptions) *runtime.Pager[OperationsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[OperationsClientListResponse]{ + 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/LambdaTest.HyperExecute/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", "2024-02-01") + 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/lambdatesthyperexecute/armlambdatesthyperexecute/operations_client_example_test.go b/sdk/resourcemanager/lambdatesthyperexecute/armlambdatesthyperexecute/operations_client_example_test.go new file mode 100644 index 000000000000..b86750f1bdd3 --- /dev/null +++ b/sdk/resourcemanager/lambdatesthyperexecute/armlambdatesthyperexecute/operations_client_example_test.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) Go Code Generator. DO NOT EDIT. + +package armlambdatesthyperexecute_test + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azidentity" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/lambdatesthyperexecute/armlambdatesthyperexecute" + "log" +) + +// Generated from example definition: 2024-02-01/Operations_List_MaximumSet_Gen.json +func ExampleOperationsClient_NewListPager_operationsListMaximumSetGenGeneratedByMaximumSetRuleGeneratedByMaximumSetRuleGeneratedByMaximumSetRule() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armlambdatesthyperexecute.NewClientFactory("", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + pager := clientFactory.NewOperationsClient().NewListPager(nil) + for pager.More() { + page, err := pager.NextPage(ctx) + if err != nil { + log.Fatalf("failed to advance page: %v", err) + } + for _, v := range page.Value { + // You could use page here. We use blank identifier for just demo purposes. + _ = v + } + // If the HTTP response code is 200 as defined in example definition, your page structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // page = armlambdatesthyperexecute.OperationsClientListResponse{ + // OperationListResult: armlambdatesthyperexecute.OperationListResult{ + // Value: []*armlambdatesthyperexecute.Operation{ + // { + // Name: to.Ptr("pqjblljnopojofemsawnpfetwqdakn"), + // IsDataAction: to.Ptr(true), + // Display: &armlambdatesthyperexecute.OperationDisplay{ + // Provider: to.Ptr("pyqznxwjmapxcfr"), + // Resource: to.Ptr("xlrbrkdnznqfgdzwbubj"), + // Operation: to.Ptr("fujfkctgncoiygfunwfczhvf"), + // Description: to.Ptr("fyqutlzqriswplfce"), + // }, + // Origin: to.Ptr(armlambdatesthyperexecute.OriginUser), + // ActionType: to.Ptr(armlambdatesthyperexecute.ActionTypeInternal), + // }, + // }, + // NextLink: to.Ptr("https://microsoft.com/a"), + // }, + // } + } +} + +// Generated from example definition: 2024-02-01/Operations_List_MinimumSet_Gen.json +func ExampleOperationsClient_NewListPager_operationsListMaximumSetGenGeneratedByMaximumSetRuleGeneratedByMaximumSetRuleGeneratedByMinimumSetRule() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armlambdatesthyperexecute.NewClientFactory("", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + pager := clientFactory.NewOperationsClient().NewListPager(nil) + for pager.More() { + page, err := pager.NextPage(ctx) + if err != nil { + log.Fatalf("failed to advance page: %v", err) + } + for _, v := range page.Value { + // You could use page here. We use blank identifier for just demo purposes. + _ = v + } + // If the HTTP response code is 200 as defined in example definition, your page structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // page = armlambdatesthyperexecute.OperationsClientListResponse{ + // OperationListResult: armlambdatesthyperexecute.OperationListResult{ + // }, + // } + } +} diff --git a/sdk/resourcemanager/lambdatesthyperexecute/armlambdatesthyperexecute/options.go b/sdk/resourcemanager/lambdatesthyperexecute/armlambdatesthyperexecute/options.go new file mode 100644 index 000000000000..da345c05b5ff --- /dev/null +++ b/sdk/resourcemanager/lambdatesthyperexecute/armlambdatesthyperexecute/options.go @@ -0,0 +1,45 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armlambdatesthyperexecute + +// OperationsClientListOptions contains the optional parameters for the OperationsClient.NewListPager method. +type OperationsClientListOptions struct { + // placeholder for future optional parameters +} + +// OrganizationsClientBeginCreateOrUpdateOptions contains the optional parameters for the OrganizationsClient.BeginCreateOrUpdate +// method. +type OrganizationsClientBeginCreateOrUpdateOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// OrganizationsClientBeginDeleteOptions contains the optional parameters for the OrganizationsClient.BeginDelete method. +type OrganizationsClientBeginDeleteOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// OrganizationsClientGetOptions contains the optional parameters for the OrganizationsClient.Get method. +type OrganizationsClientGetOptions struct { + // placeholder for future optional parameters +} + +// OrganizationsClientListByResourceGroupOptions contains the optional parameters for the OrganizationsClient.NewListByResourceGroupPager +// method. +type OrganizationsClientListByResourceGroupOptions struct { + // placeholder for future optional parameters +} + +// OrganizationsClientListBySubscriptionOptions contains the optional parameters for the OrganizationsClient.NewListBySubscriptionPager +// method. +type OrganizationsClientListBySubscriptionOptions struct { + // placeholder for future optional parameters +} + +// OrganizationsClientUpdateOptions contains the optional parameters for the OrganizationsClient.Update method. +type OrganizationsClientUpdateOptions struct { + // placeholder for future optional parameters +} diff --git a/sdk/resourcemanager/lambdatesthyperexecute/armlambdatesthyperexecute/organizations_client.go b/sdk/resourcemanager/lambdatesthyperexecute/armlambdatesthyperexecute/organizations_client.go new file mode 100644 index 000000000000..ffccc2f9b2a4 --- /dev/null +++ b/sdk/resourcemanager/lambdatesthyperexecute/armlambdatesthyperexecute/organizations_client.go @@ -0,0 +1,445 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armlambdatesthyperexecute + +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" +) + +// OrganizationsClient contains the methods for the Organizations group. +// Don't use this type directly, use NewOrganizationsClient() instead. +type OrganizationsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewOrganizationsClient creates a new instance of OrganizationsClient 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 NewOrganizationsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*OrganizationsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &OrganizationsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Create a OrganizationResource +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-02-01 +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - organizationname - Name of the Organization resource +// - resource - Resource create parameters. +// - options - OrganizationsClientBeginCreateOrUpdateOptions contains the optional parameters for the OrganizationsClient.BeginCreateOrUpdate +// method. +func (client *OrganizationsClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, organizationname string, resource OrganizationResource, options *OrganizationsClientBeginCreateOrUpdateOptions) (*runtime.Poller[OrganizationsClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, organizationname, resource, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[OrganizationsClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[OrganizationsClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Create a OrganizationResource +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-02-01 +func (client *OrganizationsClient) createOrUpdate(ctx context.Context, resourceGroupName string, organizationname string, resource OrganizationResource, options *OrganizationsClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "OrganizationsClient.BeginCreateOrUpdate" + 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, organizationname, 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 +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *OrganizationsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, organizationname string, resource OrganizationResource, _ *OrganizationsClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/LambdaTest.HyperExecute/organizations/{organizationname}" + 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 organizationname == "" { + return nil, errors.New("parameter organizationname cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{organizationname}", url.PathEscape(organizationname)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2024-02-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, resource); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Delete a OrganizationResource +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-02-01 +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - organizationname - Name of the Organization resource +// - options - OrganizationsClientBeginDeleteOptions contains the optional parameters for the OrganizationsClient.BeginDelete +// method. +func (client *OrganizationsClient) BeginDelete(ctx context.Context, resourceGroupName string, organizationname string, options *OrganizationsClientBeginDeleteOptions) (*runtime.Poller[OrganizationsClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, organizationname, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[OrganizationsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[OrganizationsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Delete a OrganizationResource +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-02-01 +func (client *OrganizationsClient) deleteOperation(ctx context.Context, resourceGroupName string, organizationname string, options *OrganizationsClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "OrganizationsClient.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, organizationname, 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 *OrganizationsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, organizationname string, _ *OrganizationsClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/LambdaTest.HyperExecute/organizations/{organizationname}" + 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 organizationname == "" { + return nil, errors.New("parameter organizationname cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{organizationname}", url.PathEscape(organizationname)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2024-02-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Get a OrganizationResource +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-02-01 +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - organizationname - Name of the Organization resource +// - options - OrganizationsClientGetOptions contains the optional parameters for the OrganizationsClient.Get method. +func (client *OrganizationsClient) Get(ctx context.Context, resourceGroupName string, organizationname string, options *OrganizationsClientGetOptions) (OrganizationsClientGetResponse, error) { + var err error + const operationName = "OrganizationsClient.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, organizationname, options) + if err != nil { + return OrganizationsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return OrganizationsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return OrganizationsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *OrganizationsClient) getCreateRequest(ctx context.Context, resourceGroupName string, organizationname string, _ *OrganizationsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/LambdaTest.HyperExecute/organizations/{organizationname}" + 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 organizationname == "" { + return nil, errors.New("parameter organizationname cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{organizationname}", url.PathEscape(organizationname)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2024-02-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *OrganizationsClient) getHandleResponse(resp *http.Response) (OrganizationsClientGetResponse, error) { + result := OrganizationsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.OrganizationResource); err != nil { + return OrganizationsClientGetResponse{}, err + } + return result, nil +} + +// NewListByResourceGroupPager - List OrganizationResource resources by resource group +// +// Generated from API version 2024-02-01 +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - options - OrganizationsClientListByResourceGroupOptions contains the optional parameters for the OrganizationsClient.NewListByResourceGroupPager +// method. +func (client *OrganizationsClient) NewListByResourceGroupPager(resourceGroupName string, options *OrganizationsClientListByResourceGroupOptions) *runtime.Pager[OrganizationsClientListByResourceGroupResponse] { + return runtime.NewPager(runtime.PagingHandler[OrganizationsClientListByResourceGroupResponse]{ + More: func(page OrganizationsClientListByResourceGroupResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *OrganizationsClientListByResourceGroupResponse) (OrganizationsClientListByResourceGroupResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "OrganizationsClient.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 OrganizationsClientListByResourceGroupResponse{}, err + } + return client.listByResourceGroupHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByResourceGroupCreateRequest creates the ListByResourceGroup request. +func (client *OrganizationsClient) listByResourceGroupCreateRequest(ctx context.Context, resourceGroupName string, _ *OrganizationsClientListByResourceGroupOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/LambdaTest.HyperExecute/organizations" + 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", "2024-02-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByResourceGroupHandleResponse handles the ListByResourceGroup response. +func (client *OrganizationsClient) listByResourceGroupHandleResponse(resp *http.Response) (OrganizationsClientListByResourceGroupResponse, error) { + result := OrganizationsClientListByResourceGroupResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.OrganizationResourceListResult); err != nil { + return OrganizationsClientListByResourceGroupResponse{}, err + } + return result, nil +} + +// NewListBySubscriptionPager - List OrganizationResource resources by subscription ID +// +// Generated from API version 2024-02-01 +// - options - OrganizationsClientListBySubscriptionOptions contains the optional parameters for the OrganizationsClient.NewListBySubscriptionPager +// method. +func (client *OrganizationsClient) NewListBySubscriptionPager(options *OrganizationsClientListBySubscriptionOptions) *runtime.Pager[OrganizationsClientListBySubscriptionResponse] { + return runtime.NewPager(runtime.PagingHandler[OrganizationsClientListBySubscriptionResponse]{ + More: func(page OrganizationsClientListBySubscriptionResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *OrganizationsClientListBySubscriptionResponse) (OrganizationsClientListBySubscriptionResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "OrganizationsClient.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 OrganizationsClientListBySubscriptionResponse{}, err + } + return client.listBySubscriptionHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listBySubscriptionCreateRequest creates the ListBySubscription request. +func (client *OrganizationsClient) listBySubscriptionCreateRequest(ctx context.Context, _ *OrganizationsClientListBySubscriptionOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/LambdaTest.HyperExecute/organizations" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2024-02-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listBySubscriptionHandleResponse handles the ListBySubscription response. +func (client *OrganizationsClient) listBySubscriptionHandleResponse(resp *http.Response) (OrganizationsClientListBySubscriptionResponse, error) { + result := OrganizationsClientListBySubscriptionResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.OrganizationResourceListResult); err != nil { + return OrganizationsClientListBySubscriptionResponse{}, err + } + return result, nil +} + +// Update - Update a OrganizationResource +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-02-01 +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - organizationname - Name of the Organization resource +// - properties - The resource properties to be updated. +// - options - OrganizationsClientUpdateOptions contains the optional parameters for the OrganizationsClient.Update method. +func (client *OrganizationsClient) Update(ctx context.Context, resourceGroupName string, organizationname string, properties OrganizationResourceUpdate, options *OrganizationsClientUpdateOptions) (OrganizationsClientUpdateResponse, error) { + var err error + const operationName = "OrganizationsClient.Update" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateCreateRequest(ctx, resourceGroupName, organizationname, properties, options) + if err != nil { + return OrganizationsClientUpdateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return OrganizationsClientUpdateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return OrganizationsClientUpdateResponse{}, err + } + resp, err := client.updateHandleResponse(httpResp) + return resp, err +} + +// updateCreateRequest creates the Update request. +func (client *OrganizationsClient) updateCreateRequest(ctx context.Context, resourceGroupName string, organizationname string, properties OrganizationResourceUpdate, _ *OrganizationsClientUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/LambdaTest.HyperExecute/organizations/{organizationname}" + 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 organizationname == "" { + return nil, errors.New("parameter organizationname cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{organizationname}", url.PathEscape(organizationname)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2024-02-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, properties); err != nil { + return nil, err + } + return req, nil +} + +// updateHandleResponse handles the Update response. +func (client *OrganizationsClient) updateHandleResponse(resp *http.Response) (OrganizationsClientUpdateResponse, error) { + result := OrganizationsClientUpdateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.OrganizationResource); err != nil { + return OrganizationsClientUpdateResponse{}, err + } + return result, nil +} diff --git a/sdk/resourcemanager/lambdatesthyperexecute/armlambdatesthyperexecute/organizations_client_example_test.go b/sdk/resourcemanager/lambdatesthyperexecute/armlambdatesthyperexecute/organizations_client_example_test.go new file mode 100644 index 000000000000..a59e1ed37c45 --- /dev/null +++ b/sdk/resourcemanager/lambdatesthyperexecute/armlambdatesthyperexecute/organizations_client_example_test.go @@ -0,0 +1,569 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armlambdatesthyperexecute_test + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/Azure/azure-sdk-for-go/sdk/azidentity" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/lambdatesthyperexecute/armlambdatesthyperexecute" + "log" +) + +// Generated from example definition: 2024-02-01/Organizations_CreateOrUpdate_MaximumSet_Gen.json +func ExampleOrganizationsClient_BeginCreateOrUpdate() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armlambdatesthyperexecute.NewClientFactory("171E7A75-341B-4472-BC4C-7603C5AB9F32", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + poller, err := clientFactory.NewOrganizationsClient().BeginCreateOrUpdate(ctx, "rgopenapi", "testorg", armlambdatesthyperexecute.OrganizationResource{ + Properties: &armlambdatesthyperexecute.OrganizationProperties{ + Marketplace: &armlambdatesthyperexecute.MarketplaceDetails{ + SubscriptionID: to.Ptr("zetdxwryjgcsnosezfpovkpvgvim"), + SubscriptionStatus: to.Ptr(armlambdatesthyperexecute.MarketplaceSubscriptionStatusPendingFulfillmentStart), + OfferDetails: &armlambdatesthyperexecute.OfferDetails{ + PublisherID: to.Ptr("ufwwpzit"), + OfferID: to.Ptr("fmljkvoivqmfdiwsu"), + PlanID: to.Ptr("ssjlabxexw"), + PlanName: to.Ptr("mrguqu"), + TermUnit: to.Ptr("acvhavsffebfivyaxhxxsaqzt"), + TermID: to.Ptr("hxkszxfscsyefeuunyyfskhibr"), + }, + }, + User: &armlambdatesthyperexecute.UserDetails{ + FirstName: to.Ptr("ssnzyujsrszbptndzeoqzrmbufrhgp"), + LastName: to.Ptr("nsfylyvdyrtfzfeehmji"), + EmailAddress: to.Ptr("joe@example.com"), + Upn: to.Ptr("tfqolz"), + PhoneNumber: to.Ptr("jkevskjaaylbwjzofkzmxdysejsoir"), + }, + PartnerProperties: &armlambdatesthyperexecute.PartnerProperties{ + LicensesSubscribed: to.Ptr[int32](7), + }, + SingleSignOnProperties: &armlambdatesthyperexecute.SingleSignOnPropertiesV2{ + Type: to.Ptr(armlambdatesthyperexecute.SingleSignOnTypeSaml), + State: to.Ptr(armlambdatesthyperexecute.SingleSignOnStatesInitial), + EnterpriseAppID: to.Ptr("sonpowym"), + URL: to.Ptr("qlshnxrfcdpjcpkxxisrn"), + AADDomains: []*string{ + to.Ptr("hrgguokssgyrfdzliyjmovtelfu"), + }, + }, + }, + Identity: &armlambdatesthyperexecute.ManagedServiceIdentity{ + Type: to.Ptr(armlambdatesthyperexecute.ManagedServiceIdentityTypeNone), + UserAssignedIdentities: map[string]*armlambdatesthyperexecute.UserAssignedIdentity{}, + }, + Tags: map[string]*string{}, + Location: to.Ptr("cvymsrlt"), + }, nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + res, err := poller.PollUntilDone(ctx, nil) + if err != nil { + log.Fatalf("failed to pull the result: %v", err) + } + // You could use response here. We use blank identifier for just demo purposes. + _ = res + // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // res = armlambdatesthyperexecute.OrganizationsClientCreateOrUpdateResponse{ + // OrganizationResource: &armlambdatesthyperexecute.OrganizationResource{ + // Properties: &armlambdatesthyperexecute.OrganizationProperties{ + // Marketplace: &armlambdatesthyperexecute.MarketplaceDetails{ + // SubscriptionID: to.Ptr("zetdxwryjgcsnosezfpovkpvgvim"), + // SubscriptionStatus: to.Ptr(armlambdatesthyperexecute.MarketplaceSubscriptionStatusPendingFulfillmentStart), + // OfferDetails: &armlambdatesthyperexecute.OfferDetails{ + // PublisherID: to.Ptr("ufwwpzit"), + // OfferID: to.Ptr("fmljkvoivqmfdiwsu"), + // PlanID: to.Ptr("ssjlabxexw"), + // PlanName: to.Ptr("mrguqu"), + // TermUnit: to.Ptr("acvhavsffebfivyaxhxxsaqzt"), + // TermID: to.Ptr("hxkszxfscsyefeuunyyfskhibr"), + // }, + // }, + // User: &armlambdatesthyperexecute.UserDetails{ + // FirstName: to.Ptr("ssnzyujsrszbptndzeoqzrmbufrhgp"), + // LastName: to.Ptr("nsfylyvdyrtfzfeehmji"), + // EmailAddress: to.Ptr("joe@example.com"), + // Upn: to.Ptr("tfqolz"), + // PhoneNumber: to.Ptr("jkevskjaaylbwjzofkzmxdysejsoir"), + // }, + // PartnerProperties: &armlambdatesthyperexecute.PartnerProperties{ + // LicensesSubscribed: to.Ptr[int32](7), + // }, + // ProvisioningState: to.Ptr(armlambdatesthyperexecute.ResourceProvisioningStateSucceeded), + // SingleSignOnProperties: &armlambdatesthyperexecute.SingleSignOnPropertiesV2{ + // Type: to.Ptr(armlambdatesthyperexecute.SingleSignOnTypeSaml), + // State: to.Ptr(armlambdatesthyperexecute.SingleSignOnStatesInitial), + // EnterpriseAppID: to.Ptr("sonpowym"), + // URL: to.Ptr("qlshnxrfcdpjcpkxxisrn"), + // AADDomains: []*string{ + // to.Ptr("hrgguokssgyrfdzliyjmovtelfu"), + // }, + // }, + // }, + // Identity: &armlambdatesthyperexecute.ManagedServiceIdentity{ + // Type: to.Ptr(armlambdatesthyperexecute.ManagedServiceIdentityTypeNone), + // UserAssignedIdentities: map[string]*armlambdatesthyperexecute.UserAssignedIdentity{ + // }, + // PrincipalID: to.Ptr("123e4567-e89b-12d3-a456-426614174000"), + // TenantID: to.Ptr("123e4567-e89b-12d3-a456-426614174000"), + // }, + // Tags: map[string]*string{ + // }, + // Location: to.Ptr("cvymsrlt"), + // ID: to.Ptr("/subscriptions/12345678-1234-1234-1234-123456789012/resourceGroups/myResourceGroup/providers/Lambdatest.Hyoerexecute/organizations/testorg"), + // Name: to.Ptr("rayjyvlsggeccbyzkstzr"), + // Type: to.Ptr("ju"), + // SystemData: &armlambdatesthyperexecute.SystemData{ + // CreatedBy: to.Ptr("muialblsfdrvcxxwenlybddkar"), + // CreatedByType: to.Ptr(armlambdatesthyperexecute.CreatedByTypeUser), + // CreatedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2024-09-05T12:10:42.989Z"); return t}()), + // LastModifiedBy: to.Ptr("qnkeaiefwrcpgihdwkesrjw"), + // LastModifiedByType: to.Ptr(armlambdatesthyperexecute.CreatedByTypeUser), + // LastModifiedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2024-09-05T12:10:42.989Z"); return t}()), + // }, + // }, + // } +} + +// Generated from example definition: 2024-02-01/Organizations_Delete_MaximumSet_Gen.json +func ExampleOrganizationsClient_BeginDelete() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armlambdatesthyperexecute.NewClientFactory("171E7A75-341B-4472-BC4C-7603C5AB9F32", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + poller, err := clientFactory.NewOrganizationsClient().BeginDelete(ctx, "rgopenapi", "testorg", nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + _, err = poller.PollUntilDone(ctx, nil) + if err != nil { + log.Fatalf("failed to pull the result: %v", err) + } +} + +// Generated from example definition: 2024-02-01/Organizations_Get_MaximumSet_Gen.json +func ExampleOrganizationsClient_Get() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armlambdatesthyperexecute.NewClientFactory("171E7A75-341B-4472-BC4C-7603C5AB9F32", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + res, err := clientFactory.NewOrganizationsClient().Get(ctx, "rgopenapi", "testorg", nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + // You could use response here. We use blank identifier for just demo purposes. + _ = res + // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // res = armlambdatesthyperexecute.OrganizationsClientGetResponse{ + // OrganizationResource: &armlambdatesthyperexecute.OrganizationResource{ + // Properties: &armlambdatesthyperexecute.OrganizationProperties{ + // Marketplace: &armlambdatesthyperexecute.MarketplaceDetails{ + // SubscriptionID: to.Ptr("zetdxwryjgcsnosezfpovkpvgvim"), + // SubscriptionStatus: to.Ptr(armlambdatesthyperexecute.MarketplaceSubscriptionStatusPendingFulfillmentStart), + // OfferDetails: &armlambdatesthyperexecute.OfferDetails{ + // PublisherID: to.Ptr("ufwwpzit"), + // OfferID: to.Ptr("fmljkvoivqmfdiwsu"), + // PlanID: to.Ptr("ssjlabxexw"), + // PlanName: to.Ptr("mrguqu"), + // TermUnit: to.Ptr("acvhavsffebfivyaxhxxsaqzt"), + // TermID: to.Ptr("hxkszxfscsyefeuunyyfskhibr"), + // }, + // }, + // User: &armlambdatesthyperexecute.UserDetails{ + // FirstName: to.Ptr("ssnzyujsrszbptndzeoqzrmbufrhgp"), + // LastName: to.Ptr("nsfylyvdyrtfzfeehmji"), + // EmailAddress: to.Ptr("joe@example.com"), + // Upn: to.Ptr("tfqolz"), + // PhoneNumber: to.Ptr("jkevskjaaylbwjzofkzmxdysejsoir"), + // }, + // PartnerProperties: &armlambdatesthyperexecute.PartnerProperties{ + // LicensesSubscribed: to.Ptr[int32](7), + // }, + // ProvisioningState: to.Ptr(armlambdatesthyperexecute.ResourceProvisioningStateSucceeded), + // SingleSignOnProperties: &armlambdatesthyperexecute.SingleSignOnPropertiesV2{ + // Type: to.Ptr(armlambdatesthyperexecute.SingleSignOnTypeSaml), + // State: to.Ptr(armlambdatesthyperexecute.SingleSignOnStatesInitial), + // EnterpriseAppID: to.Ptr("sonpowym"), + // URL: to.Ptr("qlshnxrfcdpjcpkxxisrn"), + // AADDomains: []*string{ + // to.Ptr("hrgguokssgyrfdzliyjmovtelfu"), + // }, + // }, + // }, + // Identity: &armlambdatesthyperexecute.ManagedServiceIdentity{ + // Type: to.Ptr(armlambdatesthyperexecute.ManagedServiceIdentityTypeNone), + // UserAssignedIdentities: map[string]*armlambdatesthyperexecute.UserAssignedIdentity{ + // }, + // PrincipalID: to.Ptr("123e4567-e89b-12d3-a456-426614174000"), + // TenantID: to.Ptr("123e4567-e89b-12d3-a456-426614174000"), + // }, + // Tags: map[string]*string{ + // }, + // Location: to.Ptr("cvymsrlt"), + // ID: to.Ptr("/subscriptions/12345678-1234-1234-1234-123456789012/resourceGroups/myResourceGroup/providers/Lambdatest.Hyoerexecute/organizations/testorg"), + // Name: to.Ptr("rayjyvlsggeccbyzkstzr"), + // Type: to.Ptr("ju"), + // SystemData: &armlambdatesthyperexecute.SystemData{ + // CreatedBy: to.Ptr("muialblsfdrvcxxwenlybddkar"), + // CreatedByType: to.Ptr(armlambdatesthyperexecute.CreatedByTypeUser), + // CreatedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2024-09-05T12:10:42.989Z"); return t}()), + // LastModifiedBy: to.Ptr("qnkeaiefwrcpgihdwkesrjw"), + // LastModifiedByType: to.Ptr(armlambdatesthyperexecute.CreatedByTypeUser), + // LastModifiedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2024-09-05T12:10:42.989Z"); return t}()), + // }, + // }, + // } +} + +// Generated from example definition: 2024-02-01/Organizations_ListByResourceGroup_MaximumSet_Gen.json +func ExampleOrganizationsClient_NewListByResourceGroupPager_organizationsListByResourceGroupMaximumSetGenGeneratedByMaximumSetRuleGeneratedByMaximumSetRuleGeneratedByMaximumSetRule() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armlambdatesthyperexecute.NewClientFactory("171E7A75-341B-4472-BC4C-7603C5AB9F32", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + pager := clientFactory.NewOrganizationsClient().NewListByResourceGroupPager("rgopenapi", nil) + for pager.More() { + page, err := pager.NextPage(ctx) + if err != nil { + log.Fatalf("failed to advance page: %v", err) + } + for _, v := range page.Value { + // You could use page here. We use blank identifier for just demo purposes. + _ = v + } + // If the HTTP response code is 200 as defined in example definition, your page structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // page = armlambdatesthyperexecute.OrganizationsClientListByResourceGroupResponse{ + // OrganizationResourceListResult: armlambdatesthyperexecute.OrganizationResourceListResult{ + // Value: []*armlambdatesthyperexecute.OrganizationResource{ + // { + // Properties: &armlambdatesthyperexecute.OrganizationProperties{ + // Marketplace: &armlambdatesthyperexecute.MarketplaceDetails{ + // SubscriptionID: to.Ptr("zetdxwryjgcsnosezfpovkpvgvim"), + // SubscriptionStatus: to.Ptr(armlambdatesthyperexecute.MarketplaceSubscriptionStatusPendingFulfillmentStart), + // OfferDetails: &armlambdatesthyperexecute.OfferDetails{ + // PublisherID: to.Ptr("ufwwpzit"), + // OfferID: to.Ptr("fmljkvoivqmfdiwsu"), + // PlanID: to.Ptr("ssjlabxexw"), + // PlanName: to.Ptr("mrguqu"), + // TermUnit: to.Ptr("acvhavsffebfivyaxhxxsaqzt"), + // TermID: to.Ptr("hxkszxfscsyefeuunyyfskhibr"), + // }, + // }, + // User: &armlambdatesthyperexecute.UserDetails{ + // FirstName: to.Ptr("ssnzyujsrszbptndzeoqzrmbufrhgp"), + // LastName: to.Ptr("nsfylyvdyrtfzfeehmji"), + // EmailAddress: to.Ptr("joe@example.com"), + // Upn: to.Ptr("tfqolz"), + // PhoneNumber: to.Ptr("jkevskjaaylbwjzofkzmxdysejsoir"), + // }, + // ProvisioningState: to.Ptr(armlambdatesthyperexecute.ResourceProvisioningStateSucceeded), + // PartnerProperties: &armlambdatesthyperexecute.PartnerProperties{ + // LicensesSubscribed: to.Ptr[int32](14), + // }, + // SingleSignOnProperties: &armlambdatesthyperexecute.SingleSignOnPropertiesV2{ + // Type: to.Ptr(armlambdatesthyperexecute.SingleSignOnTypeSaml), + // State: to.Ptr(armlambdatesthyperexecute.SingleSignOnStatesInitial), + // EnterpriseAppID: to.Ptr("sonpowym"), + // URL: to.Ptr("qlshnxrfcdpjcpkxxisrn"), + // AADDomains: []*string{ + // to.Ptr("hrgguokssgyrfdzliyjmovtelfu"), + // }, + // }, + // }, + // Identity: &armlambdatesthyperexecute.ManagedServiceIdentity{ + // PrincipalID: to.Ptr("123e4567-e89b-12d3-a456-426614174000"), + // TenantID: to.Ptr("123e4567-e89b-12d3-a456-426614174000"), + // Type: to.Ptr(armlambdatesthyperexecute.ManagedServiceIdentityTypeNone), + // UserAssignedIdentities: map[string]*armlambdatesthyperexecute.UserAssignedIdentity{ + // }, + // }, + // Tags: map[string]*string{ + // }, + // Location: to.Ptr("cvymsrlt"), + // ID: to.Ptr("/subscriptions/12345678-1234-1234-1234-123456789012/resourceGroups/myResourceGroup/providers/Lambdatest.Hyoerexecute/organizations/testorg"), + // Name: to.Ptr("rayjyvlsggeccbyzkstzr"), + // Type: to.Ptr("ju"), + // SystemData: &armlambdatesthyperexecute.SystemData{ + // CreatedBy: to.Ptr("muialblsfdrvcxxwenlybddkar"), + // CreatedByType: to.Ptr(armlambdatesthyperexecute.CreatedByTypeUser), + // CreatedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2024-09-05T12:10:42.989Z"); return t}()), + // LastModifiedBy: to.Ptr("qnkeaiefwrcpgihdwkesrjw"), + // LastModifiedByType: to.Ptr(armlambdatesthyperexecute.CreatedByTypeUser), + // LastModifiedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2024-09-05T12:10:42.989Z"); return t}()), + // }, + // }, + // }, + // NextLink: to.Ptr("https://microsoft.com/a"), + // }, + // } + } +} + +// Generated from example definition: 2024-02-01/Organizations_ListByResourceGroup_MinimumSet_Gen.json +func ExampleOrganizationsClient_NewListByResourceGroupPager_organizationsListByResourceGroupMaximumSetGenGeneratedByMaximumSetRuleGeneratedByMaximumSetRuleGeneratedByMinimumSetRule() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armlambdatesthyperexecute.NewClientFactory("171E7A75-341B-4472-BC4C-7603C5AB9F32", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + pager := clientFactory.NewOrganizationsClient().NewListByResourceGroupPager("rgopenapi", nil) + for pager.More() { + page, err := pager.NextPage(ctx) + if err != nil { + log.Fatalf("failed to advance page: %v", err) + } + for _, v := range page.Value { + // You could use page here. We use blank identifier for just demo purposes. + _ = v + } + // If the HTTP response code is 200 as defined in example definition, your page structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // page = armlambdatesthyperexecute.OrganizationsClientListByResourceGroupResponse{ + // OrganizationResourceListResult: armlambdatesthyperexecute.OrganizationResourceListResult{ + // Value: []*armlambdatesthyperexecute.OrganizationResource{ + // { + // Location: to.Ptr("cvymsrlt"), + // ID: to.Ptr("/subscriptions/12345678-1234-1234-1234-123456789012/resourceGroups/myResourceGroup/providers/Lambdatest.Hyoerexecute/organizations/testorg"), + // }, + // }, + // }, + // } + } +} + +// Generated from example definition: 2024-02-01/Organizations_ListBySubscription_MaximumSet_Gen.json +func ExampleOrganizationsClient_NewListBySubscriptionPager_organizationsListBySubscriptionMaximumSetGenGeneratedByMaximumSetRuleGeneratedByMaximumSetRuleGeneratedByMaximumSetRule() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armlambdatesthyperexecute.NewClientFactory("171E7A75-341B-4472-BC4C-7603C5AB9F32", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + pager := clientFactory.NewOrganizationsClient().NewListBySubscriptionPager(nil) + for pager.More() { + page, err := pager.NextPage(ctx) + if err != nil { + log.Fatalf("failed to advance page: %v", err) + } + for _, v := range page.Value { + // You could use page here. We use blank identifier for just demo purposes. + _ = v + } + // If the HTTP response code is 200 as defined in example definition, your page structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // page = armlambdatesthyperexecute.OrganizationsClientListBySubscriptionResponse{ + // OrganizationResourceListResult: armlambdatesthyperexecute.OrganizationResourceListResult{ + // Value: []*armlambdatesthyperexecute.OrganizationResource{ + // { + // Properties: &armlambdatesthyperexecute.OrganizationProperties{ + // Marketplace: &armlambdatesthyperexecute.MarketplaceDetails{ + // SubscriptionID: to.Ptr("zetdxwryjgcsnosezfpovkpvgvim"), + // SubscriptionStatus: to.Ptr(armlambdatesthyperexecute.MarketplaceSubscriptionStatusPendingFulfillmentStart), + // OfferDetails: &armlambdatesthyperexecute.OfferDetails{ + // PublisherID: to.Ptr("ufwwpzit"), + // OfferID: to.Ptr("fmljkvoivqmfdiwsu"), + // PlanID: to.Ptr("ssjlabxexw"), + // PlanName: to.Ptr("mrguqu"), + // TermUnit: to.Ptr("acvhavsffebfivyaxhxxsaqzt"), + // TermID: to.Ptr("hxkszxfscsyefeuunyyfskhibr"), + // }, + // }, + // User: &armlambdatesthyperexecute.UserDetails{ + // FirstName: to.Ptr("ssnzyujsrszbptndzeoqzrmbufrhgp"), + // LastName: to.Ptr("nsfylyvdyrtfzfeehmji"), + // EmailAddress: to.Ptr("joe@example.com"), + // Upn: to.Ptr("tfqolz"), + // PhoneNumber: to.Ptr("jkevskjaaylbwjzofkzmxdysejsoir"), + // }, + // ProvisioningState: to.Ptr(armlambdatesthyperexecute.ResourceProvisioningStateSucceeded), + // PartnerProperties: &armlambdatesthyperexecute.PartnerProperties{ + // LicensesSubscribed: to.Ptr[int32](14), + // }, + // SingleSignOnProperties: &armlambdatesthyperexecute.SingleSignOnPropertiesV2{ + // Type: to.Ptr(armlambdatesthyperexecute.SingleSignOnTypeSaml), + // State: to.Ptr(armlambdatesthyperexecute.SingleSignOnStatesInitial), + // EnterpriseAppID: to.Ptr("sonpowym"), + // URL: to.Ptr("qlshnxrfcdpjcpkxxisrn"), + // AADDomains: []*string{ + // to.Ptr("hrgguokssgyrfdzliyjmovtelfu"), + // }, + // }, + // }, + // Identity: &armlambdatesthyperexecute.ManagedServiceIdentity{ + // PrincipalID: to.Ptr("123e4567-e89b-12d3-a456-426614174000"), + // TenantID: to.Ptr("123e4567-e89b-12d3-a456-426614174000"), + // Type: to.Ptr(armlambdatesthyperexecute.ManagedServiceIdentityTypeNone), + // UserAssignedIdentities: map[string]*armlambdatesthyperexecute.UserAssignedIdentity{ + // }, + // }, + // Tags: map[string]*string{ + // }, + // Location: to.Ptr("cvymsrlt"), + // ID: to.Ptr("/subscriptions/12345678-1234-1234-1234-123456789012/resourceGroups/myResourceGroup/providers/Lambdatest.Hyoerexecute/organizations/testorg"), + // Name: to.Ptr("rayjyvlsggeccbyzkstzr"), + // Type: to.Ptr("ju"), + // SystemData: &armlambdatesthyperexecute.SystemData{ + // CreatedBy: to.Ptr("muialblsfdrvcxxwenlybddkar"), + // CreatedByType: to.Ptr(armlambdatesthyperexecute.CreatedByTypeUser), + // CreatedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2024-09-05T12:10:42.989Z"); return t}()), + // LastModifiedBy: to.Ptr("qnkeaiefwrcpgihdwkesrjw"), + // LastModifiedByType: to.Ptr(armlambdatesthyperexecute.CreatedByTypeUser), + // LastModifiedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2024-09-05T12:10:42.989Z"); return t}()), + // }, + // }, + // }, + // NextLink: to.Ptr("https://microsoft.com/a"), + // }, + // } + } +} + +// Generated from example definition: 2024-02-01/Organizations_ListBySubscription_MinimumSet_Gen.json +func ExampleOrganizationsClient_NewListBySubscriptionPager_organizationsListBySubscriptionMaximumSetGenGeneratedByMaximumSetRuleGeneratedByMaximumSetRuleGeneratedByMinimumSetRule() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armlambdatesthyperexecute.NewClientFactory("171E7A75-341B-4472-BC4C-7603C5AB9F32", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + pager := clientFactory.NewOrganizationsClient().NewListBySubscriptionPager(nil) + for pager.More() { + page, err := pager.NextPage(ctx) + if err != nil { + log.Fatalf("failed to advance page: %v", err) + } + for _, v := range page.Value { + // You could use page here. We use blank identifier for just demo purposes. + _ = v + } + // If the HTTP response code is 200 as defined in example definition, your page structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // page = armlambdatesthyperexecute.OrganizationsClientListBySubscriptionResponse{ + // OrganizationResourceListResult: armlambdatesthyperexecute.OrganizationResourceListResult{ + // Value: []*armlambdatesthyperexecute.OrganizationResource{ + // { + // Location: to.Ptr("cvymsrlt"), + // ID: to.Ptr("/subscriptions/12345678-1234-1234-1234-123456789012/resourceGroups/myResourceGroup/providers/Lambdatest.Hyoerexecute/organizations/testorg"), + // }, + // }, + // }, + // } + } +} + +// Generated from example definition: 2024-02-01/Organizations_Update_MaximumSet_Gen.json +func ExampleOrganizationsClient_Update() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armlambdatesthyperexecute.NewClientFactory("171E7A75-341B-4472-BC4C-7603C5AB9F32", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + res, err := clientFactory.NewOrganizationsClient().Update(ctx, "rgopenapi", "testorg", armlambdatesthyperexecute.OrganizationResourceUpdate{ + Tags: map[string]*string{}, + Identity: &armlambdatesthyperexecute.ManagedServiceIdentity{ + Type: to.Ptr(armlambdatesthyperexecute.ManagedServiceIdentityTypeNone), + UserAssignedIdentities: map[string]*armlambdatesthyperexecute.UserAssignedIdentity{}, + }, + }, nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + // You could use response here. We use blank identifier for just demo purposes. + _ = res + // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // res = armlambdatesthyperexecute.OrganizationsClientUpdateResponse{ + // OrganizationResource: &armlambdatesthyperexecute.OrganizationResource{ + // Properties: &armlambdatesthyperexecute.OrganizationProperties{ + // Marketplace: &armlambdatesthyperexecute.MarketplaceDetails{ + // SubscriptionID: to.Ptr("zetdxwryjgcsnosezfpovkpvgvim"), + // SubscriptionStatus: to.Ptr(armlambdatesthyperexecute.MarketplaceSubscriptionStatusPendingFulfillmentStart), + // OfferDetails: &armlambdatesthyperexecute.OfferDetails{ + // PublisherID: to.Ptr("ufwwpzit"), + // OfferID: to.Ptr("fmljkvoivqmfdiwsu"), + // PlanID: to.Ptr("ssjlabxexw"), + // PlanName: to.Ptr("mrguqu"), + // TermUnit: to.Ptr("acvhavsffebfivyaxhxxsaqzt"), + // TermID: to.Ptr("hxkszxfscsyefeuunyyfskhibr"), + // }, + // }, + // User: &armlambdatesthyperexecute.UserDetails{ + // FirstName: to.Ptr("ssnzyujsrszbptndzeoqzrmbufrhgp"), + // LastName: to.Ptr("nsfylyvdyrtfzfeehmji"), + // EmailAddress: to.Ptr("joe@example.com"), + // Upn: to.Ptr("tfqolz"), + // PhoneNumber: to.Ptr("jkevskjaaylbwjzofkzmxdysejsoir"), + // }, + // PartnerProperties: &armlambdatesthyperexecute.PartnerProperties{ + // LicensesSubscribed: to.Ptr[int32](7), + // }, + // ProvisioningState: to.Ptr(armlambdatesthyperexecute.ResourceProvisioningStateSucceeded), + // SingleSignOnProperties: &armlambdatesthyperexecute.SingleSignOnPropertiesV2{ + // Type: to.Ptr(armlambdatesthyperexecute.SingleSignOnTypeSaml), + // State: to.Ptr(armlambdatesthyperexecute.SingleSignOnStatesInitial), + // EnterpriseAppID: to.Ptr("sonpowym"), + // URL: to.Ptr("qlshnxrfcdpjcpkxxisrn"), + // AADDomains: []*string{ + // to.Ptr("hrgguokssgyrfdzliyjmovtelfu"), + // }, + // }, + // }, + // Identity: &armlambdatesthyperexecute.ManagedServiceIdentity{ + // Type: to.Ptr(armlambdatesthyperexecute.ManagedServiceIdentityTypeNone), + // UserAssignedIdentities: map[string]*armlambdatesthyperexecute.UserAssignedIdentity{ + // }, + // PrincipalID: to.Ptr("123e4567-e89b-12d3-a456-426614174000"), + // TenantID: to.Ptr("123e4567-e89b-12d3-a456-426614174000"), + // }, + // Tags: map[string]*string{ + // }, + // Location: to.Ptr("cvymsrlt"), + // ID: to.Ptr("/subscriptions/12345678-1234-1234-1234-123456789012/resourceGroups/myResourceGroup/providers/Lambdatest.Hyoerexecute/organizations/testorg"), + // Name: to.Ptr("rayjyvlsggeccbyzkstzr"), + // Type: to.Ptr("ju"), + // SystemData: &armlambdatesthyperexecute.SystemData{ + // CreatedBy: to.Ptr("muialblsfdrvcxxwenlybddkar"), + // CreatedByType: to.Ptr(armlambdatesthyperexecute.CreatedByTypeUser), + // CreatedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2024-09-05T12:10:42.989Z"); return t}()), + // LastModifiedBy: to.Ptr("qnkeaiefwrcpgihdwkesrjw"), + // LastModifiedByType: to.Ptr(armlambdatesthyperexecute.CreatedByTypeUser), + // LastModifiedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2024-09-05T12:10:42.989Z"); return t}()), + // }, + // }, + // } +} diff --git a/sdk/resourcemanager/lambdatesthyperexecute/armlambdatesthyperexecute/responses.go b/sdk/resourcemanager/lambdatesthyperexecute/armlambdatesthyperexecute/responses.go new file mode 100644 index 000000000000..a137a5a36c49 --- /dev/null +++ b/sdk/resourcemanager/lambdatesthyperexecute/armlambdatesthyperexecute/responses.go @@ -0,0 +1,46 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armlambdatesthyperexecute + +// 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 +} + +// OrganizationsClientCreateOrUpdateResponse contains the response from method OrganizationsClient.BeginCreateOrUpdate. +type OrganizationsClientCreateOrUpdateResponse struct { + // Concrete tracked resource types can be created by aliasing this type using a specific property type. + OrganizationResource +} + +// OrganizationsClientDeleteResponse contains the response from method OrganizationsClient.BeginDelete. +type OrganizationsClientDeleteResponse struct { + // placeholder for future response values +} + +// OrganizationsClientGetResponse contains the response from method OrganizationsClient.Get. +type OrganizationsClientGetResponse struct { + // Concrete tracked resource types can be created by aliasing this type using a specific property type. + OrganizationResource +} + +// OrganizationsClientListByResourceGroupResponse contains the response from method OrganizationsClient.NewListByResourceGroupPager. +type OrganizationsClientListByResourceGroupResponse struct { + // The response of a OrganizationResource list operation. + OrganizationResourceListResult +} + +// OrganizationsClientListBySubscriptionResponse contains the response from method OrganizationsClient.NewListBySubscriptionPager. +type OrganizationsClientListBySubscriptionResponse struct { + // The response of a OrganizationResource list operation. + OrganizationResourceListResult +} + +// OrganizationsClientUpdateResponse contains the response from method OrganizationsClient.Update. +type OrganizationsClientUpdateResponse struct { + // Concrete tracked resource types can be created by aliasing this type using a specific property type. + OrganizationResource +} diff --git a/sdk/resourcemanager/lambdatesthyperexecute/armlambdatesthyperexecute/time_rfc3339.go b/sdk/resourcemanager/lambdatesthyperexecute/armlambdatesthyperexecute/time_rfc3339.go new file mode 100644 index 000000000000..f6763a8ea9cc --- /dev/null +++ b/sdk/resourcemanager/lambdatesthyperexecute/armlambdatesthyperexecute/time_rfc3339.go @@ -0,0 +1,109 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armlambdatesthyperexecute + +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 +} diff --git a/sdk/resourcemanager/lambdatesthyperexecute/armlambdatesthyperexecute/tsp-location.yaml b/sdk/resourcemanager/lambdatesthyperexecute/armlambdatesthyperexecute/tsp-location.yaml new file mode 100644 index 000000000000..cc988b4172d9 --- /dev/null +++ b/sdk/resourcemanager/lambdatesthyperexecute/armlambdatesthyperexecute/tsp-location.yaml @@ -0,0 +1,4 @@ +directory: specification/liftrhyperexecute/LambdaTest.HyperExecute.Management +commit: 1f578543d267d08febc1bebf4e33ffe14363ddfc +repo: Azure/azure-rest-api-specs +additionalDirectories: diff --git a/sdk/resourcemanager/onlineexperimentation/armonlineexperimentation/CHANGELOG.md b/sdk/resourcemanager/onlineexperimentation/armonlineexperimentation/CHANGELOG.md new file mode 100644 index 000000000000..3b61df43b96d --- /dev/null +++ b/sdk/resourcemanager/onlineexperimentation/armonlineexperimentation/CHANGELOG.md @@ -0,0 +1,8 @@ +# Release History + +## 0.1.0 (2025-04-27) +### Other Changes + +The package of `github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/onlineexperimentation/armonlineexperimentation` 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/onlineexperimentation/armonlineexperimentation/LICENSE.txt b/sdk/resourcemanager/onlineexperimentation/armonlineexperimentation/LICENSE.txt new file mode 100644 index 000000000000..dc0c2ffb3dc1 --- /dev/null +++ b/sdk/resourcemanager/onlineexperimentation/armonlineexperimentation/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/onlineexperimentation/armonlineexperimentation/README.md b/sdk/resourcemanager/onlineexperimentation/armonlineexperimentation/README.md new file mode 100644 index 000000000000..8e64ebbe42fe --- /dev/null +++ b/sdk/resourcemanager/onlineexperimentation/armonlineexperimentation/README.md @@ -0,0 +1,90 @@ +# Azure Onlineexperimentation Module for Go + +The `armonlineexperimentation` module provides operations for working with Azure Onlineexperimentation. + +[Source code](https://github.com/Azure/azure-sdk-for-go/tree/main/sdk/resourcemanager/onlineexperimentation/armonlineexperimentation) + +# 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 Onlineexperimentation module: + +```sh +go get github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/onlineexperimentation/armonlineexperimentation +``` + +## Authorization + +When creating a client, you will need to provide a credential for authenticating with Azure Onlineexperimentation. 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 Onlineexperimentation 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 := armonlineexperimentation.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 := armonlineexperimentation.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.NewOnlineExperimentWorkspacesClient() +``` + +## 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 `Onlineexperimentation` 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/onlineexperimentation/armonlineexperimentation/ci.yml b/sdk/resourcemanager/onlineexperimentation/armonlineexperimentation/ci.yml new file mode 100644 index 000000000000..7ead8f99fb55 --- /dev/null +++ b/sdk/resourcemanager/onlineexperimentation/armonlineexperimentation/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/onlineexperimentation/armonlineexperimentation/ + +pr: + branches: + include: + - main + - feature/* + - hotfix/* + - release/* + paths: + include: + - sdk/resourcemanager/onlineexperimentation/armonlineexperimentation/ + +extends: + template: /eng/pipelines/templates/jobs/archetype-sdk-client.yml + parameters: + ServiceDirectory: 'resourcemanager/onlineexperimentation/armonlineexperimentation' diff --git a/sdk/resourcemanager/onlineexperimentation/armonlineexperimentation/client_factory.go b/sdk/resourcemanager/onlineexperimentation/armonlineexperimentation/client_factory.go new file mode 100644 index 000000000000..927d3fd68d1b --- /dev/null +++ b/sdk/resourcemanager/onlineexperimentation/armonlineexperimentation/client_factory.go @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armonlineexperimentation + +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 +} + +// NewOnlineExperimentWorkspacesClient creates a new instance of OnlineExperimentWorkspacesClient. +func (c *ClientFactory) NewOnlineExperimentWorkspacesClient() *OnlineExperimentWorkspacesClient { + return &OnlineExperimentWorkspacesClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewOperationsClient creates a new instance of OperationsClient. +func (c *ClientFactory) NewOperationsClient() *OperationsClient { + return &OperationsClient{ + internal: c.internal, + } +} diff --git a/sdk/resourcemanager/onlineexperimentation/armonlineexperimentation/constants.go b/sdk/resourcemanager/onlineexperimentation/armonlineexperimentation/constants.go new file mode 100644 index 000000000000..868ab94c15e7 --- /dev/null +++ b/sdk/resourcemanager/onlineexperimentation/armonlineexperimentation/constants.go @@ -0,0 +1,182 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armonlineexperimentation + +const ( + moduleName = "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/onlineexperimentation/armonlineexperimentation" + moduleVersion = "v0.1.0" +) + +// ActionType - Extensible enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. +type ActionType string + +const ( + // ActionTypeInternal - Actions are for internal-only APIs. + ActionTypeInternal ActionType = "Internal" +) + +// PossibleActionTypeValues returns the possible values for the ActionType const type. +func PossibleActionTypeValues() []ActionType { + return []ActionType{ + ActionTypeInternal, + } +} + +// CreatedByType - The kind of entity that created the resource. +type CreatedByType string + +const ( + // CreatedByTypeApplication - The entity was created by an application. + CreatedByTypeApplication CreatedByType = "Application" + // CreatedByTypeKey - The entity was created by a key. + CreatedByTypeKey CreatedByType = "Key" + // CreatedByTypeManagedIdentity - The entity was created by a managed identity. + CreatedByTypeManagedIdentity CreatedByType = "ManagedIdentity" + // CreatedByTypeUser - The entity was created by a user. + CreatedByTypeUser CreatedByType = "User" +) + +// PossibleCreatedByTypeValues returns the possible values for the CreatedByType const type. +func PossibleCreatedByTypeValues() []CreatedByType { + return []CreatedByType{ + CreatedByTypeApplication, + CreatedByTypeKey, + CreatedByTypeManagedIdentity, + CreatedByTypeUser, + } +} + +// KeyEncryptionKeyIdentityType - The type of identity to use. +type KeyEncryptionKeyIdentityType string + +const ( + // KeyEncryptionKeyIdentityTypeSystemAssignedIdentity - System assigned identity + KeyEncryptionKeyIdentityTypeSystemAssignedIdentity KeyEncryptionKeyIdentityType = "SystemAssignedIdentity" + // KeyEncryptionKeyIdentityTypeUserAssignedIdentity - User assigned identity + KeyEncryptionKeyIdentityTypeUserAssignedIdentity KeyEncryptionKeyIdentityType = "UserAssignedIdentity" +) + +// PossibleKeyEncryptionKeyIdentityTypeValues returns the possible values for the KeyEncryptionKeyIdentityType const type. +func PossibleKeyEncryptionKeyIdentityTypeValues() []KeyEncryptionKeyIdentityType { + return []KeyEncryptionKeyIdentityType{ + KeyEncryptionKeyIdentityTypeSystemAssignedIdentity, + KeyEncryptionKeyIdentityTypeUserAssignedIdentity, + } +} + +// ManagedServiceIdentityType - Type of managed service identity (where both SystemAssigned and UserAssigned types are allowed). +type ManagedServiceIdentityType string + +const ( + // ManagedServiceIdentityTypeNone - No managed identity. + ManagedServiceIdentityTypeNone ManagedServiceIdentityType = "None" + // ManagedServiceIdentityTypeSystemAssigned - System assigned managed identity. + ManagedServiceIdentityTypeSystemAssigned ManagedServiceIdentityType = "SystemAssigned" + // ManagedServiceIdentityTypeSystemAssignedUserAssigned - System and user assigned managed identity. + ManagedServiceIdentityTypeSystemAssignedUserAssigned ManagedServiceIdentityType = "SystemAssigned,UserAssigned" + // ManagedServiceIdentityTypeUserAssigned - User assigned managed identity. + ManagedServiceIdentityTypeUserAssigned ManagedServiceIdentityType = "UserAssigned" +) + +// PossibleManagedServiceIdentityTypeValues returns the possible values for the ManagedServiceIdentityType const type. +func PossibleManagedServiceIdentityTypeValues() []ManagedServiceIdentityType { + return []ManagedServiceIdentityType{ + ManagedServiceIdentityTypeNone, + ManagedServiceIdentityTypeSystemAssigned, + ManagedServiceIdentityTypeSystemAssignedUserAssigned, + ManagedServiceIdentityTypeUserAssigned, + } +} + +// 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 - Indicates the operation is initiated by a system. + OriginSystem Origin = "system" + // OriginUser - Indicates the operation is initiated by a user. + OriginUser Origin = "user" + // OriginUserSystem - Indicates the operation is initiated by a user or system. + OriginUserSystem Origin = "user,system" +) + +// PossibleOriginValues returns the possible values for the Origin const type. +func PossibleOriginValues() []Origin { + return []Origin{ + OriginSystem, + OriginUser, + OriginUserSystem, + } +} + +// ResourceProvisioningState - The provisioning state of a resource type. +type ResourceProvisioningState string + +const ( + // ResourceProvisioningStateCanceled - Resource creation was canceled. + ResourceProvisioningStateCanceled ResourceProvisioningState = "Canceled" + // ResourceProvisioningStateFailed - Resource creation failed. + ResourceProvisioningStateFailed ResourceProvisioningState = "Failed" + // ResourceProvisioningStateSucceeded - Resource has been created. + ResourceProvisioningStateSucceeded ResourceProvisioningState = "Succeeded" +) + +// PossibleResourceProvisioningStateValues returns the possible values for the ResourceProvisioningState const type. +func PossibleResourceProvisioningStateValues() []ResourceProvisioningState { + return []ResourceProvisioningState{ + ResourceProvisioningStateCanceled, + ResourceProvisioningStateFailed, + ResourceProvisioningStateSucceeded, + } +} + +// WorkspaceSKUName - The allowed SKU names for the online experimentation workspace. +type WorkspaceSKUName string + +const ( + // WorkspaceSKUNameD0 - The Developer service sku name. + WorkspaceSKUNameD0 WorkspaceSKUName = "D0" + // WorkspaceSKUNameF0 - The Free service sku name. + WorkspaceSKUNameF0 WorkspaceSKUName = "F0" + // WorkspaceSKUNameP0 - The Premium service sku name. + WorkspaceSKUNameP0 WorkspaceSKUName = "P0" + // WorkspaceSKUNameS0 - The Standard service sku name. + WorkspaceSKUNameS0 WorkspaceSKUName = "S0" +) + +// PossibleWorkspaceSKUNameValues returns the possible values for the WorkspaceSKUName const type. +func PossibleWorkspaceSKUNameValues() []WorkspaceSKUName { + return []WorkspaceSKUName{ + WorkspaceSKUNameD0, + WorkspaceSKUNameF0, + WorkspaceSKUNameP0, + WorkspaceSKUNameS0, + } +} + +// WorkspaceSKUTier - The allowed SKU tiers for the online experimentation workspace. +type WorkspaceSKUTier string + +const ( + // WorkspaceSKUTierDeveloper - The Developer service tier. + WorkspaceSKUTierDeveloper WorkspaceSKUTier = "Developer" + // WorkspaceSKUTierFree - The Free service tier. + WorkspaceSKUTierFree WorkspaceSKUTier = "Free" + // WorkspaceSKUTierPremium - The Premium service tier. + WorkspaceSKUTierPremium WorkspaceSKUTier = "Premium" + // WorkspaceSKUTierStandard - The Standard service tier. + WorkspaceSKUTierStandard WorkspaceSKUTier = "Standard" +) + +// PossibleWorkspaceSKUTierValues returns the possible values for the WorkspaceSKUTier const type. +func PossibleWorkspaceSKUTierValues() []WorkspaceSKUTier { + return []WorkspaceSKUTier{ + WorkspaceSKUTierDeveloper, + WorkspaceSKUTierFree, + WorkspaceSKUTierPremium, + WorkspaceSKUTierStandard, + } +} diff --git a/sdk/resourcemanager/onlineexperimentation/armonlineexperimentation/fake/internal.go b/sdk/resourcemanager/onlineexperimentation/armonlineexperimentation/fake/internal.go new file mode 100644 index 000000000000..7425b6a669e2 --- /dev/null +++ b/sdk/resourcemanager/onlineexperimentation/armonlineexperimentation/fake/internal.go @@ -0,0 +1,65 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "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 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/onlineexperimentation/armonlineexperimentation/fake/onlineexperimentworkspaces_server.go b/sdk/resourcemanager/onlineexperimentation/armonlineexperimentation/fake/onlineexperimentworkspaces_server.go new file mode 100644 index 000000000000..6deb8be02ec0 --- /dev/null +++ b/sdk/resourcemanager/onlineexperimentation/armonlineexperimentation/fake/onlineexperimentworkspaces_server.go @@ -0,0 +1,374 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/onlineexperimentation/armonlineexperimentation" + "net/http" + "net/url" + "regexp" +) + +// OnlineExperimentWorkspacesServer is a fake server for instances of the armonlineexperimentation.OnlineExperimentWorkspacesClient type. +type OnlineExperimentWorkspacesServer struct { + // BeginCreateOrUpdate is the fake for method OnlineExperimentWorkspacesClient.BeginCreateOrUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + BeginCreateOrUpdate func(ctx context.Context, resourceGroupName string, workspaceName string, resource armonlineexperimentation.OnlineExperimentWorkspace, options *armonlineexperimentation.OnlineExperimentWorkspacesClientBeginCreateOrUpdateOptions) (resp azfake.PollerResponder[armonlineexperimentation.OnlineExperimentWorkspacesClientCreateOrUpdateResponse], errResp azfake.ErrorResponder) + + // BeginDelete is the fake for method OnlineExperimentWorkspacesClient.BeginDelete + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent + BeginDelete func(ctx context.Context, resourceGroupName string, workspaceName string, options *armonlineexperimentation.OnlineExperimentWorkspacesClientBeginDeleteOptions) (resp azfake.PollerResponder[armonlineexperimentation.OnlineExperimentWorkspacesClientDeleteResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method OnlineExperimentWorkspacesClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceGroupName string, workspaceName string, options *armonlineexperimentation.OnlineExperimentWorkspacesClientGetOptions) (resp azfake.Responder[armonlineexperimentation.OnlineExperimentWorkspacesClientGetResponse], errResp azfake.ErrorResponder) + + // NewListByResourceGroupPager is the fake for method OnlineExperimentWorkspacesClient.NewListByResourceGroupPager + // HTTP status codes to indicate success: http.StatusOK + NewListByResourceGroupPager func(resourceGroupName string, options *armonlineexperimentation.OnlineExperimentWorkspacesClientListByResourceGroupOptions) (resp azfake.PagerResponder[armonlineexperimentation.OnlineExperimentWorkspacesClientListByResourceGroupResponse]) + + // NewListBySubscriptionPager is the fake for method OnlineExperimentWorkspacesClient.NewListBySubscriptionPager + // HTTP status codes to indicate success: http.StatusOK + NewListBySubscriptionPager func(options *armonlineexperimentation.OnlineExperimentWorkspacesClientListBySubscriptionOptions) (resp azfake.PagerResponder[armonlineexperimentation.OnlineExperimentWorkspacesClientListBySubscriptionResponse]) + + // BeginUpdate is the fake for method OnlineExperimentWorkspacesClient.BeginUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted + BeginUpdate func(ctx context.Context, resourceGroupName string, workspaceName string, properties armonlineexperimentation.OnlineExperimentWorkspace, options *armonlineexperimentation.OnlineExperimentWorkspacesClientBeginUpdateOptions) (resp azfake.PollerResponder[armonlineexperimentation.OnlineExperimentWorkspacesClientUpdateResponse], errResp azfake.ErrorResponder) +} + +// NewOnlineExperimentWorkspacesServerTransport creates a new instance of OnlineExperimentWorkspacesServerTransport with the provided implementation. +// The returned OnlineExperimentWorkspacesServerTransport instance is connected to an instance of armonlineexperimentation.OnlineExperimentWorkspacesClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewOnlineExperimentWorkspacesServerTransport(srv *OnlineExperimentWorkspacesServer) *OnlineExperimentWorkspacesServerTransport { + return &OnlineExperimentWorkspacesServerTransport{ + srv: srv, + beginCreateOrUpdate: newTracker[azfake.PollerResponder[armonlineexperimentation.OnlineExperimentWorkspacesClientCreateOrUpdateResponse]](), + beginDelete: newTracker[azfake.PollerResponder[armonlineexperimentation.OnlineExperimentWorkspacesClientDeleteResponse]](), + newListByResourceGroupPager: newTracker[azfake.PagerResponder[armonlineexperimentation.OnlineExperimentWorkspacesClientListByResourceGroupResponse]](), + newListBySubscriptionPager: newTracker[azfake.PagerResponder[armonlineexperimentation.OnlineExperimentWorkspacesClientListBySubscriptionResponse]](), + beginUpdate: newTracker[azfake.PollerResponder[armonlineexperimentation.OnlineExperimentWorkspacesClientUpdateResponse]](), + } +} + +// OnlineExperimentWorkspacesServerTransport connects instances of armonlineexperimentation.OnlineExperimentWorkspacesClient to instances of OnlineExperimentWorkspacesServer. +// Don't use this type directly, use NewOnlineExperimentWorkspacesServerTransport instead. +type OnlineExperimentWorkspacesServerTransport struct { + srv *OnlineExperimentWorkspacesServer + beginCreateOrUpdate *tracker[azfake.PollerResponder[armonlineexperimentation.OnlineExperimentWorkspacesClientCreateOrUpdateResponse]] + beginDelete *tracker[azfake.PollerResponder[armonlineexperimentation.OnlineExperimentWorkspacesClientDeleteResponse]] + newListByResourceGroupPager *tracker[azfake.PagerResponder[armonlineexperimentation.OnlineExperimentWorkspacesClientListByResourceGroupResponse]] + newListBySubscriptionPager *tracker[azfake.PagerResponder[armonlineexperimentation.OnlineExperimentWorkspacesClientListBySubscriptionResponse]] + beginUpdate *tracker[azfake.PollerResponder[armonlineexperimentation.OnlineExperimentWorkspacesClientUpdateResponse]] +} + +// Do implements the policy.Transporter interface for OnlineExperimentWorkspacesServerTransport. +func (o *OnlineExperimentWorkspacesServerTransport) 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 *OnlineExperimentWorkspacesServerTransport) 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 onlineExperimentWorkspacesServerTransportInterceptor != nil { + res.resp, res.err, intercepted = onlineExperimentWorkspacesServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "OnlineExperimentWorkspacesClient.BeginCreateOrUpdate": + res.resp, res.err = o.dispatchBeginCreateOrUpdate(req) + case "OnlineExperimentWorkspacesClient.BeginDelete": + res.resp, res.err = o.dispatchBeginDelete(req) + case "OnlineExperimentWorkspacesClient.Get": + res.resp, res.err = o.dispatchGet(req) + case "OnlineExperimentWorkspacesClient.NewListByResourceGroupPager": + res.resp, res.err = o.dispatchNewListByResourceGroupPager(req) + case "OnlineExperimentWorkspacesClient.NewListBySubscriptionPager": + res.resp, res.err = o.dispatchNewListBySubscriptionPager(req) + case "OnlineExperimentWorkspacesClient.BeginUpdate": + res.resp, res.err = o.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 (o *OnlineExperimentWorkspacesServerTransport) dispatchBeginCreateOrUpdate(req *http.Request) (*http.Response, error) { + if o.srv.BeginCreateOrUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginCreateOrUpdate not implemented")} + } + beginCreateOrUpdate := o.beginCreateOrUpdate.get(req) + if beginCreateOrUpdate == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.OnlineExperimentation/workspaces/(?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[armonlineexperimentation.OnlineExperimentWorkspace](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + workspaceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("workspaceName")]) + if err != nil { + return nil, err + } + respr, errRespr := o.srv.BeginCreateOrUpdate(req.Context(), resourceGroupNameParam, workspaceNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginCreateOrUpdate = &respr + o.beginCreateOrUpdate.add(req, beginCreateOrUpdate) + } + + resp, err := server.PollerResponderNext(beginCreateOrUpdate, req) + if err != nil { + return nil, err + } + + if !contains([]int{http.StatusOK, http.StatusCreated}, resp.StatusCode) { + o.beginCreateOrUpdate.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", resp.StatusCode)} + } + if !server.PollerResponderMore(beginCreateOrUpdate) { + o.beginCreateOrUpdate.remove(req) + } + + return resp, nil +} + +func (o *OnlineExperimentWorkspacesServerTransport) dispatchBeginDelete(req *http.Request) (*http.Response, error) { + if o.srv.BeginDelete == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginDelete not implemented")} + } + beginDelete := o.beginDelete.get(req) + if beginDelete == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.OnlineExperimentation/workspaces/(?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 + } + workspaceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("workspaceName")]) + if err != nil { + return nil, err + } + respr, errRespr := o.srv.BeginDelete(req.Context(), resourceGroupNameParam, workspaceNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginDelete = &respr + o.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) { + o.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) { + o.beginDelete.remove(req) + } + + return resp, nil +} + +func (o *OnlineExperimentWorkspacesServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if o.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\.OnlineExperimentation/workspaces/(?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 + } + workspaceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("workspaceName")]) + if err != nil { + return nil, err + } + respr, errRespr := o.srv.Get(req.Context(), resourceGroupNameParam, workspaceNameParam, 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).OnlineExperimentWorkspace, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (o *OnlineExperimentWorkspacesServerTransport) dispatchNewListByResourceGroupPager(req *http.Request) (*http.Response, error) { + if o.srv.NewListByResourceGroupPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListByResourceGroupPager not implemented")} + } + newListByResourceGroupPager := o.newListByResourceGroupPager.get(req) + if newListByResourceGroupPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.OnlineExperimentation/workspaces` + 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 := o.srv.NewListByResourceGroupPager(resourceGroupNameParam, nil) + newListByResourceGroupPager = &resp + o.newListByResourceGroupPager.add(req, newListByResourceGroupPager) + server.PagerResponderInjectNextLinks(newListByResourceGroupPager, req, func(page *armonlineexperimentation.OnlineExperimentWorkspacesClientListByResourceGroupResponse, 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) { + o.newListByResourceGroupPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListByResourceGroupPager) { + o.newListByResourceGroupPager.remove(req) + } + return resp, nil +} + +func (o *OnlineExperimentWorkspacesServerTransport) dispatchNewListBySubscriptionPager(req *http.Request) (*http.Response, error) { + if o.srv.NewListBySubscriptionPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListBySubscriptionPager not implemented")} + } + newListBySubscriptionPager := o.newListBySubscriptionPager.get(req) + if newListBySubscriptionPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.OnlineExperimentation/workspaces` + 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 := o.srv.NewListBySubscriptionPager(nil) + newListBySubscriptionPager = &resp + o.newListBySubscriptionPager.add(req, newListBySubscriptionPager) + server.PagerResponderInjectNextLinks(newListBySubscriptionPager, req, func(page *armonlineexperimentation.OnlineExperimentWorkspacesClientListBySubscriptionResponse, 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) { + o.newListBySubscriptionPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListBySubscriptionPager) { + o.newListBySubscriptionPager.remove(req) + } + return resp, nil +} + +func (o *OnlineExperimentWorkspacesServerTransport) dispatchBeginUpdate(req *http.Request) (*http.Response, error) { + if o.srv.BeginUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginUpdate not implemented")} + } + beginUpdate := o.beginUpdate.get(req) + if beginUpdate == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.OnlineExperimentation/workspaces/(?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[armonlineexperimentation.OnlineExperimentWorkspace](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + workspaceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("workspaceName")]) + if err != nil { + return nil, err + } + respr, errRespr := o.srv.BeginUpdate(req.Context(), resourceGroupNameParam, workspaceNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginUpdate = &respr + o.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) { + o.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) { + o.beginUpdate.remove(req) + } + + return resp, nil +} + +// set this to conditionally intercept incoming requests to OnlineExperimentWorkspacesServerTransport +var onlineExperimentWorkspacesServerTransportInterceptor 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/onlineexperimentation/armonlineexperimentation/fake/operations_server.go b/sdk/resourcemanager/onlineexperimentation/armonlineexperimentation/fake/operations_server.go new file mode 100644 index 000000000000..9b2de84cea29 --- /dev/null +++ b/sdk/resourcemanager/onlineexperimentation/armonlineexperimentation/fake/operations_server.go @@ -0,0 +1,117 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/onlineexperimentation/armonlineexperimentation" + "net/http" +) + +// OperationsServer is a fake server for instances of the armonlineexperimentation.OperationsClient type. +type OperationsServer struct { + // NewListPager is the fake for method OperationsClient.NewListPager + // HTTP status codes to indicate success: http.StatusOK + NewListPager func(options *armonlineexperimentation.OperationsClientListOptions) (resp azfake.PagerResponder[armonlineexperimentation.OperationsClientListResponse]) +} + +// NewOperationsServerTransport creates a new instance of OperationsServerTransport with the provided implementation. +// The returned OperationsServerTransport instance is connected to an instance of armonlineexperimentation.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[armonlineexperimentation.OperationsClientListResponse]](), + } +} + +// OperationsServerTransport connects instances of armonlineexperimentation.OperationsClient to instances of OperationsServer. +// Don't use this type directly, use NewOperationsServerTransport instead. +type OperationsServerTransport struct { + srv *OperationsServer + newListPager *tracker[azfake.PagerResponder[armonlineexperimentation.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 *armonlineexperimentation.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/onlineexperimentation/armonlineexperimentation/fake/server_factory.go b/sdk/resourcemanager/onlineexperimentation/armonlineexperimentation/fake/server_factory.go new file mode 100644 index 000000000000..f980c9b1b225 --- /dev/null +++ b/sdk/resourcemanager/onlineexperimentation/armonlineexperimentation/fake/server_factory.go @@ -0,0 +1,81 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "errors" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" + "sync" +) + +// ServerFactory is a fake server for instances of the armonlineexperimentation.ClientFactory type. +type ServerFactory struct { + // OnlineExperimentWorkspacesServer contains the fakes for client OnlineExperimentWorkspacesClient + OnlineExperimentWorkspacesServer OnlineExperimentWorkspacesServer + + // OperationsServer contains the fakes for client OperationsClient + OperationsServer OperationsServer +} + +// NewServerFactoryTransport creates a new instance of ServerFactoryTransport with the provided implementation. +// The returned ServerFactoryTransport instance is connected to an instance of armonlineexperimentation.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 armonlineexperimentation.ClientFactory to instances of ServerFactory. +// Don't use this type directly, use NewServerFactoryTransport instead. +type ServerFactoryTransport struct { + srv *ServerFactory + trMu sync.Mutex + trOnlineExperimentWorkspacesServer *OnlineExperimentWorkspacesServerTransport + trOperationsServer *OperationsServerTransport +} + +// 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 "OnlineExperimentWorkspacesClient": + initServer(s, &s.trOnlineExperimentWorkspacesServer, func() *OnlineExperimentWorkspacesServerTransport { + return NewOnlineExperimentWorkspacesServerTransport(&s.srv.OnlineExperimentWorkspacesServer) + }) + resp, err = s.trOnlineExperimentWorkspacesServer.Do(req) + case "OperationsClient": + initServer(s, &s.trOperationsServer, func() *OperationsServerTransport { return NewOperationsServerTransport(&s.srv.OperationsServer) }) + resp, err = s.trOperationsServer.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/onlineexperimentation/armonlineexperimentation/fake/time_rfc3339.go b/sdk/resourcemanager/onlineexperimentation/armonlineexperimentation/fake/time_rfc3339.go new file mode 100644 index 000000000000..87ee11e83b32 --- /dev/null +++ b/sdk/resourcemanager/onlineexperimentation/armonlineexperimentation/fake/time_rfc3339.go @@ -0,0 +1,109 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "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 +} diff --git a/sdk/resourcemanager/onlineexperimentation/armonlineexperimentation/go.mod b/sdk/resourcemanager/onlineexperimentation/armonlineexperimentation/go.mod new file mode 100644 index 000000000000..e785b0027f46 --- /dev/null +++ b/sdk/resourcemanager/onlineexperimentation/armonlineexperimentation/go.mod @@ -0,0 +1,23 @@ +module github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/onlineexperimentation/armonlineexperimentation + +go 1.23.0 + +toolchain go1.23.8 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.17.1 + github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.7.0 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.10.0 // indirect + github.com/AzureAD/microsoft-authentication-library-for-go v1.2.2 // indirect + github.com/golang-jwt/jwt/v5 v5.2.1 // indirect + github.com/google/uuid v1.6.0 // indirect + github.com/kylelemons/godebug v1.1.0 // indirect + github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c // indirect + golang.org/x/crypto v0.36.0 // indirect + golang.org/x/net v0.37.0 // indirect + golang.org/x/sys v0.31.0 // indirect + golang.org/x/text v0.23.0 // indirect +) diff --git a/sdk/resourcemanager/onlineexperimentation/armonlineexperimentation/go.sum b/sdk/resourcemanager/onlineexperimentation/armonlineexperimentation/go.sum new file mode 100644 index 000000000000..1f92486fbbcf --- /dev/null +++ b/sdk/resourcemanager/onlineexperimentation/armonlineexperimentation/go.sum @@ -0,0 +1,33 @@ +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/azidentity v1.7.0 h1:tfLQ34V6F7tVSwoTf/4lH5sE0o6eCJuNDTmH09nDpbc= +github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.7.0/go.mod h1:9kIvujWAA58nmPmWB1m23fyWic1kYZMxD9CxaWn4Qpg= +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/AzureAD/microsoft-authentication-library-for-go v1.2.2 h1:XHOnouVk1mxXfQidrMEnLlPk9UMeRtyBTnEFtxkV0kU= +github.com/AzureAD/microsoft-authentication-library-for-go v1.2.2/go.mod h1:wP83P5OoQ5p6ip3ScPr0BAq0BvuPAvacpEuSzyouqAI= +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/golang-jwt/jwt/v5 v5.2.1 h1:OuVbFODueb089Lh128TAcimifWaLhJwVflnrgM17wHk= +github.com/golang-jwt/jwt/v5 v5.2.1/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk= +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc= +github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= +github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c h1:+mdjkGKdHQG3305AYmdv1U2eRNDiU2ErMBj1gwrq8eQ= +github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c/go.mod h1:7rwL4CYBLnjLxUqIJNnCWiEdr3bn6IUYi15bNlnbCCU= +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/crypto v0.36.0 h1:AnAEvhDddvBdpY+uR+MyHmuZzzNqXSe/GvuDeob5L34= +golang.org/x/crypto v0.36.0/go.mod h1:Y4J0ReaxCR1IMaabaSMugxJES1EpwhBHhv2bDHklZvc= +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/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.31.0 h1:ioabZlmFYtWhL+TRYpcnNlLwhyxaM9kWTDEmfnprqik= +golang.org/x/sys v0.31.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= +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/onlineexperimentation/armonlineexperimentation/models.go b/sdk/resourcemanager/onlineexperimentation/armonlineexperimentation/models.go new file mode 100644 index 000000000000..71df56b213ab --- /dev/null +++ b/sdk/resourcemanager/onlineexperimentation/armonlineexperimentation/models.go @@ -0,0 +1,207 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armonlineexperimentation + +import "time" + +// CustomerManagedKeyEncryption - Customer-managed key encryption properties for the resource. +type CustomerManagedKeyEncryption struct { + // All identity configuration for Customer-managed key settings defining which identity should be used to auth to Key Vault. + KeyEncryptionKeyIdentity *KeyEncryptionKeyIdentity + + // key encryption key Url, versioned or non-versioned. Ex: https://contosovault.vault.azure.net/keys/contosokek/562a4bb76b524a1493a6afe8e536ee78 + // or https://contosovault.vault.azure.net/keys/contosokek. + KeyEncryptionKeyURL *string +} + +// KeyEncryptionKeyIdentity - All identity configuration for Customer-managed key settings defining which identity should +// be used to auth to Key Vault. +type KeyEncryptionKeyIdentity struct { + // application client identity to use for accessing key encryption key Url in a different tenant. Ex: f83c6b1b-4d34-47e4-bb34-9d83df58b540 + FederatedClientID *string + + // The type of identity to use. Values can be systemAssignedIdentity, userAssignedIdentity, or delegatedResourceIdentity. + IdentityType *KeyEncryptionKeyIdentityType + + // User assigned identity to use for accessing key encryption key Url. Ex: /subscriptions/fa5fc227-a624-475e-b696-cdd604c735bc/resourceGroups//providers/Microsoft.ManagedIdentity/userAssignedIdentities/myId. Mutually exclusive with identityType systemAssignedIdentity. + UserAssignedIdentityResourceID *string +} + +// ManagedServiceIdentity - Managed service identity (system assigned and/or user assigned identities) +type ManagedServiceIdentity struct { + // REQUIRED; The type of managed identity assigned to this resource. + Type *ManagedServiceIdentityType + + // The identities assigned to this resource by the user. + 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 +} + +// OnlineExperimentWorkspace - An online experiment workspace resource. +type OnlineExperimentWorkspace struct { + // REQUIRED; The geo-location where the resource lives + Location *string + + // READ-ONLY; The name of the OnlineExperimentWorkspace + Name *string + + // The managed service identities assigned to this resource. + Identity *ManagedServiceIdentity + + // The resource-specific properties for this resource. + Properties *OnlineExperimentWorkspaceProperties + + // The SKU (Stock Keeping Unit) assigned to this resource. + SKU *WorkspaceSKU + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; 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 +} + +// OnlineExperimentWorkspaceListResult - The response of a OnlineExperimentWorkspace list operation. +type OnlineExperimentWorkspaceListResult struct { + // REQUIRED; The OnlineExperimentWorkspace items on this page + Value []*OnlineExperimentWorkspace + + // The link to the next page of items + NextLink *string +} + +// OnlineExperimentWorkspaceProperties - The properties of an online experiment workspace. +type OnlineExperimentWorkspaceProperties struct { + // REQUIRED; The resource identifier of App Configuration with which this online experiment workspace is tied for experimentation. + // This is a required field for creating an online experiment workspace. + AppConfigurationResourceID *string + + // REQUIRED; The resource identifier of the Log Analytics workspace which online experiment workspace uses for generating + // experiment analysis results. + LogAnalyticsWorkspaceResourceID *string + + // REQUIRED; The resource identifier of storage account where logs are exported from Log Analytics workspace. Online Experiment + // workspace uses it generating experiment analysis results. + LogsExporterStorageAccountResourceID *string + + // The encryption configuration for the online experiment workspace resource. + Encryption *ResourceEncryptionConfiguration + + // READ-ONLY; The data plane endpoint for the online experiment workspace resource. + Endpoint *string + + // READ-ONLY; The provisioning state for the resource + ProvisioningState *ResourceProvisioningState + + // READ-ONLY; The Id of the workspace. + WorkspaceID *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; Extensible 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 Azure + // Resource Manager/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 and 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 { + // REQUIRED; The Operation items on this page + Value []*Operation + + // The link to the next page of items + NextLink *string +} + +// ResourceEncryptionConfiguration - The encryption configuration for the online experiment workspace resource. +type ResourceEncryptionConfiguration struct { + // All Customer-managed key encryption properties for the resource. + CustomerManagedKeyEncryption *CustomerManagedKeyEncryption +} + +// 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 +} + +// 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 +} + +// WorkspaceSKU - The SKU (Stock Keeping Unit) assigned to this resource. +type WorkspaceSKU struct { + // REQUIRED; The name of the SKU. Ex - F0, P0. It is typically a letter+number code + Name *WorkspaceSKUName + + // READ-ONLY; The name of the SKU tier + Tier *WorkspaceSKUTier +} diff --git a/sdk/resourcemanager/onlineexperimentation/armonlineexperimentation/models_serde.go b/sdk/resourcemanager/onlineexperimentation/armonlineexperimentation/models_serde.go new file mode 100644 index 000000000000..80fb0849cfdf --- /dev/null +++ b/sdk/resourcemanager/onlineexperimentation/armonlineexperimentation/models_serde.go @@ -0,0 +1,527 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armonlineexperimentation + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "reflect" +) + +// MarshalJSON implements the json.Marshaller interface for type CustomerManagedKeyEncryption. +func (c CustomerManagedKeyEncryption) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "keyEncryptionKeyIdentity", c.KeyEncryptionKeyIdentity) + populate(objectMap, "keyEncryptionKeyUrl", c.KeyEncryptionKeyURL) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CustomerManagedKeyEncryption. +func (c *CustomerManagedKeyEncryption) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "keyEncryptionKeyIdentity": + err = unpopulate(val, "KeyEncryptionKeyIdentity", &c.KeyEncryptionKeyIdentity) + delete(rawMsg, key) + case "keyEncryptionKeyUrl": + err = unpopulate(val, "KeyEncryptionKeyURL", &c.KeyEncryptionKeyURL) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type KeyEncryptionKeyIdentity. +func (k KeyEncryptionKeyIdentity) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "federatedClientId", k.FederatedClientID) + populate(objectMap, "identityType", k.IdentityType) + populate(objectMap, "userAssignedIdentityResourceId", k.UserAssignedIdentityResourceID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type KeyEncryptionKeyIdentity. +func (k *KeyEncryptionKeyIdentity) 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", k, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "federatedClientId": + err = unpopulate(val, "FederatedClientID", &k.FederatedClientID) + delete(rawMsg, key) + case "identityType": + err = unpopulate(val, "IdentityType", &k.IdentityType) + delete(rawMsg, key) + case "userAssignedIdentityResourceId": + err = unpopulate(val, "UserAssignedIdentityResourceID", &k.UserAssignedIdentityResourceID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", k, 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 OnlineExperimentWorkspace. +func (o OnlineExperimentWorkspace) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", o.ID) + populate(objectMap, "identity", o.Identity) + populate(objectMap, "location", o.Location) + populate(objectMap, "name", o.Name) + populate(objectMap, "properties", o.Properties) + populate(objectMap, "sku", o.SKU) + populate(objectMap, "systemData", o.SystemData) + populate(objectMap, "tags", o.Tags) + populate(objectMap, "type", o.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OnlineExperimentWorkspace. +func (o *OnlineExperimentWorkspace) 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 "id": + err = unpopulate(val, "ID", &o.ID) + delete(rawMsg, key) + case "identity": + err = unpopulate(val, "Identity", &o.Identity) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &o.Location) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &o.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &o.Properties) + delete(rawMsg, key) + case "sku": + err = unpopulate(val, "SKU", &o.SKU) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &o.SystemData) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &o.Tags) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &o.Type) + 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 OnlineExperimentWorkspaceListResult. +func (o OnlineExperimentWorkspaceListResult) 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 OnlineExperimentWorkspaceListResult. +func (o *OnlineExperimentWorkspaceListResult) 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 OnlineExperimentWorkspaceProperties. +func (o OnlineExperimentWorkspaceProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "appConfigurationResourceId", o.AppConfigurationResourceID) + populate(objectMap, "encryption", o.Encryption) + populate(objectMap, "endpoint", o.Endpoint) + populate(objectMap, "logAnalyticsWorkspaceResourceId", o.LogAnalyticsWorkspaceResourceID) + populate(objectMap, "logsExporterStorageAccountResourceId", o.LogsExporterStorageAccountResourceID) + populate(objectMap, "provisioningState", o.ProvisioningState) + populate(objectMap, "workspaceId", o.WorkspaceID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OnlineExperimentWorkspaceProperties. +func (o *OnlineExperimentWorkspaceProperties) 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 "appConfigurationResourceId": + err = unpopulate(val, "AppConfigurationResourceID", &o.AppConfigurationResourceID) + delete(rawMsg, key) + case "encryption": + err = unpopulate(val, "Encryption", &o.Encryption) + delete(rawMsg, key) + case "endpoint": + err = unpopulate(val, "Endpoint", &o.Endpoint) + delete(rawMsg, key) + case "logAnalyticsWorkspaceResourceId": + err = unpopulate(val, "LogAnalyticsWorkspaceResourceID", &o.LogAnalyticsWorkspaceResourceID) + delete(rawMsg, key) + case "logsExporterStorageAccountResourceId": + err = unpopulate(val, "LogsExporterStorageAccountResourceID", &o.LogsExporterStorageAccountResourceID) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &o.ProvisioningState) + delete(rawMsg, key) + case "workspaceId": + err = unpopulate(val, "WorkspaceID", &o.WorkspaceID) + 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 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 ResourceEncryptionConfiguration. +func (r ResourceEncryptionConfiguration) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "customerManagedKeyEncryption", r.CustomerManagedKeyEncryption) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ResourceEncryptionConfiguration. +func (r *ResourceEncryptionConfiguration) 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 "customerManagedKeyEncryption": + err = unpopulate(val, "CustomerManagedKeyEncryption", &r.CustomerManagedKeyEncryption) + 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 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 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 +} + +// MarshalJSON implements the json.Marshaller interface for type WorkspaceSKU. +func (w WorkspaceSKU) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", w.Name) + populate(objectMap, "tier", w.Tier) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type WorkspaceSKU. +func (w *WorkspaceSKU) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", w, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &w.Name) + delete(rawMsg, key) + case "tier": + err = unpopulate(val, "Tier", &w.Tier) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", w, err) + } + } + return nil +} + +func populate(m map[string]any, k string, v any) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} + +func 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/onlineexperimentation/armonlineexperimentation/onlineexperimentworkspaces_client.go b/sdk/resourcemanager/onlineexperimentation/armonlineexperimentation/onlineexperimentworkspaces_client.go new file mode 100644 index 000000000000..b16356f7f448 --- /dev/null +++ b/sdk/resourcemanager/onlineexperimentation/armonlineexperimentation/onlineexperimentworkspaces_client.go @@ -0,0 +1,458 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armonlineexperimentation + +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" +) + +// OnlineExperimentWorkspacesClient contains the methods for the OnlineExperimentWorkspaces group. +// Don't use this type directly, use NewOnlineExperimentWorkspacesClient() instead. +type OnlineExperimentWorkspacesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewOnlineExperimentWorkspacesClient creates a new instance of OnlineExperimentWorkspacesClient 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 NewOnlineExperimentWorkspacesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*OnlineExperimentWorkspacesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &OnlineExperimentWorkspacesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Create an experiment workspace, or update an existing workspace +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2025-05-31-preview +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - workspaceName - The name of the OnlineExperimentWorkspace +// - resource - Resource create parameters. +// - options - OnlineExperimentWorkspacesClientBeginCreateOrUpdateOptions contains the optional parameters for the OnlineExperimentWorkspacesClient.BeginCreateOrUpdate +// method. +func (client *OnlineExperimentWorkspacesClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, workspaceName string, resource OnlineExperimentWorkspace, options *OnlineExperimentWorkspacesClientBeginCreateOrUpdateOptions) (*runtime.Poller[OnlineExperimentWorkspacesClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, workspaceName, resource, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[OnlineExperimentWorkspacesClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[OnlineExperimentWorkspacesClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Create an experiment workspace, or update an existing workspace +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2025-05-31-preview +func (client *OnlineExperimentWorkspacesClient) createOrUpdate(ctx context.Context, resourceGroupName string, workspaceName string, resource OnlineExperimentWorkspace, options *OnlineExperimentWorkspacesClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "OnlineExperimentWorkspacesClient.BeginCreateOrUpdate" + 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, workspaceName, 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 +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *OnlineExperimentWorkspacesClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, workspaceName string, resource OnlineExperimentWorkspace, _ *OnlineExperimentWorkspacesClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.OnlineExperimentation/workspaces/{workspaceName}" + 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 workspaceName == "" { + return nil, errors.New("parameter workspaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{workspaceName}", url.PathEscape(workspaceName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2025-05-31-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, resource); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Deletes an experiment workspace +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2025-05-31-preview +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - workspaceName - The name of the OnlineExperimentWorkspace +// - options - OnlineExperimentWorkspacesClientBeginDeleteOptions contains the optional parameters for the OnlineExperimentWorkspacesClient.BeginDelete +// method. +func (client *OnlineExperimentWorkspacesClient) BeginDelete(ctx context.Context, resourceGroupName string, workspaceName string, options *OnlineExperimentWorkspacesClientBeginDeleteOptions) (*runtime.Poller[OnlineExperimentWorkspacesClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, workspaceName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[OnlineExperimentWorkspacesClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[OnlineExperimentWorkspacesClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes an experiment workspace +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2025-05-31-preview +func (client *OnlineExperimentWorkspacesClient) deleteOperation(ctx context.Context, resourceGroupName string, workspaceName string, options *OnlineExperimentWorkspacesClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "OnlineExperimentWorkspacesClient.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, workspaceName, 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 *OnlineExperimentWorkspacesClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, workspaceName string, _ *OnlineExperimentWorkspacesClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.OnlineExperimentation/workspaces/{workspaceName}" + 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 workspaceName == "" { + return nil, errors.New("parameter workspaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{workspaceName}", url.PathEscape(workspaceName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2025-05-31-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Gets an experiment workspace +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2025-05-31-preview +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - workspaceName - The name of the OnlineExperimentWorkspace +// - options - OnlineExperimentWorkspacesClientGetOptions contains the optional parameters for the OnlineExperimentWorkspacesClient.Get +// method. +func (client *OnlineExperimentWorkspacesClient) Get(ctx context.Context, resourceGroupName string, workspaceName string, options *OnlineExperimentWorkspacesClientGetOptions) (OnlineExperimentWorkspacesClientGetResponse, error) { + var err error + const operationName = "OnlineExperimentWorkspacesClient.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, workspaceName, options) + if err != nil { + return OnlineExperimentWorkspacesClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return OnlineExperimentWorkspacesClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return OnlineExperimentWorkspacesClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *OnlineExperimentWorkspacesClient) getCreateRequest(ctx context.Context, resourceGroupName string, workspaceName string, _ *OnlineExperimentWorkspacesClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.OnlineExperimentation/workspaces/{workspaceName}" + 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 workspaceName == "" { + return nil, errors.New("parameter workspaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{workspaceName}", url.PathEscape(workspaceName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2025-05-31-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *OnlineExperimentWorkspacesClient) getHandleResponse(resp *http.Response) (OnlineExperimentWorkspacesClientGetResponse, error) { + result := OnlineExperimentWorkspacesClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.OnlineExperimentWorkspace); err != nil { + return OnlineExperimentWorkspacesClientGetResponse{}, err + } + return result, nil +} + +// NewListByResourceGroupPager - Gets all experiment workspaces in a resource group. +// +// Generated from API version 2025-05-31-preview +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - options - OnlineExperimentWorkspacesClientListByResourceGroupOptions contains the optional parameters for the OnlineExperimentWorkspacesClient.NewListByResourceGroupPager +// method. +func (client *OnlineExperimentWorkspacesClient) NewListByResourceGroupPager(resourceGroupName string, options *OnlineExperimentWorkspacesClientListByResourceGroupOptions) *runtime.Pager[OnlineExperimentWorkspacesClientListByResourceGroupResponse] { + return runtime.NewPager(runtime.PagingHandler[OnlineExperimentWorkspacesClientListByResourceGroupResponse]{ + More: func(page OnlineExperimentWorkspacesClientListByResourceGroupResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *OnlineExperimentWorkspacesClientListByResourceGroupResponse) (OnlineExperimentWorkspacesClientListByResourceGroupResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "OnlineExperimentWorkspacesClient.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 OnlineExperimentWorkspacesClientListByResourceGroupResponse{}, err + } + return client.listByResourceGroupHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByResourceGroupCreateRequest creates the ListByResourceGroup request. +func (client *OnlineExperimentWorkspacesClient) listByResourceGroupCreateRequest(ctx context.Context, resourceGroupName string, _ *OnlineExperimentWorkspacesClientListByResourceGroupOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.OnlineExperimentation/workspaces" + 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", "2025-05-31-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByResourceGroupHandleResponse handles the ListByResourceGroup response. +func (client *OnlineExperimentWorkspacesClient) listByResourceGroupHandleResponse(resp *http.Response) (OnlineExperimentWorkspacesClientListByResourceGroupResponse, error) { + result := OnlineExperimentWorkspacesClientListByResourceGroupResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.OnlineExperimentWorkspaceListResult); err != nil { + return OnlineExperimentWorkspacesClientListByResourceGroupResponse{}, err + } + return result, nil +} + +// NewListBySubscriptionPager - Gets all experiment workspaces in the specified subscription. +// +// Generated from API version 2025-05-31-preview +// - options - OnlineExperimentWorkspacesClientListBySubscriptionOptions contains the optional parameters for the OnlineExperimentWorkspacesClient.NewListBySubscriptionPager +// method. +func (client *OnlineExperimentWorkspacesClient) NewListBySubscriptionPager(options *OnlineExperimentWorkspacesClientListBySubscriptionOptions) *runtime.Pager[OnlineExperimentWorkspacesClientListBySubscriptionResponse] { + return runtime.NewPager(runtime.PagingHandler[OnlineExperimentWorkspacesClientListBySubscriptionResponse]{ + More: func(page OnlineExperimentWorkspacesClientListBySubscriptionResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *OnlineExperimentWorkspacesClientListBySubscriptionResponse) (OnlineExperimentWorkspacesClientListBySubscriptionResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "OnlineExperimentWorkspacesClient.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 OnlineExperimentWorkspacesClientListBySubscriptionResponse{}, err + } + return client.listBySubscriptionHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listBySubscriptionCreateRequest creates the ListBySubscription request. +func (client *OnlineExperimentWorkspacesClient) listBySubscriptionCreateRequest(ctx context.Context, _ *OnlineExperimentWorkspacesClientListBySubscriptionOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.OnlineExperimentation/workspaces" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2025-05-31-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listBySubscriptionHandleResponse handles the ListBySubscription response. +func (client *OnlineExperimentWorkspacesClient) listBySubscriptionHandleResponse(resp *http.Response) (OnlineExperimentWorkspacesClientListBySubscriptionResponse, error) { + result := OnlineExperimentWorkspacesClientListBySubscriptionResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.OnlineExperimentWorkspaceListResult); err != nil { + return OnlineExperimentWorkspacesClientListBySubscriptionResponse{}, err + } + return result, nil +} + +// BeginUpdate - Patch an experiment workspace +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2025-05-31-preview +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - workspaceName - The name of the OnlineExperimentWorkspace +// - properties - The resource properties to be updated. +// - options - OnlineExperimentWorkspacesClientBeginUpdateOptions contains the optional parameters for the OnlineExperimentWorkspacesClient.BeginUpdate +// method. +func (client *OnlineExperimentWorkspacesClient) BeginUpdate(ctx context.Context, resourceGroupName string, workspaceName string, properties OnlineExperimentWorkspace, options *OnlineExperimentWorkspacesClientBeginUpdateOptions) (*runtime.Poller[OnlineExperimentWorkspacesClientUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.update(ctx, resourceGroupName, workspaceName, properties, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[OnlineExperimentWorkspacesClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[OnlineExperimentWorkspacesClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Update - Patch an experiment workspace +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2025-05-31-preview +func (client *OnlineExperimentWorkspacesClient) update(ctx context.Context, resourceGroupName string, workspaceName string, properties OnlineExperimentWorkspace, options *OnlineExperimentWorkspacesClientBeginUpdateOptions) (*http.Response, error) { + var err error + const operationName = "OnlineExperimentWorkspacesClient.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, workspaceName, 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 *OnlineExperimentWorkspacesClient) updateCreateRequest(ctx context.Context, resourceGroupName string, workspaceName string, properties OnlineExperimentWorkspace, _ *OnlineExperimentWorkspacesClientBeginUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.OnlineExperimentation/workspaces/{workspaceName}" + 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 workspaceName == "" { + return nil, errors.New("parameter workspaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{workspaceName}", url.PathEscape(workspaceName)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2025-05-31-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, properties); err != nil { + return nil, err + } + return req, nil +} diff --git a/sdk/resourcemanager/onlineexperimentation/armonlineexperimentation/onlineexperimentworkspaces_client_example_test.go b/sdk/resourcemanager/onlineexperimentation/armonlineexperimentation/onlineexperimentworkspaces_client_example_test.go new file mode 100644 index 000000000000..20099e68d167 --- /dev/null +++ b/sdk/resourcemanager/onlineexperimentation/armonlineexperimentation/onlineexperimentworkspaces_client_example_test.go @@ -0,0 +1,679 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armonlineexperimentation_test + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/Azure/azure-sdk-for-go/sdk/azidentity" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/onlineexperimentation/armonlineexperimentation" + "log" +) + +// Generated from example definition: 2025-05-31-preview/OnlineExperimentWorkspaces_CreateOrUpdate.json +func ExampleOnlineExperimentWorkspacesClient_BeginCreateOrUpdate_createOrUpdateAnOnlineExperimentWorkspaceWithFreeSku() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armonlineexperimentation.NewClientFactory("fa5fc227-a624-475e-b696-cdd604c735bc", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + poller, err := clientFactory.NewOnlineExperimentWorkspacesClient().BeginCreateOrUpdate(ctx, "res9871", "expworkspace7", armonlineexperimentation.OnlineExperimentWorkspace{ + Location: to.Ptr("eastus2"), + Tags: map[string]*string{ + "newKey": to.Ptr("newVal"), + }, + Properties: &armonlineexperimentation.OnlineExperimentWorkspaceProperties{ + LogAnalyticsWorkspaceResourceID: to.Ptr("/subscriptions/fa5fc227-a624-475e-b696-cdd604c735bc/resourceGroups/res9871/providers/Microsoft.OperationalInsights/workspaces/log9871"), + LogsExporterStorageAccountResourceID: to.Ptr("/subscriptions/fa5fc227-a624-475e-b696-cdd604c735bc/resourceGroups/res9871/providers/Microsoft.Storage/storageAccounts/sto9871"), + AppConfigurationResourceID: to.Ptr("/subscriptions/fa5fc227-a624-475e-b696-cdd604c735bc/resourceGroups/res9871/providers/Microsoft.AppConfiguration/configurationStores/appconfig9871"), + }, + Identity: &armonlineexperimentation.ManagedServiceIdentity{ + Type: to.Ptr(armonlineexperimentation.ManagedServiceIdentityTypeUserAssigned), + UserAssignedIdentities: map[string]*armonlineexperimentation.UserAssignedIdentity{ + "/subscriptions/fa5fc227-a624-475e-b696-cdd604c735bc/resourceGroups/eu2cgroup/providers/Microsoft.ManagedIdentity/userAssignedIdentities/id1": {}, + "/subscriptions/fa5fc227-a624-475e-b696-cdd604c735bc/resourceGroups/eu2cgroup/providers/Microsoft.ManagedIdentity/userAssignedIdentities/id2": {}, + }, + }, + SKU: &armonlineexperimentation.WorkspaceSKU{ + Name: to.Ptr(armonlineexperimentation.WorkspaceSKUNameF0), + }, + }, nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + res, err := poller.PollUntilDone(ctx, nil) + if err != nil { + log.Fatalf("failed to pull the result: %v", err) + } + // You could use response here. We use blank identifier for just demo purposes. + _ = res + // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // res = armonlineexperimentation.OnlineExperimentWorkspacesClientCreateOrUpdateResponse{ + // OnlineExperimentWorkspace: &armonlineexperimentation.OnlineExperimentWorkspace{ + // ID: to.Ptr("/subscriptions/fa5fc227-a624-475e-b696-cdd604c735bc/resourceGroups/res9871/providers/Microsoft.OnlineExperimentation/workspaces/expworkspace7"), + // Name: to.Ptr("expworkspace7"), + // Type: to.Ptr("Microsoft.OnlineExperimentation/workspaces"), + // Location: to.Ptr("eastus2"), + // Tags: map[string]*string{ + // "newKey": to.Ptr("newVal"), + // }, + // Properties: &armonlineexperimentation.OnlineExperimentWorkspaceProperties{ + // WorkspaceID: to.Ptr("02270d43-f68a-401b-b526-86942525c351"), + // ProvisioningState: to.Ptr(armonlineexperimentation.ResourceProvisioningStateSucceeded), + // LogAnalyticsWorkspaceResourceID: to.Ptr("/subscriptions/fa5fc227-a624-475e-b696-cdd604c735bc/resourceGroups/res9871/providers/Microsoft.OperationalInsights/workspaces/log9871"), + // LogsExporterStorageAccountResourceID: to.Ptr("/subscriptions/fa5fc227-a624-475e-b696-cdd604c735bc/resourceGroups/res9871/providers/Microsoft.Storage/storageAccounts/sto9871"), + // AppConfigurationResourceID: to.Ptr("/subscriptions/fa5fc227-a624-475e-b696-cdd604c735bc/resourceGroups/res9871/providers/Microsoft.AppConfiguration/configurationStores/appconfig9871"), + // Endpoint: to.Ptr("https://expworkspace7.eastus2.exp.azure.net"), + // }, + // Identity: &armonlineexperimentation.ManagedServiceIdentity{ + // Type: to.Ptr(armonlineexperimentation.ManagedServiceIdentityTypeUserAssigned), + // UserAssignedIdentities: map[string]*armonlineexperimentation.UserAssignedIdentity{ + // "/subscriptions/fa5fc227-a624-475e-b696-cdd604c735bc/resourceGroups/eu2cgroup/providers/Microsoft.ManagedIdentity/userAssignedIdentities/id1": &armonlineexperimentation.UserAssignedIdentity{ + // ClientID: to.Ptr("fbe75b66-01c5-4f87-a220-233af3270436"), + // PrincipalID: to.Ptr("075a0ca6-43f6-4434-9abf-c9b1b79f9219"), + // }, + // "/subscriptions/fa5fc227-a624-475e-b696-cdd604c735bc/resourceGroups/eu2cgroup/providers/Microsoft.ManagedIdentity/userAssignedIdentities/id2": &armonlineexperimentation.UserAssignedIdentity{ + // ClientID: to.Ptr("47429305-c0d3-40bc-8595-61946c4df3dc"), + // PrincipalID: to.Ptr("bf9ebbc8-b92d-4752-8e66-c999000326e0"), + // }, + // }, + // }, + // SKU: &armonlineexperimentation.WorkspaceSKU{ + // Name: to.Ptr(armonlineexperimentation.WorkspaceSKUNameF0), + // Tier: to.Ptr(armonlineexperimentation.WorkspaceSKUTierFree), + // }, + // }, + // } +} + +// Generated from example definition: 2025-05-31-preview/OnlineExperimentWorkspaces_CreateOrUpdateWithEncryption.json +func ExampleOnlineExperimentWorkspacesClient_BeginCreateOrUpdate_createOrUpdateAnOnlineExperimentWorkspaceWithFreeSkuAndCustomerManagedKey() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armonlineexperimentation.NewClientFactory("fa5fc227-a624-475e-b696-cdd604c735bc", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + poller, err := clientFactory.NewOnlineExperimentWorkspacesClient().BeginCreateOrUpdate(ctx, "res9871", "expworkspace7", armonlineexperimentation.OnlineExperimentWorkspace{ + Location: to.Ptr("eastus2"), + Tags: map[string]*string{ + "newKey": to.Ptr("newVal"), + }, + Properties: &armonlineexperimentation.OnlineExperimentWorkspaceProperties{ + LogAnalyticsWorkspaceResourceID: to.Ptr("/subscriptions/fa5fc227-a624-475e-b696-cdd604c735bc/resourceGroups/res9871/providers/Microsoft.OperationalInsights/workspaces/log9871"), + LogsExporterStorageAccountResourceID: to.Ptr("/subscriptions/fa5fc227-a624-475e-b696-cdd604c735bc/resourceGroups/res9871/providers/Microsoft.Storage/storageAccounts/sto9871"), + AppConfigurationResourceID: to.Ptr("/subscriptions/fa5fc227-a624-475e-b696-cdd604c735bc/resourceGroups/res9871/providers/Microsoft.AppConfiguration/configurationStores/appconfig9871"), + Encryption: &armonlineexperimentation.ResourceEncryptionConfiguration{ + CustomerManagedKeyEncryption: &armonlineexperimentation.CustomerManagedKeyEncryption{ + KeyEncryptionKeyIdentity: &armonlineexperimentation.KeyEncryptionKeyIdentity{ + IdentityType: to.Ptr(armonlineexperimentation.KeyEncryptionKeyIdentityTypeUserAssignedIdentity), + UserAssignedIdentityResourceID: to.Ptr("/subscriptions/fa5fc227-a624-475e-b696-cdd604c735bc/resourceGroups/eu2cgroup/providers/Microsoft.ManagedIdentity/userAssignedIdentities/id1"), + }, + KeyEncryptionKeyURL: to.Ptr("https://contosovault.vault.azure.net/keys/contosokek"), + }, + }, + }, + Identity: &armonlineexperimentation.ManagedServiceIdentity{ + Type: to.Ptr(armonlineexperimentation.ManagedServiceIdentityTypeUserAssigned), + UserAssignedIdentities: map[string]*armonlineexperimentation.UserAssignedIdentity{ + "/subscriptions/fa5fc227-a624-475e-b696-cdd604c735bc/resourceGroups/eu2cgroup/providers/Microsoft.ManagedIdentity/userAssignedIdentities/id1": {}, + "/subscriptions/fa5fc227-a624-475e-b696-cdd604c735bc/resourceGroups/eu2cgroup/providers/Microsoft.ManagedIdentity/userAssignedIdentities/id2": {}, + }, + }, + SKU: &armonlineexperimentation.WorkspaceSKU{ + Name: to.Ptr(armonlineexperimentation.WorkspaceSKUNameF0), + }, + }, nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + res, err := poller.PollUntilDone(ctx, nil) + if err != nil { + log.Fatalf("failed to pull the result: %v", err) + } + // You could use response here. We use blank identifier for just demo purposes. + _ = res + // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // res = armonlineexperimentation.OnlineExperimentWorkspacesClientCreateOrUpdateResponse{ + // OnlineExperimentWorkspace: &armonlineexperimentation.OnlineExperimentWorkspace{ + // ID: to.Ptr("/subscriptions/fa5fc227-a624-475e-b696-cdd604c735bc/resourceGroups/res9871/providers/Microsoft.OnlineExperimentation/workspaces/expworkspace7"), + // Name: to.Ptr("expworkspace7"), + // Type: to.Ptr("Microsoft.OnlineExperimentation/workspaces"), + // Location: to.Ptr("eastus2"), + // Tags: map[string]*string{ + // "newKey": to.Ptr("newVal"), + // }, + // Properties: &armonlineexperimentation.OnlineExperimentWorkspaceProperties{ + // WorkspaceID: to.Ptr("02270d43-f68a-401b-b526-86942525c351"), + // ProvisioningState: to.Ptr(armonlineexperimentation.ResourceProvisioningStateSucceeded), + // LogAnalyticsWorkspaceResourceID: to.Ptr("/subscriptions/fa5fc227-a624-475e-b696-cdd604c735bc/resourceGroups/res9871/providers/Microsoft.OperationalInsights/workspaces/log9871"), + // LogsExporterStorageAccountResourceID: to.Ptr("/subscriptions/fa5fc227-a624-475e-b696-cdd604c735bc/resourceGroups/res9871/providers/Microsoft.Storage/storageAccounts/sto9871"), + // AppConfigurationResourceID: to.Ptr("/subscriptions/fa5fc227-a624-475e-b696-cdd604c735bc/resourceGroups/res9871/providers/Microsoft.AppConfiguration/configurationStores/appconfig9871"), + // Encryption: &armonlineexperimentation.ResourceEncryptionConfiguration{ + // CustomerManagedKeyEncryption: &armonlineexperimentation.CustomerManagedKeyEncryption{ + // KeyEncryptionKeyIdentity: &armonlineexperimentation.KeyEncryptionKeyIdentity{ + // IdentityType: to.Ptr(armonlineexperimentation.KeyEncryptionKeyIdentityTypeUserAssignedIdentity), + // UserAssignedIdentityResourceID: to.Ptr("/subscriptions/fa5fc227-a624-475e-b696-cdd604c735bc/resourceGroups/eu2cgroup/providers/Microsoft.ManagedIdentity/userAssignedIdentities/id1"), + // }, + // KeyEncryptionKeyURL: to.Ptr("https://contosovault.vault.azure.net/keys/contosokek"), + // }, + // }, + // Endpoint: to.Ptr("https://expworkspace7.eastus2.exp.azure.net"), + // }, + // Identity: &armonlineexperimentation.ManagedServiceIdentity{ + // Type: to.Ptr(armonlineexperimentation.ManagedServiceIdentityTypeUserAssigned), + // UserAssignedIdentities: map[string]*armonlineexperimentation.UserAssignedIdentity{ + // "/subscriptions/fa5fc227-a624-475e-b696-cdd604c735bc/resourceGroups/eu2cgroup/providers/Microsoft.ManagedIdentity/userAssignedIdentities/id1": &armonlineexperimentation.UserAssignedIdentity{ + // ClientID: to.Ptr("fbe75b66-01c5-4f87-a220-233af3270436"), + // PrincipalID: to.Ptr("075a0ca6-43f6-4434-9abf-c9b1b79f9219"), + // }, + // "/subscriptions/fa5fc227-a624-475e-b696-cdd604c735bc/resourceGroups/eu2cgroup/providers/Microsoft.ManagedIdentity/userAssignedIdentities/id2": &armonlineexperimentation.UserAssignedIdentity{ + // ClientID: to.Ptr("47429305-c0d3-40bc-8595-61946c4df3dc"), + // PrincipalID: to.Ptr("bf9ebbc8-b92d-4752-8e66-c999000326e0"), + // }, + // }, + // }, + // SKU: &armonlineexperimentation.WorkspaceSKU{ + // Name: to.Ptr(armonlineexperimentation.WorkspaceSKUNameF0), + // Tier: to.Ptr(armonlineexperimentation.WorkspaceSKUTierFree), + // }, + // }, + // } +} + +// Generated from example definition: 2025-05-31-preview/OnlineExperimentWorkspaces_Delete.json +func ExampleOnlineExperimentWorkspacesClient_BeginDelete() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armonlineexperimentation.NewClientFactory("fa5fc227-a624-475e-b696-cdd604c735bc", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + poller, err := clientFactory.NewOnlineExperimentWorkspacesClient().BeginDelete(ctx, "res9871", "expworkspace3", nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + _, err = poller.PollUntilDone(ctx, nil) + if err != nil { + log.Fatalf("failed to pull the result: %v", err) + } +} + +// Generated from example definition: 2025-05-31-preview/OnlineExperimentWorkspaces_Get.json +func ExampleOnlineExperimentWorkspacesClient_Get() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armonlineexperimentation.NewClientFactory("fa5fc227-a624-475e-b696-cdd604c735bc", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + res, err := clientFactory.NewOnlineExperimentWorkspacesClient().Get(ctx, "res9871", "expworkspace3", nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + // You could use response here. We use blank identifier for just demo purposes. + _ = res + // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // res = armonlineexperimentation.OnlineExperimentWorkspacesClientGetResponse{ + // OnlineExperimentWorkspace: &armonlineexperimentation.OnlineExperimentWorkspace{ + // ID: to.Ptr("/subscriptions/fa5fc227-a624-475e-b696-cdd604c735bc/resourceGroups/res9871/providers/Microsoft.OnlineExperimentation/workspaces/expworkspace3"), + // Name: to.Ptr("expworkspace3"), + // Type: to.Ptr("Microsoft.OnlineExperimentation/workspaces"), + // Location: to.Ptr("westus2"), + // Properties: &armonlineexperimentation.OnlineExperimentWorkspaceProperties{ + // WorkspaceID: to.Ptr("02270d43-f68a-401b-b526-86942525c350"), + // ProvisioningState: to.Ptr(armonlineexperimentation.ResourceProvisioningStateSucceeded), + // LogAnalyticsWorkspaceResourceID: to.Ptr("/subscriptions/fa5fc227-a624-475e-b696-cdd604c735bc/resourceGroups/res9871/providers/Microsoft.OperationalInsights/workspaces/log9871"), + // LogsExporterStorageAccountResourceID: to.Ptr("/subscriptions/fa5fc227-a624-475e-b696-cdd604c735bc/resourceGroups/res9871/providers/Microsoft.Storage/storageAccounts/sto9871"), + // AppConfigurationResourceID: to.Ptr("/subscriptions/fa5fc227-a624-475e-b696-cdd604c735bc/resourceGroups/res9871/providers/Microsoft.AppConfiguration/configurationStores/appconfig9871"), + // Endpoint: to.Ptr("https://expworkspace3.westus2.exp.azure.net"), + // }, + // Identity: &armonlineexperimentation.ManagedServiceIdentity{ + // Type: to.Ptr(armonlineexperimentation.ManagedServiceIdentityTypeUserAssigned), + // UserAssignedIdentities: map[string]*armonlineexperimentation.UserAssignedIdentity{ + // "/subscriptions/fa5fc227-a624-475e-b696-cdd604c735bc/resourceGroups/eu2cgroup/providers/Microsoft.ManagedIdentity/userAssignedIdentities/id1": &armonlineexperimentation.UserAssignedIdentity{ + // ClientID: to.Ptr("fbe75b66-01c5-4f87-a220-233af3270436"), + // PrincipalID: to.Ptr("075a0ca6-43f6-4434-9abf-c9b1b79f9219"), + // }, + // "/subscriptions/fa5fc227-a624-475e-b696-cdd604c735bc/resourceGroups/eu2cgroup/providers/Microsoft.ManagedIdentity/userAssignedIdentities/id2": &armonlineexperimentation.UserAssignedIdentity{ + // ClientID: to.Ptr("47429305-c0d3-40bc-8595-61946c4df3dc"), + // PrincipalID: to.Ptr("bf9ebbc8-b92d-4752-8e66-c999000326e0"), + // }, + // }, + // }, + // SKU: &armonlineexperimentation.WorkspaceSKU{ + // Name: to.Ptr(armonlineexperimentation.WorkspaceSKUNameF0), + // Tier: to.Ptr(armonlineexperimentation.WorkspaceSKUTierFree), + // }, + // }, + // } +} + +// Generated from example definition: 2025-05-31-preview/OnlineExperimentWorkspaces_ListByResourceGroup.json +func ExampleOnlineExperimentWorkspacesClient_NewListByResourceGroupPager() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armonlineexperimentation.NewClientFactory("fa5fc227-a624-475e-b696-cdd604c735bc", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + pager := clientFactory.NewOnlineExperimentWorkspacesClient().NewListByResourceGroupPager("res9871", nil) + for pager.More() { + page, err := pager.NextPage(ctx) + if err != nil { + log.Fatalf("failed to advance page: %v", err) + } + for _, v := range page.Value { + // You could use page here. We use blank identifier for just demo purposes. + _ = v + } + // If the HTTP response code is 200 as defined in example definition, your page structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // page = armonlineexperimentation.OnlineExperimentWorkspacesClientListByResourceGroupResponse{ + // OnlineExperimentWorkspaceListResult: armonlineexperimentation.OnlineExperimentWorkspaceListResult{ + // Value: []*armonlineexperimentation.OnlineExperimentWorkspace{ + // { + // ID: to.Ptr("/subscriptions/fa5fc227-a624-475e-b696-cdd604c735bc/resourceGroups/res9871/providers/Microsoft.OnlineExperimentation/workspaces/expworkspace3"), + // Name: to.Ptr("expworkspace3"), + // Type: to.Ptr("Microsoft.OnlineExperimentation/workspaces"), + // Location: to.Ptr("westus2"), + // Properties: &armonlineexperimentation.OnlineExperimentWorkspaceProperties{ + // WorkspaceID: to.Ptr("02270d43-f68a-401b-b526-86942525c350"), + // ProvisioningState: to.Ptr(armonlineexperimentation.ResourceProvisioningStateSucceeded), + // LogAnalyticsWorkspaceResourceID: to.Ptr("/subscriptions/fa5fc227-a624-475e-b696-cdd604c735bc/resourceGroups/res9871/providers/Microsoft.OperationalInsights/workspaces/log9871"), + // LogsExporterStorageAccountResourceID: to.Ptr("/subscriptions/fa5fc227-a624-475e-b696-cdd604c735bc/resourceGroups/res9871/providers/Microsoft.Storage/storageAccounts/sto9871"), + // AppConfigurationResourceID: to.Ptr("/subscriptions/fa5fc227-a624-475e-b696-cdd604c735bc/resourceGroups/res9871/providers/Microsoft.AppConfiguration/configurationStores/appconfig9871"), + // Endpoint: to.Ptr("https://expworkspace3.westus2.exp.azure.net"), + // }, + // Identity: &armonlineexperimentation.ManagedServiceIdentity{ + // Type: to.Ptr(armonlineexperimentation.ManagedServiceIdentityTypeUserAssigned), + // UserAssignedIdentities: map[string]*armonlineexperimentation.UserAssignedIdentity{ + // "/subscriptions/fa5fc227-a624-475e-b696-cdd604c735bc/resourceGroups/eu2cgroup/providers/Microsoft.ManagedIdentity/userAssignedIdentities/id1": &armonlineexperimentation.UserAssignedIdentity{ + // ClientID: to.Ptr("fbe75b66-01c5-4f87-a220-233af3270436"), + // PrincipalID: to.Ptr("075a0ca6-43f6-4434-9abf-c9b1b79f9219"), + // }, + // "/subscriptions/fa5fc227-a624-475e-b696-cdd604c735bc/resourceGroups/eu2cgroup/providers/Microsoft.ManagedIdentity/userAssignedIdentities/id2": &armonlineexperimentation.UserAssignedIdentity{ + // ClientID: to.Ptr("47429305-c0d3-40bc-8595-61946c4df3dc"), + // PrincipalID: to.Ptr("bf9ebbc8-b92d-4752-8e66-c999000326e0"), + // }, + // }, + // }, + // SKU: &armonlineexperimentation.WorkspaceSKU{ + // Name: to.Ptr(armonlineexperimentation.WorkspaceSKUNameF0), + // Tier: to.Ptr(armonlineexperimentation.WorkspaceSKUTierFree), + // }, + // }, + // { + // ID: to.Ptr("/subscriptions/fa5fc227-a624-475e-b696-cdd604c735bc/resourceGroups/res9871/providers/Microsoft.OnlineExperimentation/workspaces/expworkspace2"), + // Name: to.Ptr("expworkspace2"), + // Type: to.Ptr("Microsoft.OnlineExperimentation/workspaces"), + // Location: to.Ptr("westus2"), + // Properties: &armonlineexperimentation.OnlineExperimentWorkspaceProperties{ + // WorkspaceID: to.Ptr("02270d43-f68a-401b-b526-86942525c357"), + // ProvisioningState: to.Ptr(armonlineexperimentation.ResourceProvisioningStateSucceeded), + // LogAnalyticsWorkspaceResourceID: to.Ptr("/subscriptions/fa5fc227-a624-475e-b696-cdd604c735bc/resourceGroups/res9871/providers/Microsoft.OperationalInsights/workspaces/log9871"), + // LogsExporterStorageAccountResourceID: to.Ptr("/subscriptions/fa5fc227-a624-475e-b696-cdd604c735bc/resourceGroups/res9871/providers/Microsoft.Storage/storageAccounts/sto9871"), + // AppConfigurationResourceID: to.Ptr("/subscriptions/fa5fc227-a624-475e-b696-cdd604c735bc/resourceGroups/res9871/providers/Microsoft.AppConfiguration/configurationStores/appconfig9871"), + // Endpoint: to.Ptr("https://expworkspace2.westus2.exp.azure.net"), + // }, + // Identity: &armonlineexperimentation.ManagedServiceIdentity{ + // Type: to.Ptr(armonlineexperimentation.ManagedServiceIdentityTypeUserAssigned), + // UserAssignedIdentities: map[string]*armonlineexperimentation.UserAssignedIdentity{ + // "/subscriptions/fa5fc227-a624-475e-b696-cdd604c735bc/resourceGroups/eu2cgroup/providers/Microsoft.ManagedIdentity/userAssignedIdentities/id1": &armonlineexperimentation.UserAssignedIdentity{ + // ClientID: to.Ptr("fbe75b66-01c5-4f87-a220-233af3270436"), + // PrincipalID: to.Ptr("075a0ca6-43f6-4434-9abf-c9b1b79f9219"), + // }, + // "/subscriptions/fa5fc227-a624-475e-b696-cdd604c735bc/resourceGroups/eu2cgroup/providers/Microsoft.ManagedIdentity/userAssignedIdentities/id2": &armonlineexperimentation.UserAssignedIdentity{ + // ClientID: to.Ptr("47429305-c0d3-40bc-8595-61946c4df3dc"), + // PrincipalID: to.Ptr("bf9ebbc8-b92d-4752-8e66-c999000326e0"), + // }, + // }, + // }, + // SKU: &armonlineexperimentation.WorkspaceSKU{ + // Name: to.Ptr(armonlineexperimentation.WorkspaceSKUNameF0), + // Tier: to.Ptr(armonlineexperimentation.WorkspaceSKUTierFree), + // }, + // }, + // }, + // }, + // } + } +} + +// Generated from example definition: 2025-05-31-preview/OnlineExperimentWorkspaces_ListBySubscription.json +func ExampleOnlineExperimentWorkspacesClient_NewListBySubscriptionPager() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armonlineexperimentation.NewClientFactory("fa5fc227-a624-475e-b696-cdd604c735bc", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + pager := clientFactory.NewOnlineExperimentWorkspacesClient().NewListBySubscriptionPager(nil) + for pager.More() { + page, err := pager.NextPage(ctx) + if err != nil { + log.Fatalf("failed to advance page: %v", err) + } + for _, v := range page.Value { + // You could use page here. We use blank identifier for just demo purposes. + _ = v + } + // If the HTTP response code is 200 as defined in example definition, your page structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // page = armonlineexperimentation.OnlineExperimentWorkspacesClientListBySubscriptionResponse{ + // OnlineExperimentWorkspaceListResult: armonlineexperimentation.OnlineExperimentWorkspaceListResult{ + // Value: []*armonlineexperimentation.OnlineExperimentWorkspace{ + // { + // ID: to.Ptr("/subscriptions/fa5fc227-a624-475e-b696-cdd604c735bc/resourceGroups/res9871/providers/Microsoft.OnlineExperimentation/workspaces/expworkspace3"), + // Name: to.Ptr("expworkspace3"), + // Type: to.Ptr("Microsoft.OnlineExperimentation/workspaces"), + // Location: to.Ptr("westus2"), + // Properties: &armonlineexperimentation.OnlineExperimentWorkspaceProperties{ + // WorkspaceID: to.Ptr("02270d43-f68a-401b-b526-86942525c352"), + // ProvisioningState: to.Ptr(armonlineexperimentation.ResourceProvisioningStateSucceeded), + // LogAnalyticsWorkspaceResourceID: to.Ptr("/subscriptions/fa5fc227-a624-475e-b696-cdd604c735bc/resourceGroups/res9871/providers/Microsoft.OperationalInsights/workspaces/log9871"), + // LogsExporterStorageAccountResourceID: to.Ptr("/subscriptions/fa5fc227-a624-475e-b696-cdd604c735bc/resourceGroups/res9871/providers/Microsoft.Storage/storageAccounts/sto9871"), + // AppConfigurationResourceID: to.Ptr("/subscriptions/fa5fc227-a624-475e-b696-cdd604c735bc/resourceGroups/res9871/providers/Microsoft.AppConfiguration/configurationStores/appconfig9871"), + // Endpoint: to.Ptr("https://expworkspace3.westus2.exp.azure.net"), + // }, + // Identity: &armonlineexperimentation.ManagedServiceIdentity{ + // Type: to.Ptr(armonlineexperimentation.ManagedServiceIdentityTypeUserAssigned), + // UserAssignedIdentities: map[string]*armonlineexperimentation.UserAssignedIdentity{ + // "/subscriptions/fa5fc227-a624-475e-b696-cdd604c735bc/resourceGroups/eu2cgroup/providers/Microsoft.ManagedIdentity/userAssignedIdentities/id1": &armonlineexperimentation.UserAssignedIdentity{ + // ClientID: to.Ptr("fbe75b66-01c5-4f87-a220-233af3270436"), + // PrincipalID: to.Ptr("075a0ca6-43f6-4434-9abf-c9b1b79f9219"), + // }, + // "/subscriptions/fa5fc227-a624-475e-b696-cdd604c735bc/resourceGroups/eu2cgroup/providers/Microsoft.ManagedIdentity/userAssignedIdentities/id2": &armonlineexperimentation.UserAssignedIdentity{ + // ClientID: to.Ptr("47429305-c0d3-40bc-8595-61946c4df3dc"), + // PrincipalID: to.Ptr("bf9ebbc8-b92d-4752-8e66-c999000326e0"), + // }, + // }, + // }, + // SKU: &armonlineexperimentation.WorkspaceSKU{ + // Name: to.Ptr(armonlineexperimentation.WorkspaceSKUNameF0), + // Tier: to.Ptr(armonlineexperimentation.WorkspaceSKUTierFree), + // }, + // }, + // { + // ID: to.Ptr("/subscriptions/fa5fc227-a624-475e-b696-cdd604c735bc/resourceGroups/res9871/providers/Microsoft.OnlineExperimentation/workspaces/expworkspace2"), + // Name: to.Ptr("expworkspace2"), + // Type: to.Ptr("Microsoft.OnlineExperimentation/workspaces"), + // Location: to.Ptr("westus2"), + // Properties: &armonlineexperimentation.OnlineExperimentWorkspaceProperties{ + // WorkspaceID: to.Ptr("02270d43-f68a-401b-b526-86942525c353"), + // ProvisioningState: to.Ptr(armonlineexperimentation.ResourceProvisioningStateSucceeded), + // LogAnalyticsWorkspaceResourceID: to.Ptr("/subscriptions/fa5fc227-a624-475e-b696-cdd604c735bc/resourceGroups/res9871/providers/Microsoft.OperationalInsights/workspaces/log9871"), + // LogsExporterStorageAccountResourceID: to.Ptr("/subscriptions/fa5fc227-a624-475e-b696-cdd604c735bc/resourceGroups/res9871/providers/Microsoft.Storage/storageAccounts/sto9871"), + // AppConfigurationResourceID: to.Ptr("/subscriptions/fa5fc227-a624-475e-b696-cdd604c735bc/resourceGroups/res9871/providers/Microsoft.AppConfiguration/configurationStores/appconfig9871"), + // Endpoint: to.Ptr("https://expworkspace2.westus2.exp.azure.net"), + // }, + // Identity: &armonlineexperimentation.ManagedServiceIdentity{ + // Type: to.Ptr(armonlineexperimentation.ManagedServiceIdentityTypeUserAssigned), + // UserAssignedIdentities: map[string]*armonlineexperimentation.UserAssignedIdentity{ + // "/subscriptions/fa5fc227-a624-475e-b696-cdd604c735bc/resourceGroups/eu2cgroup/providers/Microsoft.ManagedIdentity/userAssignedIdentities/id1": &armonlineexperimentation.UserAssignedIdentity{ + // ClientID: to.Ptr("fbe75b66-01c5-4f87-a220-233af3270436"), + // PrincipalID: to.Ptr("075a0ca6-43f6-4434-9abf-c9b1b79f9219"), + // }, + // "/subscriptions/fa5fc227-a624-475e-b696-cdd604c735bc/resourceGroups/eu2cgroup/providers/Microsoft.ManagedIdentity/userAssignedIdentities/id2": &armonlineexperimentation.UserAssignedIdentity{ + // ClientID: to.Ptr("47429305-c0d3-40bc-8595-61946c4df3dc"), + // PrincipalID: to.Ptr("bf9ebbc8-b92d-4752-8e66-c999000326e0"), + // }, + // }, + // }, + // SKU: &armonlineexperimentation.WorkspaceSKU{ + // Name: to.Ptr(armonlineexperimentation.WorkspaceSKUNameF0), + // Tier: to.Ptr(armonlineexperimentation.WorkspaceSKUTierFree), + // }, + // }, + // { + // ID: to.Ptr("/subscriptions/fa5fc227-a624-475e-b696-cdd604c735bc/resourceGroups/res9871/providers/Microsoft.OnlineExperimentation/workspaces/expworkspace4"), + // Name: to.Ptr("expworkspace4"), + // Type: to.Ptr("Microsoft.OnlineExperimentation/workspaces"), + // Location: to.Ptr("westus2"), + // Properties: &armonlineexperimentation.OnlineExperimentWorkspaceProperties{ + // WorkspaceID: to.Ptr("02270d43-f68a-401b-b526-86942525c354"), + // ProvisioningState: to.Ptr(armonlineexperimentation.ResourceProvisioningStateSucceeded), + // LogAnalyticsWorkspaceResourceID: to.Ptr("/subscriptions/fa5fc227-a624-475e-b696-cdd604c735bc/resourceGroups/res9871/providers/Microsoft.OperationalInsights/workspaces/log9871"), + // LogsExporterStorageAccountResourceID: to.Ptr("/subscriptions/fa5fc227-a624-475e-b696-cdd604c735bc/resourceGroups/res9871/providers/Microsoft.Storage/storageAccounts/sto9871"), + // AppConfigurationResourceID: to.Ptr("/subscriptions/fa5fc227-a624-475e-b696-cdd604c735bc/resourceGroups/res9871/providers/Microsoft.AppConfiguration/configurationStores/appconfig9871"), + // Endpoint: to.Ptr("https://expworkspace4.westus2.exp.azure.net"), + // }, + // Identity: &armonlineexperimentation.ManagedServiceIdentity{ + // Type: to.Ptr(armonlineexperimentation.ManagedServiceIdentityTypeUserAssigned), + // UserAssignedIdentities: map[string]*armonlineexperimentation.UserAssignedIdentity{ + // "/subscriptions/fa5fc227-a624-475e-b696-cdd604c735bc/resourceGroups/eu2cgroup/providers/Microsoft.ManagedIdentity/userAssignedIdentities/id1": &armonlineexperimentation.UserAssignedIdentity{ + // ClientID: to.Ptr("fbe75b66-01c5-4f87-a220-233af3270436"), + // PrincipalID: to.Ptr("075a0ca6-43f6-4434-9abf-c9b1b79f9219"), + // }, + // "/subscriptions/fa5fc227-a624-475e-b696-cdd604c735bc/resourceGroups/eu2cgroup/providers/Microsoft.ManagedIdentity/userAssignedIdentities/id2": &armonlineexperimentation.UserAssignedIdentity{ + // ClientID: to.Ptr("47429305-c0d3-40bc-8595-61946c4df3dc"), + // PrincipalID: to.Ptr("bf9ebbc8-b92d-4752-8e66-c999000326e0"), + // }, + // }, + // }, + // SKU: &armonlineexperimentation.WorkspaceSKU{ + // Name: to.Ptr(armonlineexperimentation.WorkspaceSKUNameF0), + // Tier: to.Ptr(armonlineexperimentation.WorkspaceSKUTierFree), + // }, + // }, + // { + // ID: to.Ptr("/subscriptions/fa5fc227-a624-475e-b696-cdd604c735bc/resourceGroups/res9871/providers/Microsoft.OnlineExperimentation/workspaces/expworkspace5"), + // Name: to.Ptr("expworkspace5"), + // Type: to.Ptr("Microsoft.OnlineExperimentation/workspaces"), + // Location: to.Ptr("westus2"), + // Properties: &armonlineexperimentation.OnlineExperimentWorkspaceProperties{ + // WorkspaceID: to.Ptr("02270d43-f68a-401b-b526-86942525c354"), + // ProvisioningState: to.Ptr(armonlineexperimentation.ResourceProvisioningStateSucceeded), + // LogAnalyticsWorkspaceResourceID: to.Ptr("/subscriptions/fa5fc227-a624-475e-b696-cdd604c735bc/resourceGroups/res9871/providers/Microsoft.OperationalInsights/workspaces/log9871"), + // LogsExporterStorageAccountResourceID: to.Ptr("/subscriptions/fa5fc227-a624-475e-b696-cdd604c735bc/resourceGroups/res9871/providers/Microsoft.Storage/storageAccounts/sto9871"), + // AppConfigurationResourceID: to.Ptr("/subscriptions/fa5fc227-a624-475e-b696-cdd604c735bc/resourceGroups/res9871/providers/Microsoft.AppConfiguration/configurationStores/appconfig9871"), + // Endpoint: to.Ptr("https://expworkspace5.westus2.exp.azure.net"), + // }, + // Identity: &armonlineexperimentation.ManagedServiceIdentity{ + // Type: to.Ptr(armonlineexperimentation.ManagedServiceIdentityTypeUserAssigned), + // UserAssignedIdentities: map[string]*armonlineexperimentation.UserAssignedIdentity{ + // "/subscriptions/fa5fc227-a624-475e-b696-cdd604c735bc/resourceGroups/eu2cgroup/providers/Microsoft.ManagedIdentity/userAssignedIdentities/id1": &armonlineexperimentation.UserAssignedIdentity{ + // ClientID: to.Ptr("fbe75b66-01c5-4f87-a220-233af3270436"), + // PrincipalID: to.Ptr("075a0ca6-43f6-4434-9abf-c9b1b79f9219"), + // }, + // "/subscriptions/fa5fc227-a624-475e-b696-cdd604c735bc/resourceGroups/eu2cgroup/providers/Microsoft.ManagedIdentity/userAssignedIdentities/id2": &armonlineexperimentation.UserAssignedIdentity{ + // ClientID: to.Ptr("47429305-c0d3-40bc-8595-61946c4df3dc"), + // PrincipalID: to.Ptr("bf9ebbc8-b92d-4752-8e66-c999000326e0"), + // }, + // }, + // }, + // SKU: &armonlineexperimentation.WorkspaceSKU{ + // Name: to.Ptr(armonlineexperimentation.WorkspaceSKUNameF0), + // Tier: to.Ptr(armonlineexperimentation.WorkspaceSKUTierFree), + // }, + // }, + // }, + // }, + // } + } +} + +// Generated from example definition: 2025-05-31-preview/OnlineExperimentWorkspaces_Update.json +func ExampleOnlineExperimentWorkspacesClient_BeginUpdate_updateAnOnlineExperimentWorkspace() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armonlineexperimentation.NewClientFactory("fa5fc227-a624-475e-b696-cdd604c735bc", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + poller, err := clientFactory.NewOnlineExperimentWorkspacesClient().BeginUpdate(ctx, "res9871", "expworkspace3", armonlineexperimentation.OnlineExperimentWorkspace{ + Tags: map[string]*string{ + "newKey": to.Ptr("newVal"), + }, + Identity: &armonlineexperimentation.ManagedServiceIdentity{ + Type: to.Ptr(armonlineexperimentation.ManagedServiceIdentityTypeUserAssigned), + UserAssignedIdentities: map[string]*armonlineexperimentation.UserAssignedIdentity{ + "/subscriptions/fa5fc227-a624-475e-b696-cdd604c735bc/resourceGroups/eu2cgroup/providers/Microsoft.ManagedIdentity/userAssignedIdentities/id1": {}, + "/subscriptions/fa5fc227-a624-475e-b696-cdd604c735bc/resourceGroups/eu2cgroup/providers/Microsoft.ManagedIdentity/userAssignedIdentities/id2": {}, + }, + }, + }, nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + res, err := poller.PollUntilDone(ctx, nil) + if err != nil { + log.Fatalf("failed to pull the result: %v", err) + } + // You could use response here. We use blank identifier for just demo purposes. + _ = res + // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // res = armonlineexperimentation.OnlineExperimentWorkspacesClientUpdateResponse{ + // OnlineExperimentWorkspace: &armonlineexperimentation.OnlineExperimentWorkspace{ + // ID: to.Ptr("/subscriptions/fa5fc227-a624-475e-b696-cdd604c735bc/resourceGroups/res9871/providers/Microsoft.OnlineExperimentation/workspaces/expworkspace3"), + // Name: to.Ptr("expworkspace3"), + // Type: to.Ptr("Microsoft.OnlineExperimentation/workspaces"), + // Location: to.Ptr("westus2"), + // Tags: map[string]*string{ + // "supportTeam": to.Ptr("someteam@microsoft.com"), + // "newKey": to.Ptr("newVal"), + // }, + // Properties: &armonlineexperimentation.OnlineExperimentWorkspaceProperties{ + // WorkspaceID: to.Ptr("02270d43-f68a-401b-b526-86942525c350"), + // ProvisioningState: to.Ptr(armonlineexperimentation.ResourceProvisioningStateSucceeded), + // LogAnalyticsWorkspaceResourceID: to.Ptr("/subscriptions/fa5fc227-a624-475e-b696-cdd604c735bc/resourceGroups/res9871/providers/Microsoft.OperationalInsights/workspaces/log9871"), + // LogsExporterStorageAccountResourceID: to.Ptr("/subscriptions/fa5fc227-a624-475e-b696-cdd604c735bc/resourceGroups/res9871/providers/Microsoft.Storage/storageAccounts/sto9871"), + // AppConfigurationResourceID: to.Ptr("/subscriptions/fa5fc227-a624-475e-b696-cdd604c735bc/resourceGroups/res9871/providers/Microsoft.AppConfiguration/configurationStores/appconfig9871"), + // Endpoint: to.Ptr("https://expworkspace3.westus2.exp.azure.net"), + // }, + // Identity: &armonlineexperimentation.ManagedServiceIdentity{ + // Type: to.Ptr(armonlineexperimentation.ManagedServiceIdentityTypeUserAssigned), + // UserAssignedIdentities: map[string]*armonlineexperimentation.UserAssignedIdentity{ + // "/subscriptions/fa5fc227-a624-475e-b696-cdd604c735bc/resourceGroups/eu2cgroup/providers/Microsoft.ManagedIdentity/userAssignedIdentities/id1": &armonlineexperimentation.UserAssignedIdentity{ + // ClientID: to.Ptr("fbe75b66-01c5-4f87-a220-233af3270436"), + // PrincipalID: to.Ptr("075a0ca6-43f6-4434-9abf-c9b1b79f9219"), + // }, + // "/subscriptions/fa5fc227-a624-475e-b696-cdd604c735bc/resourceGroups/eu2cgroup/providers/Microsoft.ManagedIdentity/userAssignedIdentities/id2": &armonlineexperimentation.UserAssignedIdentity{ + // ClientID: to.Ptr("47429305-c0d3-40bc-8595-61946c4df3dc"), + // PrincipalID: to.Ptr("bf9ebbc8-b92d-4752-8e66-c999000326e0"), + // }, + // }, + // }, + // SKU: &armonlineexperimentation.WorkspaceSKU{ + // Name: to.Ptr(armonlineexperimentation.WorkspaceSKUNameF0), + // Tier: to.Ptr(armonlineexperimentation.WorkspaceSKUTierFree), + // }, + // }, + // } +} + +// Generated from example definition: 2025-05-31-preview/OnlineExperimentWorkspaces_UpdateWithEncryption.json +func ExampleOnlineExperimentWorkspacesClient_BeginUpdate_updateAnOnlineExperimentWorkspaceWithCustomerManagedEncryptionKey() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armonlineexperimentation.NewClientFactory("fa5fc227-a624-475e-b696-cdd604c735bc", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + poller, err := clientFactory.NewOnlineExperimentWorkspacesClient().BeginUpdate(ctx, "res9871", "expworkspace3", armonlineexperimentation.OnlineExperimentWorkspace{ + Tags: map[string]*string{ + "newKey": to.Ptr("newVal"), + }, + Identity: &armonlineexperimentation.ManagedServiceIdentity{ + Type: to.Ptr(armonlineexperimentation.ManagedServiceIdentityTypeUserAssigned), + UserAssignedIdentities: map[string]*armonlineexperimentation.UserAssignedIdentity{ + "/subscriptions/fa5fc227-a624-475e-b696-cdd604c735bc/resourceGroups/eu2cgroup/providers/Microsoft.ManagedIdentity/userAssignedIdentities/id1": {}, + "/subscriptions/fa5fc227-a624-475e-b696-cdd604c735bc/resourceGroups/eu2cgroup/providers/Microsoft.ManagedIdentity/userAssignedIdentities/id2": {}, + }, + }, + Properties: &armonlineexperimentation.OnlineExperimentWorkspaceProperties{ + LogAnalyticsWorkspaceResourceID: to.Ptr("/subscriptions/fa5fc227-a624-475e-b696-cdd604c735bc/resourceGroups/res9871/providers/Microsoft.OperationalInsights/workspaces/log9871"), + LogsExporterStorageAccountResourceID: to.Ptr("/subscriptions/fa5fc227-a624-475e-b696-cdd604c735bc/resourceGroups/res9871/providers/Microsoft.Storage/storageAccounts/sto9871"), + Encryption: &armonlineexperimentation.ResourceEncryptionConfiguration{ + CustomerManagedKeyEncryption: &armonlineexperimentation.CustomerManagedKeyEncryption{ + KeyEncryptionKeyIdentity: &armonlineexperimentation.KeyEncryptionKeyIdentity{ + IdentityType: to.Ptr(armonlineexperimentation.KeyEncryptionKeyIdentityTypeUserAssignedIdentity), + UserAssignedIdentityResourceID: to.Ptr("/subscriptions/fa5fc227-a624-475e-b696-cdd604c735bc/resourceGroups/eu2cgroup/providers/Microsoft.ManagedIdentity/userAssignedIdentities/id1"), + }, + KeyEncryptionKeyURL: to.Ptr("https://contosovault.vault.azure.net/keys/contosokek"), + }, + }, + }, + }, nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + res, err := poller.PollUntilDone(ctx, nil) + if err != nil { + log.Fatalf("failed to pull the result: %v", err) + } + // You could use response here. We use blank identifier for just demo purposes. + _ = res + // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // res = armonlineexperimentation.OnlineExperimentWorkspacesClientUpdateResponse{ + // OnlineExperimentWorkspace: &armonlineexperimentation.OnlineExperimentWorkspace{ + // ID: to.Ptr("/subscriptions/fa5fc227-a624-475e-b696-cdd604c735bc/resourceGroups/res9871/providers/Microsoft.OnlineExperimentation/workspaces/expworkspace3"), + // Name: to.Ptr("expworkspace3"), + // Type: to.Ptr("Microsoft.OnlineExperimentation/workspaces"), + // Location: to.Ptr("westus2"), + // Tags: map[string]*string{ + // "supportTeam": to.Ptr("someteam@microsoft.com"), + // "newKey": to.Ptr("newVal"), + // }, + // Properties: &armonlineexperimentation.OnlineExperimentWorkspaceProperties{ + // WorkspaceID: to.Ptr("02270d43-f68a-401b-b526-86942525c350"), + // ProvisioningState: to.Ptr(armonlineexperimentation.ResourceProvisioningStateSucceeded), + // LogAnalyticsWorkspaceResourceID: to.Ptr("/subscriptions/fa5fc227-a624-475e-b696-cdd604c735bc/resourceGroups/res9871/providers/Microsoft.OperationalInsights/workspaces/log9871"), + // LogsExporterStorageAccountResourceID: to.Ptr("/subscriptions/fa5fc227-a624-475e-b696-cdd604c735bc/resourceGroups/res9871/providers/Microsoft.Storage/storageAccounts/sto9871"), + // AppConfigurationResourceID: to.Ptr("/subscriptions/fa5fc227-a624-475e-b696-cdd604c735bc/resourceGroups/res9871/providers/Microsoft.AppConfiguration/configurationStores/appconfig9871"), + // Encryption: &armonlineexperimentation.ResourceEncryptionConfiguration{ + // CustomerManagedKeyEncryption: &armonlineexperimentation.CustomerManagedKeyEncryption{ + // KeyEncryptionKeyIdentity: &armonlineexperimentation.KeyEncryptionKeyIdentity{ + // IdentityType: to.Ptr(armonlineexperimentation.KeyEncryptionKeyIdentityTypeUserAssignedIdentity), + // UserAssignedIdentityResourceID: to.Ptr("/subscriptions/fa5fc227-a624-475e-b696-cdd604c735bc/resourceGroups/eu2cgroup/providers/Microsoft.ManagedIdentity/userAssignedIdentities/id1"), + // }, + // KeyEncryptionKeyURL: to.Ptr("https://contosovault.vault.azure.net/keys/contosokek"), + // }, + // }, + // Endpoint: to.Ptr("https://expworkspace3.westus2.exp.azure.net"), + // }, + // Identity: &armonlineexperimentation.ManagedServiceIdentity{ + // Type: to.Ptr(armonlineexperimentation.ManagedServiceIdentityTypeUserAssigned), + // UserAssignedIdentities: map[string]*armonlineexperimentation.UserAssignedIdentity{ + // "/subscriptions/fa5fc227-a624-475e-b696-cdd604c735bc/resourceGroups/eu2cgroup/providers/Microsoft.ManagedIdentity/userAssignedIdentities/id1": &armonlineexperimentation.UserAssignedIdentity{ + // ClientID: to.Ptr("fbe75b66-01c5-4f87-a220-233af3270436"), + // PrincipalID: to.Ptr("075a0ca6-43f6-4434-9abf-c9b1b79f9219"), + // }, + // "/subscriptions/fa5fc227-a624-475e-b696-cdd604c735bc/resourceGroups/eu2cgroup/providers/Microsoft.ManagedIdentity/userAssignedIdentities/id2": &armonlineexperimentation.UserAssignedIdentity{ + // ClientID: to.Ptr("47429305-c0d3-40bc-8595-61946c4df3dc"), + // PrincipalID: to.Ptr("bf9ebbc8-b92d-4752-8e66-c999000326e0"), + // }, + // }, + // }, + // SKU: &armonlineexperimentation.WorkspaceSKU{ + // Name: to.Ptr(armonlineexperimentation.WorkspaceSKUNameF0), + // Tier: to.Ptr(armonlineexperimentation.WorkspaceSKUTierFree), + // }, + // }, + // } +} diff --git a/sdk/resourcemanager/onlineexperimentation/armonlineexperimentation/operations_client.go b/sdk/resourcemanager/onlineexperimentation/armonlineexperimentation/operations_client.go new file mode 100644 index 000000000000..890adbc45beb --- /dev/null +++ b/sdk/resourcemanager/onlineexperimentation/armonlineexperimentation/operations_client.go @@ -0,0 +1,84 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armonlineexperimentation + +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 2025-05-31-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.OnlineExperimentation/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", "2025-05-31-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/onlineexperimentation/armonlineexperimentation/operations_client_example_test.go b/sdk/resourcemanager/onlineexperimentation/armonlineexperimentation/operations_client_example_test.go new file mode 100644 index 000000000000..a5201d7fc68a --- /dev/null +++ b/sdk/resourcemanager/onlineexperimentation/armonlineexperimentation/operations_client_example_test.go @@ -0,0 +1,55 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armonlineexperimentation_test + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azidentity" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/onlineexperimentation/armonlineexperimentation" + "log" +) + +// Generated from example definition: 2025-05-31-preview/OnlineExperimentWorkspaces_OperationsList.json +func ExampleOperationsClient_NewListPager() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armonlineexperimentation.NewClientFactory("", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + pager := clientFactory.NewOperationsClient().NewListPager(nil) + for pager.More() { + page, err := pager.NextPage(ctx) + if err != nil { + log.Fatalf("failed to advance page: %v", err) + } + for _, v := range page.Value { + // You could use page here. We use blank identifier for just demo purposes. + _ = v + } + // If the HTTP response code is 200 as defined in example definition, your page structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // page = armonlineexperimentation.OperationsClientListResponse{ + // OperationListResult: armonlineexperimentation.OperationListResult{ + // Value: []*armonlineexperimentation.Operation{ + // { + // Name: to.Ptr("aaaaaaaaa"), + // IsDataAction: to.Ptr(true), + // Display: &armonlineexperimentation.OperationDisplay{ + // Provider: to.Ptr("aaaaaaaa"), + // Resource: to.Ptr("aaaaaaaaaaaaaaaaa"), + // Operation: to.Ptr("aaaaaaaaaaaaaaaaaaaa"), + // Description: to.Ptr("aaaaaaaaaaaaaaaaaaaa"), + // }, + // Origin: to.Ptr(armonlineexperimentation.OriginUser), + // }, + // }, + // NextLink: to.Ptr("https://management.azure.com/providers/Microsoft.OnlineExperimentation/operations?api-version=2025-05-31-preview&$skiptoken=aaaaaaaaaaaaaaaaaaaaaaaaaaaa"), + // }, + // } + } +} diff --git a/sdk/resourcemanager/onlineexperimentation/armonlineexperimentation/options.go b/sdk/resourcemanager/onlineexperimentation/armonlineexperimentation/options.go new file mode 100644 index 000000000000..043d1d42398d --- /dev/null +++ b/sdk/resourcemanager/onlineexperimentation/armonlineexperimentation/options.go @@ -0,0 +1,49 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armonlineexperimentation + +// OnlineExperimentWorkspacesClientBeginCreateOrUpdateOptions contains the optional parameters for the OnlineExperimentWorkspacesClient.BeginCreateOrUpdate +// method. +type OnlineExperimentWorkspacesClientBeginCreateOrUpdateOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// OnlineExperimentWorkspacesClientBeginDeleteOptions contains the optional parameters for the OnlineExperimentWorkspacesClient.BeginDelete +// method. +type OnlineExperimentWorkspacesClientBeginDeleteOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// OnlineExperimentWorkspacesClientBeginUpdateOptions contains the optional parameters for the OnlineExperimentWorkspacesClient.BeginUpdate +// method. +type OnlineExperimentWorkspacesClientBeginUpdateOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// OnlineExperimentWorkspacesClientGetOptions contains the optional parameters for the OnlineExperimentWorkspacesClient.Get +// method. +type OnlineExperimentWorkspacesClientGetOptions struct { + // placeholder for future optional parameters +} + +// OnlineExperimentWorkspacesClientListByResourceGroupOptions contains the optional parameters for the OnlineExperimentWorkspacesClient.NewListByResourceGroupPager +// method. +type OnlineExperimentWorkspacesClientListByResourceGroupOptions struct { + // placeholder for future optional parameters +} + +// OnlineExperimentWorkspacesClientListBySubscriptionOptions contains the optional parameters for the OnlineExperimentWorkspacesClient.NewListBySubscriptionPager +// method. +type OnlineExperimentWorkspacesClientListBySubscriptionOptions struct { + // placeholder for future optional parameters +} + +// OperationsClientListOptions contains the optional parameters for the OperationsClient.NewListPager method. +type OperationsClientListOptions struct { + // placeholder for future optional parameters +} diff --git a/sdk/resourcemanager/onlineexperimentation/armonlineexperimentation/responses.go b/sdk/resourcemanager/onlineexperimentation/armonlineexperimentation/responses.go new file mode 100644 index 000000000000..fa38c8969264 --- /dev/null +++ b/sdk/resourcemanager/onlineexperimentation/armonlineexperimentation/responses.go @@ -0,0 +1,46 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armonlineexperimentation + +// OnlineExperimentWorkspacesClientCreateOrUpdateResponse contains the response from method OnlineExperimentWorkspacesClient.BeginCreateOrUpdate. +type OnlineExperimentWorkspacesClientCreateOrUpdateResponse struct { + // An online experiment workspace resource. + OnlineExperimentWorkspace +} + +// OnlineExperimentWorkspacesClientDeleteResponse contains the response from method OnlineExperimentWorkspacesClient.BeginDelete. +type OnlineExperimentWorkspacesClientDeleteResponse struct { + // placeholder for future response values +} + +// OnlineExperimentWorkspacesClientGetResponse contains the response from method OnlineExperimentWorkspacesClient.Get. +type OnlineExperimentWorkspacesClientGetResponse struct { + // An online experiment workspace resource. + OnlineExperimentWorkspace +} + +// OnlineExperimentWorkspacesClientListByResourceGroupResponse contains the response from method OnlineExperimentWorkspacesClient.NewListByResourceGroupPager. +type OnlineExperimentWorkspacesClientListByResourceGroupResponse struct { + // The response of a OnlineExperimentWorkspace list operation. + OnlineExperimentWorkspaceListResult +} + +// OnlineExperimentWorkspacesClientListBySubscriptionResponse contains the response from method OnlineExperimentWorkspacesClient.NewListBySubscriptionPager. +type OnlineExperimentWorkspacesClientListBySubscriptionResponse struct { + // The response of a OnlineExperimentWorkspace list operation. + OnlineExperimentWorkspaceListResult +} + +// OnlineExperimentWorkspacesClientUpdateResponse contains the response from method OnlineExperimentWorkspacesClient.BeginUpdate. +type OnlineExperimentWorkspacesClientUpdateResponse struct { + // An online experiment workspace resource. + OnlineExperimentWorkspace +} + +// 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 +} diff --git a/sdk/resourcemanager/onlineexperimentation/armonlineexperimentation/time_rfc3339.go b/sdk/resourcemanager/onlineexperimentation/armonlineexperimentation/time_rfc3339.go new file mode 100644 index 000000000000..701577422960 --- /dev/null +++ b/sdk/resourcemanager/onlineexperimentation/armonlineexperimentation/time_rfc3339.go @@ -0,0 +1,109 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armonlineexperimentation + +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 +} diff --git a/sdk/resourcemanager/onlineexperimentation/armonlineexperimentation/tsp-location.yaml b/sdk/resourcemanager/onlineexperimentation/armonlineexperimentation/tsp-location.yaml new file mode 100644 index 000000000000..8f670628771a --- /dev/null +++ b/sdk/resourcemanager/onlineexperimentation/armonlineexperimentation/tsp-location.yaml @@ -0,0 +1,4 @@ +directory: specification/onlineexperimentation/OnlineExperimentation.Management +commit: 1f578543d267d08febc1bebf4e33ffe14363ddfc +repo: Azure/azure-rest-api-specs +additionalDirectories: diff --git a/sdk/resourcemanager/sitemanager/armsitemanager/CHANGELOG.md b/sdk/resourcemanager/sitemanager/armsitemanager/CHANGELOG.md new file mode 100644 index 000000000000..007c7b687b8a --- /dev/null +++ b/sdk/resourcemanager/sitemanager/armsitemanager/CHANGELOG.md @@ -0,0 +1,8 @@ +# Release History + +## 0.1.0 (2025-04-27) +### Other Changes + +The package of `github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/sitemanager/armsitemanager` 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/sitemanager/armsitemanager/LICENSE.txt b/sdk/resourcemanager/sitemanager/armsitemanager/LICENSE.txt new file mode 100644 index 000000000000..dc0c2ffb3dc1 --- /dev/null +++ b/sdk/resourcemanager/sitemanager/armsitemanager/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/sitemanager/armsitemanager/README.md b/sdk/resourcemanager/sitemanager/armsitemanager/README.md new file mode 100644 index 000000000000..eb53888840b9 --- /dev/null +++ b/sdk/resourcemanager/sitemanager/armsitemanager/README.md @@ -0,0 +1,90 @@ +# Azure Sitemanager Module for Go + +The `armsitemanager` module provides operations for working with Azure Sitemanager. + +[Source code](https://github.com/Azure/azure-sdk-for-go/tree/main/sdk/resourcemanager/sitemanager/armsitemanager) + +# 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 Sitemanager module: + +```sh +go get github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/sitemanager/armsitemanager +``` + +## Authorization + +When creating a client, you will need to provide a credential for authenticating with Azure Sitemanager. 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 Sitemanager 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 := armsitemanager.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 := armsitemanager.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.NewSitesBySubscriptionClient() +``` + +## 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 `Sitemanager` 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/sitemanager/armsitemanager/ci.yml b/sdk/resourcemanager/sitemanager/armsitemanager/ci.yml new file mode 100644 index 000000000000..a680c0b4f1af --- /dev/null +++ b/sdk/resourcemanager/sitemanager/armsitemanager/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/sitemanager/armsitemanager/ + +pr: + branches: + include: + - main + - feature/* + - hotfix/* + - release/* + paths: + include: + - sdk/resourcemanager/sitemanager/armsitemanager/ + +extends: + template: /eng/pipelines/templates/jobs/archetype-sdk-client.yml + parameters: + ServiceDirectory: 'resourcemanager/sitemanager/armsitemanager' diff --git a/sdk/resourcemanager/sitemanager/armsitemanager/client_factory.go b/sdk/resourcemanager/sitemanager/armsitemanager/client_factory.go new file mode 100644 index 000000000000..c32210938fb8 --- /dev/null +++ b/sdk/resourcemanager/sitemanager/armsitemanager/client_factory.go @@ -0,0 +1,49 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armsitemanager + +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 +} + +// NewSitesBySubscriptionClient creates a new instance of SitesBySubscriptionClient. +func (c *ClientFactory) NewSitesBySubscriptionClient() *SitesBySubscriptionClient { + return &SitesBySubscriptionClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewSitesClient creates a new instance of SitesClient. +func (c *ClientFactory) NewSitesClient() *SitesClient { + return &SitesClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} diff --git a/sdk/resourcemanager/sitemanager/armsitemanager/constants.go b/sdk/resourcemanager/sitemanager/armsitemanager/constants.go new file mode 100644 index 000000000000..938b4a1f6098 --- /dev/null +++ b/sdk/resourcemanager/sitemanager/armsitemanager/constants.go @@ -0,0 +1,55 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armsitemanager + +const ( + moduleName = "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/sitemanager/armsitemanager" + moduleVersion = "v0.1.0" +) + +// CreatedByType - The kind of entity that created the resource. +type CreatedByType string + +const ( + // CreatedByTypeApplication - The entity was created by an application. + CreatedByTypeApplication CreatedByType = "Application" + // CreatedByTypeKey - The entity was created by a key. + CreatedByTypeKey CreatedByType = "Key" + // CreatedByTypeManagedIdentity - The entity was created by a managed identity. + CreatedByTypeManagedIdentity CreatedByType = "ManagedIdentity" + // CreatedByTypeUser - The entity was created by a user. + CreatedByTypeUser CreatedByType = "User" +) + +// PossibleCreatedByTypeValues returns the possible values for the CreatedByType const type. +func PossibleCreatedByTypeValues() []CreatedByType { + return []CreatedByType{ + CreatedByTypeApplication, + CreatedByTypeKey, + CreatedByTypeManagedIdentity, + CreatedByTypeUser, + } +} + +// ResourceProvisioningState - The provisioning state of a resource type. +type ResourceProvisioningState string + +const ( + // ResourceProvisioningStateCanceled - Resource creation was canceled. + ResourceProvisioningStateCanceled ResourceProvisioningState = "Canceled" + // ResourceProvisioningStateFailed - Resource creation failed. + ResourceProvisioningStateFailed ResourceProvisioningState = "Failed" + // ResourceProvisioningStateSucceeded - Resource has been created. + ResourceProvisioningStateSucceeded ResourceProvisioningState = "Succeeded" +) + +// PossibleResourceProvisioningStateValues returns the possible values for the ResourceProvisioningState const type. +func PossibleResourceProvisioningStateValues() []ResourceProvisioningState { + return []ResourceProvisioningState{ + ResourceProvisioningStateCanceled, + ResourceProvisioningStateFailed, + ResourceProvisioningStateSucceeded, + } +} diff --git a/sdk/resourcemanager/sitemanager/armsitemanager/fake/internal.go b/sdk/resourcemanager/sitemanager/armsitemanager/fake/internal.go new file mode 100644 index 000000000000..7425b6a669e2 --- /dev/null +++ b/sdk/resourcemanager/sitemanager/armsitemanager/fake/internal.go @@ -0,0 +1,65 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "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 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/sitemanager/armsitemanager/fake/server_factory.go b/sdk/resourcemanager/sitemanager/armsitemanager/fake/server_factory.go new file mode 100644 index 000000000000..b0ca6984dca2 --- /dev/null +++ b/sdk/resourcemanager/sitemanager/armsitemanager/fake/server_factory.go @@ -0,0 +1,81 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "errors" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" + "sync" +) + +// ServerFactory is a fake server for instances of the armsitemanager.ClientFactory type. +type ServerFactory struct { + // SitesBySubscriptionServer contains the fakes for client SitesBySubscriptionClient + SitesBySubscriptionServer SitesBySubscriptionServer + + // SitesServer contains the fakes for client SitesClient + SitesServer SitesServer +} + +// NewServerFactoryTransport creates a new instance of ServerFactoryTransport with the provided implementation. +// The returned ServerFactoryTransport instance is connected to an instance of armsitemanager.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 armsitemanager.ClientFactory to instances of ServerFactory. +// Don't use this type directly, use NewServerFactoryTransport instead. +type ServerFactoryTransport struct { + srv *ServerFactory + trMu sync.Mutex + trSitesBySubscriptionServer *SitesBySubscriptionServerTransport + trSitesServer *SitesServerTransport +} + +// 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 "SitesBySubscriptionClient": + initServer(s, &s.trSitesBySubscriptionServer, func() *SitesBySubscriptionServerTransport { + return NewSitesBySubscriptionServerTransport(&s.srv.SitesBySubscriptionServer) + }) + resp, err = s.trSitesBySubscriptionServer.Do(req) + case "SitesClient": + initServer(s, &s.trSitesServer, func() *SitesServerTransport { return NewSitesServerTransport(&s.srv.SitesServer) }) + resp, err = s.trSitesServer.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/sitemanager/armsitemanager/fake/sites_server.go b/sdk/resourcemanager/sitemanager/armsitemanager/fake/sites_server.go new file mode 100644 index 000000000000..d76902de37a3 --- /dev/null +++ b/sdk/resourcemanager/sitemanager/armsitemanager/fake/sites_server.go @@ -0,0 +1,307 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/sitemanager/armsitemanager" + "net/http" + "net/url" + "regexp" +) + +// SitesServer is a fake server for instances of the armsitemanager.SitesClient type. +type SitesServer struct { + // BeginCreateOrUpdate is the fake for method SitesClient.BeginCreateOrUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + BeginCreateOrUpdate func(ctx context.Context, resourceGroupName string, siteName string, resource armsitemanager.Site, options *armsitemanager.SitesClientBeginCreateOrUpdateOptions) (resp azfake.PollerResponder[armsitemanager.SitesClientCreateOrUpdateResponse], errResp azfake.ErrorResponder) + + // Delete is the fake for method SitesClient.Delete + // HTTP status codes to indicate success: http.StatusOK, http.StatusNoContent + Delete func(ctx context.Context, resourceGroupName string, siteName string, options *armsitemanager.SitesClientDeleteOptions) (resp azfake.Responder[armsitemanager.SitesClientDeleteResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method SitesClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceGroupName string, siteName string, options *armsitemanager.SitesClientGetOptions) (resp azfake.Responder[armsitemanager.SitesClientGetResponse], errResp azfake.ErrorResponder) + + // NewListByResourceGroupPager is the fake for method SitesClient.NewListByResourceGroupPager + // HTTP status codes to indicate success: http.StatusOK + NewListByResourceGroupPager func(resourceGroupName string, options *armsitemanager.SitesClientListByResourceGroupOptions) (resp azfake.PagerResponder[armsitemanager.SitesClientListByResourceGroupResponse]) + + // Update is the fake for method SitesClient.Update + // HTTP status codes to indicate success: http.StatusOK + Update func(ctx context.Context, resourceGroupName string, siteName string, properties armsitemanager.SiteUpdate, options *armsitemanager.SitesClientUpdateOptions) (resp azfake.Responder[armsitemanager.SitesClientUpdateResponse], errResp azfake.ErrorResponder) +} + +// NewSitesServerTransport creates a new instance of SitesServerTransport with the provided implementation. +// The returned SitesServerTransport instance is connected to an instance of armsitemanager.SitesClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewSitesServerTransport(srv *SitesServer) *SitesServerTransport { + return &SitesServerTransport{ + srv: srv, + beginCreateOrUpdate: newTracker[azfake.PollerResponder[armsitemanager.SitesClientCreateOrUpdateResponse]](), + newListByResourceGroupPager: newTracker[azfake.PagerResponder[armsitemanager.SitesClientListByResourceGroupResponse]](), + } +} + +// SitesServerTransport connects instances of armsitemanager.SitesClient to instances of SitesServer. +// Don't use this type directly, use NewSitesServerTransport instead. +type SitesServerTransport struct { + srv *SitesServer + beginCreateOrUpdate *tracker[azfake.PollerResponder[armsitemanager.SitesClientCreateOrUpdateResponse]] + newListByResourceGroupPager *tracker[azfake.PagerResponder[armsitemanager.SitesClientListByResourceGroupResponse]] +} + +// Do implements the policy.Transporter interface for SitesServerTransport. +func (s *SitesServerTransport) 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 *SitesServerTransport) 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 sitesServerTransportInterceptor != nil { + res.resp, res.err, intercepted = sitesServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "SitesClient.BeginCreateOrUpdate": + res.resp, res.err = s.dispatchBeginCreateOrUpdate(req) + case "SitesClient.Delete": + res.resp, res.err = s.dispatchDelete(req) + case "SitesClient.Get": + res.resp, res.err = s.dispatchGet(req) + case "SitesClient.NewListByResourceGroupPager": + res.resp, res.err = s.dispatchNewListByResourceGroupPager(req) + case "SitesClient.Update": + res.resp, res.err = s.dispatchUpdate(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 *SitesServerTransport) dispatchBeginCreateOrUpdate(req *http.Request) (*http.Response, error) { + if s.srv.BeginCreateOrUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginCreateOrUpdate not implemented")} + } + beginCreateOrUpdate := s.beginCreateOrUpdate.get(req) + if beginCreateOrUpdate == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Edge/sites/(?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[armsitemanager.Site](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + siteNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("siteName")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.BeginCreateOrUpdate(req.Context(), resourceGroupNameParam, siteNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginCreateOrUpdate = &respr + s.beginCreateOrUpdate.add(req, beginCreateOrUpdate) + } + + resp, err := server.PollerResponderNext(beginCreateOrUpdate, req) + if err != nil { + return nil, err + } + + if !contains([]int{http.StatusOK, http.StatusCreated}, resp.StatusCode) { + s.beginCreateOrUpdate.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", resp.StatusCode)} + } + if !server.PollerResponderMore(beginCreateOrUpdate) { + s.beginCreateOrUpdate.remove(req) + } + + return resp, nil +} + +func (s *SitesServerTransport) 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\.Edge/sites/(?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 + } + siteNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("siteName")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.Delete(req.Context(), resourceGroupNameParam, siteNameParam, 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 *SitesServerTransport) 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\.Edge/sites/(?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 + } + siteNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("siteName")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.Get(req.Context(), resourceGroupNameParam, siteNameParam, 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).Site, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SitesServerTransport) dispatchNewListByResourceGroupPager(req *http.Request) (*http.Response, error) { + if s.srv.NewListByResourceGroupPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListByResourceGroupPager not implemented")} + } + newListByResourceGroupPager := s.newListByResourceGroupPager.get(req) + if newListByResourceGroupPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Edge/sites` + 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 := s.srv.NewListByResourceGroupPager(resourceGroupNameParam, nil) + newListByResourceGroupPager = &resp + s.newListByResourceGroupPager.add(req, newListByResourceGroupPager) + server.PagerResponderInjectNextLinks(newListByResourceGroupPager, req, func(page *armsitemanager.SitesClientListByResourceGroupResponse, 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) { + s.newListByResourceGroupPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListByResourceGroupPager) { + s.newListByResourceGroupPager.remove(req) + } + return resp, nil +} + +func (s *SitesServerTransport) dispatchUpdate(req *http.Request) (*http.Response, error) { + if s.srv.Update == nil { + return nil, &nonRetriableError{errors.New("fake for method Update not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Edge/sites/(?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[armsitemanager.SiteUpdate](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + siteNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("siteName")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.Update(req.Context(), resourceGroupNameParam, siteNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Site, req) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to SitesServerTransport +var sitesServerTransportInterceptor 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/sitemanager/armsitemanager/fake/sitesbysubscription_server.go b/sdk/resourcemanager/sitemanager/armsitemanager/fake/sitesbysubscription_server.go new file mode 100644 index 000000000000..4b36c82422df --- /dev/null +++ b/sdk/resourcemanager/sitemanager/armsitemanager/fake/sitesbysubscription_server.go @@ -0,0 +1,287 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/sitemanager/armsitemanager" + "net/http" + "net/url" + "regexp" +) + +// SitesBySubscriptionServer is a fake server for instances of the armsitemanager.SitesBySubscriptionClient type. +type SitesBySubscriptionServer struct { + // BeginCreateOrUpdate is the fake for method SitesBySubscriptionClient.BeginCreateOrUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + BeginCreateOrUpdate func(ctx context.Context, siteName string, resource armsitemanager.Site, options *armsitemanager.SitesBySubscriptionClientBeginCreateOrUpdateOptions) (resp azfake.PollerResponder[armsitemanager.SitesBySubscriptionClientCreateOrUpdateResponse], errResp azfake.ErrorResponder) + + // Delete is the fake for method SitesBySubscriptionClient.Delete + // HTTP status codes to indicate success: http.StatusOK, http.StatusNoContent + Delete func(ctx context.Context, siteName string, options *armsitemanager.SitesBySubscriptionClientDeleteOptions) (resp azfake.Responder[armsitemanager.SitesBySubscriptionClientDeleteResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method SitesBySubscriptionClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, siteName string, options *armsitemanager.SitesBySubscriptionClientGetOptions) (resp azfake.Responder[armsitemanager.SitesBySubscriptionClientGetResponse], errResp azfake.ErrorResponder) + + // NewListPager is the fake for method SitesBySubscriptionClient.NewListPager + // HTTP status codes to indicate success: http.StatusOK + NewListPager func(options *armsitemanager.SitesBySubscriptionClientListOptions) (resp azfake.PagerResponder[armsitemanager.SitesBySubscriptionClientListResponse]) + + // Update is the fake for method SitesBySubscriptionClient.Update + // HTTP status codes to indicate success: http.StatusOK + Update func(ctx context.Context, siteName string, properties armsitemanager.SiteUpdate, options *armsitemanager.SitesBySubscriptionClientUpdateOptions) (resp azfake.Responder[armsitemanager.SitesBySubscriptionClientUpdateResponse], errResp azfake.ErrorResponder) +} + +// NewSitesBySubscriptionServerTransport creates a new instance of SitesBySubscriptionServerTransport with the provided implementation. +// The returned SitesBySubscriptionServerTransport instance is connected to an instance of armsitemanager.SitesBySubscriptionClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewSitesBySubscriptionServerTransport(srv *SitesBySubscriptionServer) *SitesBySubscriptionServerTransport { + return &SitesBySubscriptionServerTransport{ + srv: srv, + beginCreateOrUpdate: newTracker[azfake.PollerResponder[armsitemanager.SitesBySubscriptionClientCreateOrUpdateResponse]](), + newListPager: newTracker[azfake.PagerResponder[armsitemanager.SitesBySubscriptionClientListResponse]](), + } +} + +// SitesBySubscriptionServerTransport connects instances of armsitemanager.SitesBySubscriptionClient to instances of SitesBySubscriptionServer. +// Don't use this type directly, use NewSitesBySubscriptionServerTransport instead. +type SitesBySubscriptionServerTransport struct { + srv *SitesBySubscriptionServer + beginCreateOrUpdate *tracker[azfake.PollerResponder[armsitemanager.SitesBySubscriptionClientCreateOrUpdateResponse]] + newListPager *tracker[azfake.PagerResponder[armsitemanager.SitesBySubscriptionClientListResponse]] +} + +// Do implements the policy.Transporter interface for SitesBySubscriptionServerTransport. +func (s *SitesBySubscriptionServerTransport) 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 *SitesBySubscriptionServerTransport) 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 sitesBySubscriptionServerTransportInterceptor != nil { + res.resp, res.err, intercepted = sitesBySubscriptionServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "SitesBySubscriptionClient.BeginCreateOrUpdate": + res.resp, res.err = s.dispatchBeginCreateOrUpdate(req) + case "SitesBySubscriptionClient.Delete": + res.resp, res.err = s.dispatchDelete(req) + case "SitesBySubscriptionClient.Get": + res.resp, res.err = s.dispatchGet(req) + case "SitesBySubscriptionClient.NewListPager": + res.resp, res.err = s.dispatchNewListPager(req) + case "SitesBySubscriptionClient.Update": + res.resp, res.err = s.dispatchUpdate(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 *SitesBySubscriptionServerTransport) dispatchBeginCreateOrUpdate(req *http.Request) (*http.Response, error) { + if s.srv.BeginCreateOrUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginCreateOrUpdate not implemented")} + } + beginCreateOrUpdate := s.beginCreateOrUpdate.get(req) + if beginCreateOrUpdate == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Edge/sites/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if matches == nil || len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armsitemanager.Site](req) + if err != nil { + return nil, err + } + siteNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("siteName")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.BeginCreateOrUpdate(req.Context(), siteNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginCreateOrUpdate = &respr + s.beginCreateOrUpdate.add(req, beginCreateOrUpdate) + } + + resp, err := server.PollerResponderNext(beginCreateOrUpdate, req) + if err != nil { + return nil, err + } + + if !contains([]int{http.StatusOK, http.StatusCreated}, resp.StatusCode) { + s.beginCreateOrUpdate.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", resp.StatusCode)} + } + if !server.PollerResponderMore(beginCreateOrUpdate) { + s.beginCreateOrUpdate.remove(req) + } + + return resp, nil +} + +func (s *SitesBySubscriptionServerTransport) 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~%@]+)/providers/Microsoft\.Edge/sites/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if matches == nil || len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + siteNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("siteName")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.Delete(req.Context(), siteNameParam, 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 *SitesBySubscriptionServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if s.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Edge/sites/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if matches == nil || len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + siteNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("siteName")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.Get(req.Context(), siteNameParam, 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).Site, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SitesBySubscriptionServerTransport) dispatchNewListPager(req *http.Request) (*http.Response, error) { + if s.srv.NewListPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListPager not implemented")} + } + newListPager := s.newListPager.get(req) + if newListPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Edge/sites` + 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 := s.srv.NewListPager(nil) + newListPager = &resp + s.newListPager.add(req, newListPager) + server.PagerResponderInjectNextLinks(newListPager, req, func(page *armsitemanager.SitesBySubscriptionClientListResponse, 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) { + s.newListPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListPager) { + s.newListPager.remove(req) + } + return resp, nil +} + +func (s *SitesBySubscriptionServerTransport) dispatchUpdate(req *http.Request) (*http.Response, error) { + if s.srv.Update == nil { + return nil, &nonRetriableError{errors.New("fake for method Update not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Edge/sites/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if matches == nil || len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armsitemanager.SiteUpdate](req) + if err != nil { + return nil, err + } + siteNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("siteName")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.Update(req.Context(), siteNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Site, req) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to SitesBySubscriptionServerTransport +var sitesBySubscriptionServerTransportInterceptor 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/sitemanager/armsitemanager/fake/time_rfc3339.go b/sdk/resourcemanager/sitemanager/armsitemanager/fake/time_rfc3339.go new file mode 100644 index 000000000000..87ee11e83b32 --- /dev/null +++ b/sdk/resourcemanager/sitemanager/armsitemanager/fake/time_rfc3339.go @@ -0,0 +1,109 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "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 +} diff --git a/sdk/resourcemanager/sitemanager/armsitemanager/go.mod b/sdk/resourcemanager/sitemanager/armsitemanager/go.mod new file mode 100644 index 000000000000..f80d019aca96 --- /dev/null +++ b/sdk/resourcemanager/sitemanager/armsitemanager/go.mod @@ -0,0 +1,23 @@ +module github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/sitemanager/armsitemanager + +go 1.23.0 + +toolchain go1.23.8 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.17.1 + github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.7.0 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.10.0 // indirect + github.com/AzureAD/microsoft-authentication-library-for-go v1.2.2 // indirect + github.com/golang-jwt/jwt/v5 v5.2.1 // indirect + github.com/google/uuid v1.6.0 // indirect + github.com/kylelemons/godebug v1.1.0 // indirect + github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c // indirect + golang.org/x/crypto v0.36.0 // indirect + golang.org/x/net v0.37.0 // indirect + golang.org/x/sys v0.31.0 // indirect + golang.org/x/text v0.23.0 // indirect +) diff --git a/sdk/resourcemanager/sitemanager/armsitemanager/go.sum b/sdk/resourcemanager/sitemanager/armsitemanager/go.sum new file mode 100644 index 000000000000..1f92486fbbcf --- /dev/null +++ b/sdk/resourcemanager/sitemanager/armsitemanager/go.sum @@ -0,0 +1,33 @@ +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/azidentity v1.7.0 h1:tfLQ34V6F7tVSwoTf/4lH5sE0o6eCJuNDTmH09nDpbc= +github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.7.0/go.mod h1:9kIvujWAA58nmPmWB1m23fyWic1kYZMxD9CxaWn4Qpg= +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/AzureAD/microsoft-authentication-library-for-go v1.2.2 h1:XHOnouVk1mxXfQidrMEnLlPk9UMeRtyBTnEFtxkV0kU= +github.com/AzureAD/microsoft-authentication-library-for-go v1.2.2/go.mod h1:wP83P5OoQ5p6ip3ScPr0BAq0BvuPAvacpEuSzyouqAI= +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/golang-jwt/jwt/v5 v5.2.1 h1:OuVbFODueb089Lh128TAcimifWaLhJwVflnrgM17wHk= +github.com/golang-jwt/jwt/v5 v5.2.1/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk= +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc= +github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= +github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c h1:+mdjkGKdHQG3305AYmdv1U2eRNDiU2ErMBj1gwrq8eQ= +github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c/go.mod h1:7rwL4CYBLnjLxUqIJNnCWiEdr3bn6IUYi15bNlnbCCU= +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/crypto v0.36.0 h1:AnAEvhDddvBdpY+uR+MyHmuZzzNqXSe/GvuDeob5L34= +golang.org/x/crypto v0.36.0/go.mod h1:Y4J0ReaxCR1IMaabaSMugxJES1EpwhBHhv2bDHklZvc= +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/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.31.0 h1:ioabZlmFYtWhL+TRYpcnNlLwhyxaM9kWTDEmfnprqik= +golang.org/x/sys v0.31.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= +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/sitemanager/armsitemanager/models.go b/sdk/resourcemanager/sitemanager/armsitemanager/models.go new file mode 100644 index 000000000000..c766ac6d29a2 --- /dev/null +++ b/sdk/resourcemanager/sitemanager/armsitemanager/models.go @@ -0,0 +1,88 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armsitemanager + +import "time" + +// Site as ARM Resource +type Site struct { + // The resource-specific properties for this resource. + Properties *SiteProperties + + // READ-ONLY; Name of Site resource + Name *string + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *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 +} + +// SiteListResult - The response of a Site list operation. +type SiteListResult struct { + // REQUIRED; The Site items on this page + Value []*Site + + // The link to the next page of items + NextLink *string +} + +// SiteProperties - Site properties +type SiteProperties struct { + // AddressResource ArmId of Site resource + AddressResourceID *string + + // Description of Site resource + Description *string + + // displayName of Site resource + DisplayName *string + + // READ-ONLY; Provisioning state of last operation + ProvisioningState *ResourceProvisioningState +} + +// SiteUpdate - The type used for update operations of the Site. +type SiteUpdate struct { + // The updatable properties of the Site. + Properties *SiteUpdateProperties +} + +// SiteUpdateProperties - The updatable properties of the Site. +type SiteUpdateProperties struct { + // AddressResource ArmId of Site resource + AddressResourceID *string + + // Description of Site resource + Description *string + + // displayName of Site resource + DisplayName *string +} + +// 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 +} diff --git a/sdk/resourcemanager/sitemanager/armsitemanager/models_serde.go b/sdk/resourcemanager/sitemanager/armsitemanager/models_serde.go new file mode 100644 index 000000000000..50edcbd3f177 --- /dev/null +++ b/sdk/resourcemanager/sitemanager/armsitemanager/models_serde.go @@ -0,0 +1,254 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armsitemanager + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "reflect" +) + +// MarshalJSON implements the json.Marshaller interface for type Site. +func (s Site) 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 Site. +func (s *Site) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &s.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &s.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &s.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &s.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &s.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SiteListResult. +func (s SiteListResult) 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 SiteListResult. +func (s *SiteListResult) 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 SiteProperties. +func (s SiteProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "addressResourceId", s.AddressResourceID) + populate(objectMap, "description", s.Description) + populate(objectMap, "displayName", s.DisplayName) + populate(objectMap, "provisioningState", s.ProvisioningState) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SiteProperties. +func (s *SiteProperties) 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 "addressResourceId": + err = unpopulate(val, "AddressResourceID", &s.AddressResourceID) + delete(rawMsg, key) + case "description": + err = unpopulate(val, "Description", &s.Description) + delete(rawMsg, key) + case "displayName": + err = unpopulate(val, "DisplayName", &s.DisplayName) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &s.ProvisioningState) + 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 SiteUpdate. +func (s SiteUpdate) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "properties", s.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SiteUpdate. +func (s *SiteUpdate) 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 "properties": + err = unpopulate(val, "Properties", &s.Properties) + 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 SiteUpdateProperties. +func (s SiteUpdateProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "addressResourceId", s.AddressResourceID) + populate(objectMap, "description", s.Description) + populate(objectMap, "displayName", s.DisplayName) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SiteUpdateProperties. +func (s *SiteUpdateProperties) 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 "addressResourceId": + err = unpopulate(val, "AddressResourceID", &s.AddressResourceID) + delete(rawMsg, key) + case "description": + err = unpopulate(val, "Description", &s.Description) + delete(rawMsg, key) + case "displayName": + err = unpopulate(val, "DisplayName", &s.DisplayName) + 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 +} + +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/sitemanager/armsitemanager/options.go b/sdk/resourcemanager/sitemanager/armsitemanager/options.go new file mode 100644 index 000000000000..c798e4b73cb5 --- /dev/null +++ b/sdk/resourcemanager/sitemanager/armsitemanager/options.go @@ -0,0 +1,59 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armsitemanager + +// SitesBySubscriptionClientBeginCreateOrUpdateOptions contains the optional parameters for the SitesBySubscriptionClient.BeginCreateOrUpdate +// method. +type SitesBySubscriptionClientBeginCreateOrUpdateOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// SitesBySubscriptionClientDeleteOptions contains the optional parameters for the SitesBySubscriptionClient.Delete method. +type SitesBySubscriptionClientDeleteOptions struct { + // placeholder for future optional parameters +} + +// SitesBySubscriptionClientGetOptions contains the optional parameters for the SitesBySubscriptionClient.Get method. +type SitesBySubscriptionClientGetOptions struct { + // placeholder for future optional parameters +} + +// SitesBySubscriptionClientListOptions contains the optional parameters for the SitesBySubscriptionClient.NewListPager method. +type SitesBySubscriptionClientListOptions struct { + // placeholder for future optional parameters +} + +// SitesBySubscriptionClientUpdateOptions contains the optional parameters for the SitesBySubscriptionClient.Update method. +type SitesBySubscriptionClientUpdateOptions struct { + // placeholder for future optional parameters +} + +// SitesClientBeginCreateOrUpdateOptions contains the optional parameters for the SitesClient.BeginCreateOrUpdate method. +type SitesClientBeginCreateOrUpdateOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// SitesClientDeleteOptions contains the optional parameters for the SitesClient.Delete method. +type SitesClientDeleteOptions struct { + // placeholder for future optional parameters +} + +// SitesClientGetOptions contains the optional parameters for the SitesClient.Get method. +type SitesClientGetOptions struct { + // placeholder for future optional parameters +} + +// SitesClientListByResourceGroupOptions contains the optional parameters for the SitesClient.NewListByResourceGroupPager +// method. +type SitesClientListByResourceGroupOptions struct { + // placeholder for future optional parameters +} + +// SitesClientUpdateOptions contains the optional parameters for the SitesClient.Update method. +type SitesClientUpdateOptions struct { + // placeholder for future optional parameters +} diff --git a/sdk/resourcemanager/sitemanager/armsitemanager/responses.go b/sdk/resourcemanager/sitemanager/armsitemanager/responses.go new file mode 100644 index 000000000000..acb8b682c742 --- /dev/null +++ b/sdk/resourcemanager/sitemanager/armsitemanager/responses.go @@ -0,0 +1,63 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armsitemanager + +// SitesBySubscriptionClientCreateOrUpdateResponse contains the response from method SitesBySubscriptionClient.BeginCreateOrUpdate. +type SitesBySubscriptionClientCreateOrUpdateResponse struct { + // Site as ARM Resource + Site +} + +// SitesBySubscriptionClientDeleteResponse contains the response from method SitesBySubscriptionClient.Delete. +type SitesBySubscriptionClientDeleteResponse struct { + // placeholder for future response values +} + +// SitesBySubscriptionClientGetResponse contains the response from method SitesBySubscriptionClient.Get. +type SitesBySubscriptionClientGetResponse struct { + // Site as ARM Resource + Site +} + +// SitesBySubscriptionClientListResponse contains the response from method SitesBySubscriptionClient.NewListPager. +type SitesBySubscriptionClientListResponse struct { + // The response of a Site list operation. + SiteListResult +} + +// SitesBySubscriptionClientUpdateResponse contains the response from method SitesBySubscriptionClient.Update. +type SitesBySubscriptionClientUpdateResponse struct { + // Site as ARM Resource + Site +} + +// SitesClientCreateOrUpdateResponse contains the response from method SitesClient.BeginCreateOrUpdate. +type SitesClientCreateOrUpdateResponse struct { + // Site as ARM Resource + Site +} + +// SitesClientDeleteResponse contains the response from method SitesClient.Delete. +type SitesClientDeleteResponse struct { + // placeholder for future response values +} + +// SitesClientGetResponse contains the response from method SitesClient.Get. +type SitesClientGetResponse struct { + // Site as ARM Resource + Site +} + +// SitesClientListByResourceGroupResponse contains the response from method SitesClient.NewListByResourceGroupPager. +type SitesClientListByResourceGroupResponse struct { + // The response of a Site list operation. + SiteListResult +} + +// SitesClientUpdateResponse contains the response from method SitesClient.Update. +type SitesClientUpdateResponse struct { + // Site as ARM Resource + Site +} diff --git a/sdk/resourcemanager/sitemanager/armsitemanager/sites_client.go b/sdk/resourcemanager/sitemanager/armsitemanager/sites_client.go new file mode 100644 index 000000000000..49563f0564ce --- /dev/null +++ b/sdk/resourcemanager/sitemanager/armsitemanager/sites_client.go @@ -0,0 +1,368 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armsitemanager + +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" +) + +// SitesClient contains the methods for the Sites group. +// Don't use this type directly, use NewSitesClient() instead. +type SitesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewSitesClient creates a new instance of SitesClient 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 NewSitesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*SitesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &SitesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Create a Site +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-02-01-preview +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - siteName - Name of Site resource +// - resource - Resource create parameters. +// - options - SitesClientBeginCreateOrUpdateOptions contains the optional parameters for the SitesClient.BeginCreateOrUpdate +// method. +func (client *SitesClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, siteName string, resource Site, options *SitesClientBeginCreateOrUpdateOptions) (*runtime.Poller[SitesClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, siteName, resource, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[SitesClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[SitesClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Create a Site +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-02-01-preview +func (client *SitesClient) createOrUpdate(ctx context.Context, resourceGroupName string, siteName string, resource Site, options *SitesClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "SitesClient.BeginCreateOrUpdate" + 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, siteName, 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 +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *SitesClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, siteName string, resource Site, _ *SitesClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Edge/sites/{siteName}" + 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 siteName == "" { + return nil, errors.New("parameter siteName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{siteName}", url.PathEscape(siteName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2024-02-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, resource); err != nil { + return nil, err + } + return req, nil +} + +// Delete - Delete a Site +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-02-01-preview +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - siteName - Name of Site resource +// - options - SitesClientDeleteOptions contains the optional parameters for the SitesClient.Delete method. +func (client *SitesClient) Delete(ctx context.Context, resourceGroupName string, siteName string, options *SitesClientDeleteOptions) (SitesClientDeleteResponse, error) { + var err error + const operationName = "SitesClient.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, siteName, options) + if err != nil { + return SitesClientDeleteResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SitesClientDeleteResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SitesClientDeleteResponse{}, err + } + return SitesClientDeleteResponse{}, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *SitesClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, siteName string, _ *SitesClientDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Edge/sites/{siteName}" + 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 siteName == "" { + return nil, errors.New("parameter siteName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{siteName}", url.PathEscape(siteName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2024-02-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Get a Site +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-02-01-preview +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - siteName - Name of Site resource +// - options - SitesClientGetOptions contains the optional parameters for the SitesClient.Get method. +func (client *SitesClient) Get(ctx context.Context, resourceGroupName string, siteName string, options *SitesClientGetOptions) (SitesClientGetResponse, error) { + var err error + const operationName = "SitesClient.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, siteName, options) + if err != nil { + return SitesClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SitesClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return SitesClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *SitesClient) getCreateRequest(ctx context.Context, resourceGroupName string, siteName string, _ *SitesClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Edge/sites/{siteName}" + 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 siteName == "" { + return nil, errors.New("parameter siteName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{siteName}", url.PathEscape(siteName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2024-02-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 *SitesClient) getHandleResponse(resp *http.Response) (SitesClientGetResponse, error) { + result := SitesClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Site); err != nil { + return SitesClientGetResponse{}, err + } + return result, nil +} + +// NewListByResourceGroupPager - List Site resources by resource group +// +// Generated from API version 2024-02-01-preview +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - options - SitesClientListByResourceGroupOptions contains the optional parameters for the SitesClient.NewListByResourceGroupPager +// method. +func (client *SitesClient) NewListByResourceGroupPager(resourceGroupName string, options *SitesClientListByResourceGroupOptions) *runtime.Pager[SitesClientListByResourceGroupResponse] { + return runtime.NewPager(runtime.PagingHandler[SitesClientListByResourceGroupResponse]{ + More: func(page SitesClientListByResourceGroupResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *SitesClientListByResourceGroupResponse) (SitesClientListByResourceGroupResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "SitesClient.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 SitesClientListByResourceGroupResponse{}, err + } + return client.listByResourceGroupHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByResourceGroupCreateRequest creates the ListByResourceGroup request. +func (client *SitesClient) listByResourceGroupCreateRequest(ctx context.Context, resourceGroupName string, _ *SitesClientListByResourceGroupOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Edge/sites" + 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", "2024-02-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 *SitesClient) listByResourceGroupHandleResponse(resp *http.Response) (SitesClientListByResourceGroupResponse, error) { + result := SitesClientListByResourceGroupResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.SiteListResult); err != nil { + return SitesClientListByResourceGroupResponse{}, err + } + return result, nil +} + +// Update - Update a Site +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-02-01-preview +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - siteName - Name of Site resource +// - properties - The resource properties to be updated. +// - options - SitesClientUpdateOptions contains the optional parameters for the SitesClient.Update method. +func (client *SitesClient) Update(ctx context.Context, resourceGroupName string, siteName string, properties SiteUpdate, options *SitesClientUpdateOptions) (SitesClientUpdateResponse, error) { + var err error + const operationName = "SitesClient.Update" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateCreateRequest(ctx, resourceGroupName, siteName, properties, options) + if err != nil { + return SitesClientUpdateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SitesClientUpdateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return SitesClientUpdateResponse{}, err + } + resp, err := client.updateHandleResponse(httpResp) + return resp, err +} + +// updateCreateRequest creates the Update request. +func (client *SitesClient) updateCreateRequest(ctx context.Context, resourceGroupName string, siteName string, properties SiteUpdate, _ *SitesClientUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Edge/sites/{siteName}" + 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 siteName == "" { + return nil, errors.New("parameter siteName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{siteName}", url.PathEscape(siteName)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2024-02-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, properties); err != nil { + return nil, err + } + return req, nil +} + +// updateHandleResponse handles the Update response. +func (client *SitesClient) updateHandleResponse(resp *http.Response) (SitesClientUpdateResponse, error) { + result := SitesClientUpdateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Site); err != nil { + return SitesClientUpdateResponse{}, err + } + return result, nil +} diff --git a/sdk/resourcemanager/sitemanager/armsitemanager/sites_client_example_test.go b/sdk/resourcemanager/sitemanager/armsitemanager/sites_client_example_test.go new file mode 100644 index 000000000000..fcd9ca928be2 --- /dev/null +++ b/sdk/resourcemanager/sitemanager/armsitemanager/sites_client_example_test.go @@ -0,0 +1,188 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armsitemanager_test + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/Azure/azure-sdk-for-go/sdk/azidentity" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/sitemanager/armsitemanager" + "log" +) + +// Generated from example definition: 2024-02-01-preview/Sites_CreateOrUpdate.json +func ExampleSitesClient_BeginCreateOrUpdate() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armsitemanager.NewClientFactory("0154f7fe-df09-4981-bf82-7ad5c1f596eb", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + poller, err := clientFactory.NewSitesClient().BeginCreateOrUpdate(ctx, "string", "string", armsitemanager.Site{ + Properties: &armsitemanager.SiteProperties{ + DisplayName: to.Ptr("string"), + Description: to.Ptr("string"), + AddressResourceID: to.Ptr("/subscriptions/680d0dad-59aa-4464-3df3-b34b2b42738c/resourceGroups/us-site-rg/providers/Microsoft.EdgeOrder/addresses/12343213"), + }, + }, nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + res, err := poller.PollUntilDone(ctx, nil) + if err != nil { + log.Fatalf("failed to pull the result: %v", err) + } + // You could use response here. We use blank identifier for just demo purposes. + _ = res + // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // res = armsitemanager.SitesClientCreateOrUpdateResponse{ + // Site: &armsitemanager.Site{ + // ID: to.Ptr("/subscriptions/0154f7fe-df09-4981-bf82-7ad5c1f596eb/resourcegroups/EdgeSitesRG/providers/Microsoft.Edge/Sites/BellvueSite"), + // Type: to.Ptr("string"), + // Properties: &armsitemanager.SiteProperties{ + // DisplayName: to.Ptr("string"), + // Description: to.Ptr("string"), + // AddressResourceID: to.Ptr("/subscriptions/680d0dad-59aa-4464-3df3-b34b2b42738c/resourceGroups/us-site-rg/providers/Microsoft.EdgeOrder/addresses/12343213"), + // ProvisioningState: to.Ptr(armsitemanager.ResourceProvisioningStateSucceeded), + // }, + // }, + // } +} + +// Generated from example definition: 2024-02-01-preview/Sites_Delete.json +func ExampleSitesClient_Delete() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armsitemanager.NewClientFactory("0154f7fe-df09-4981-bf82-7ad5c1f596eb", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + res, err := clientFactory.NewSitesClient().Delete(ctx, "string", "string", nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + // You could use response here. We use blank identifier for just demo purposes. + _ = res + // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // res = armsitemanager.SitesClientDeleteResponse{ + // } +} + +// Generated from example definition: 2024-02-01-preview/Sites_Get.json +func ExampleSitesClient_Get() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armsitemanager.NewClientFactory("0154f7fe-df09-4981-bf82-7ad5c1f596eb", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + res, err := clientFactory.NewSitesClient().Get(ctx, "string", "string", nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + // You could use response here. We use blank identifier for just demo purposes. + _ = res + // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // res = armsitemanager.SitesClientGetResponse{ + // Site: &armsitemanager.Site{ + // ID: to.Ptr("/subscriptions/0154f7fe-df09-4981-bf82-7ad5c1f596eb/resourcegroups/EdgeSitesRG/providers/Microsoft.Edge/Sites/BellvueSite"), + // Type: to.Ptr("string"), + // Properties: &armsitemanager.SiteProperties{ + // DisplayName: to.Ptr("string"), + // Description: to.Ptr("string"), + // AddressResourceID: to.Ptr("/subscriptions/11111111-2222-3333-4444-55555555/resourceGroups/us-site-rg/providers/Microsoft.EdgeOrder/addresses/12343213"), + // ProvisioningState: to.Ptr(armsitemanager.ResourceProvisioningStateSucceeded), + // }, + // }, + // } +} + +// Generated from example definition: 2024-02-01-preview/Sites_ListByResourceGroup.json +func ExampleSitesClient_NewListByResourceGroupPager() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armsitemanager.NewClientFactory("0154f7fe-df09-4981-bf82-7ad5c1f596eb", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + pager := clientFactory.NewSitesClient().NewListByResourceGroupPager("string", nil) + for pager.More() { + page, err := pager.NextPage(ctx) + if err != nil { + log.Fatalf("failed to advance page: %v", err) + } + for _, v := range page.Value { + // You could use page here. We use blank identifier for just demo purposes. + _ = v + } + // If the HTTP response code is 200 as defined in example definition, your page structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // page = armsitemanager.SitesClientListByResourceGroupResponse{ + // SiteListResult: armsitemanager.SiteListResult{ + // Value: []*armsitemanager.Site{ + // { + // ID: to.Ptr("/subscriptions/0154f7fe-df09-4981-bf82-7ad5c1f596eb/resourcegroups/EdgeSitesRG/providers/Microsoft.Edge/Sites/BellvueSite"), + // Type: to.Ptr("string"), + // Properties: &armsitemanager.SiteProperties{ + // DisplayName: to.Ptr("string"), + // Description: to.Ptr("string"), + // AddressResourceID: to.Ptr("/subscriptions/11111111-2222-3333-4444-55555555/resourceGroups/us-site-rg/providers/Microsoft.EdgeOrder/addresses/12343213"), + // ProvisioningState: to.Ptr(armsitemanager.ResourceProvisioningStateSucceeded), + // }, + // }, + // }, + // }, + // } + } +} + +// Generated from example definition: 2024-02-01-preview/Sites_Update.json +func ExampleSitesClient_Update() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armsitemanager.NewClientFactory("0154f7fe-df09-4981-bf82-7ad5c1f596eb", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + res, err := clientFactory.NewSitesClient().Update(ctx, "string", "string", armsitemanager.SiteUpdate{ + Properties: &armsitemanager.SiteUpdateProperties{ + DisplayName: to.Ptr("string"), + Description: to.Ptr("string"), + AddressResourceID: to.Ptr("/subscriptions/11111111-2222-3333-4444-55555555/resourceGroups/us-site-rg/providers/Microsoft.EdgeOrder/addresses/12343213"), + }, + }, nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + // You could use response here. We use blank identifier for just demo purposes. + _ = res + // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // res = armsitemanager.SitesClientUpdateResponse{ + // Site: &armsitemanager.Site{ + // ID: to.Ptr("/subscriptions/0154f7fe-df09-4981-bf82-7ad5c1f596eb/resourcegroups/EdgeSitesRG/providers/Microsoft.Edge/Sites/BellvueSite"), + // Type: to.Ptr("string"), + // Properties: &armsitemanager.SiteProperties{ + // DisplayName: to.Ptr("string"), + // Description: to.Ptr("string"), + // AddressResourceID: to.Ptr("/subscriptions/11111111-2222-3333-4444-55555555/resourceGroups/us-site-rg/providers/Microsoft.EdgeOrder/addresses/12343213"), + // ProvisioningState: to.Ptr(armsitemanager.ResourceProvisioningStateSucceeded), + // }, + // }, + // } +} diff --git a/sdk/resourcemanager/sitemanager/armsitemanager/sitesbysubscription_client.go b/sdk/resourcemanager/sitemanager/armsitemanager/sitesbysubscription_client.go new file mode 100644 index 000000000000..47677c70b4c6 --- /dev/null +++ b/sdk/resourcemanager/sitemanager/armsitemanager/sitesbysubscription_client.go @@ -0,0 +1,345 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armsitemanager + +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" +) + +// SitesBySubscriptionClient contains the methods for the SitesBySubscription group. +// Don't use this type directly, use NewSitesBySubscriptionClient() instead. +type SitesBySubscriptionClient struct { + internal *arm.Client + subscriptionID string +} + +// NewSitesBySubscriptionClient creates a new instance of SitesBySubscriptionClient 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 NewSitesBySubscriptionClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*SitesBySubscriptionClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &SitesBySubscriptionClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Create a Site +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-02-01-preview +// - siteName - Name of Site resource +// - resource - Resource create parameters. +// - options - SitesBySubscriptionClientBeginCreateOrUpdateOptions contains the optional parameters for the SitesBySubscriptionClient.BeginCreateOrUpdate +// method. +func (client *SitesBySubscriptionClient) BeginCreateOrUpdate(ctx context.Context, siteName string, resource Site, options *SitesBySubscriptionClientBeginCreateOrUpdateOptions) (*runtime.Poller[SitesBySubscriptionClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, siteName, resource, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[SitesBySubscriptionClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[SitesBySubscriptionClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Create a Site +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-02-01-preview +func (client *SitesBySubscriptionClient) createOrUpdate(ctx context.Context, siteName string, resource Site, options *SitesBySubscriptionClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "SitesBySubscriptionClient.BeginCreateOrUpdate" + 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, siteName, 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 +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *SitesBySubscriptionClient) createOrUpdateCreateRequest(ctx context.Context, siteName string, resource Site, _ *SitesBySubscriptionClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Edge/sites/{siteName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if siteName == "" { + return nil, errors.New("parameter siteName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{siteName}", url.PathEscape(siteName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2024-02-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, resource); err != nil { + return nil, err + } + return req, nil +} + +// Delete - Delete a Site +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-02-01-preview +// - siteName - Name of Site resource +// - options - SitesBySubscriptionClientDeleteOptions contains the optional parameters for the SitesBySubscriptionClient.Delete +// method. +func (client *SitesBySubscriptionClient) Delete(ctx context.Context, siteName string, options *SitesBySubscriptionClientDeleteOptions) (SitesBySubscriptionClientDeleteResponse, error) { + var err error + const operationName = "SitesBySubscriptionClient.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, siteName, options) + if err != nil { + return SitesBySubscriptionClientDeleteResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SitesBySubscriptionClientDeleteResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SitesBySubscriptionClientDeleteResponse{}, err + } + return SitesBySubscriptionClientDeleteResponse{}, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *SitesBySubscriptionClient) deleteCreateRequest(ctx context.Context, siteName string, _ *SitesBySubscriptionClientDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Edge/sites/{siteName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if siteName == "" { + return nil, errors.New("parameter siteName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{siteName}", url.PathEscape(siteName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2024-02-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Get a Site +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-02-01-preview +// - siteName - Name of Site resource +// - options - SitesBySubscriptionClientGetOptions contains the optional parameters for the SitesBySubscriptionClient.Get method. +func (client *SitesBySubscriptionClient) Get(ctx context.Context, siteName string, options *SitesBySubscriptionClientGetOptions) (SitesBySubscriptionClientGetResponse, error) { + var err error + const operationName = "SitesBySubscriptionClient.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, siteName, options) + if err != nil { + return SitesBySubscriptionClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SitesBySubscriptionClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return SitesBySubscriptionClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *SitesBySubscriptionClient) getCreateRequest(ctx context.Context, siteName string, _ *SitesBySubscriptionClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Edge/sites/{siteName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if siteName == "" { + return nil, errors.New("parameter siteName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{siteName}", url.PathEscape(siteName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2024-02-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 *SitesBySubscriptionClient) getHandleResponse(resp *http.Response) (SitesBySubscriptionClientGetResponse, error) { + result := SitesBySubscriptionClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Site); err != nil { + return SitesBySubscriptionClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - List Site resources by subscription ID +// +// Generated from API version 2024-02-01-preview +// - options - SitesBySubscriptionClientListOptions contains the optional parameters for the SitesBySubscriptionClient.NewListPager +// method. +func (client *SitesBySubscriptionClient) NewListPager(options *SitesBySubscriptionClientListOptions) *runtime.Pager[SitesBySubscriptionClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[SitesBySubscriptionClientListResponse]{ + More: func(page SitesBySubscriptionClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *SitesBySubscriptionClientListResponse) (SitesBySubscriptionClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "SitesBySubscriptionClient.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 SitesBySubscriptionClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *SitesBySubscriptionClient) listCreateRequest(ctx context.Context, _ *SitesBySubscriptionClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Edge/sites" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2024-02-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 *SitesBySubscriptionClient) listHandleResponse(resp *http.Response) (SitesBySubscriptionClientListResponse, error) { + result := SitesBySubscriptionClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.SiteListResult); err != nil { + return SitesBySubscriptionClientListResponse{}, err + } + return result, nil +} + +// Update - Update a Site +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-02-01-preview +// - siteName - Name of Site resource +// - properties - The resource properties to be updated. +// - options - SitesBySubscriptionClientUpdateOptions contains the optional parameters for the SitesBySubscriptionClient.Update +// method. +func (client *SitesBySubscriptionClient) Update(ctx context.Context, siteName string, properties SiteUpdate, options *SitesBySubscriptionClientUpdateOptions) (SitesBySubscriptionClientUpdateResponse, error) { + var err error + const operationName = "SitesBySubscriptionClient.Update" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateCreateRequest(ctx, siteName, properties, options) + if err != nil { + return SitesBySubscriptionClientUpdateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SitesBySubscriptionClientUpdateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return SitesBySubscriptionClientUpdateResponse{}, err + } + resp, err := client.updateHandleResponse(httpResp) + return resp, err +} + +// updateCreateRequest creates the Update request. +func (client *SitesBySubscriptionClient) updateCreateRequest(ctx context.Context, siteName string, properties SiteUpdate, _ *SitesBySubscriptionClientUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Edge/sites/{siteName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if siteName == "" { + return nil, errors.New("parameter siteName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{siteName}", url.PathEscape(siteName)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2024-02-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, properties); err != nil { + return nil, err + } + return req, nil +} + +// updateHandleResponse handles the Update response. +func (client *SitesBySubscriptionClient) updateHandleResponse(resp *http.Response) (SitesBySubscriptionClientUpdateResponse, error) { + result := SitesBySubscriptionClientUpdateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Site); err != nil { + return SitesBySubscriptionClientUpdateResponse{}, err + } + return result, nil +} diff --git a/sdk/resourcemanager/sitemanager/armsitemanager/sitesbysubscription_client_example_test.go b/sdk/resourcemanager/sitemanager/armsitemanager/sitesbysubscription_client_example_test.go new file mode 100644 index 000000000000..735649fd32e7 --- /dev/null +++ b/sdk/resourcemanager/sitemanager/armsitemanager/sitesbysubscription_client_example_test.go @@ -0,0 +1,188 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armsitemanager_test + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/Azure/azure-sdk-for-go/sdk/azidentity" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/sitemanager/armsitemanager" + "log" +) + +// Generated from example definition: 2024-02-01-preview/SitesBySubscription_CreateOrUpdate.json +func ExampleSitesBySubscriptionClient_BeginCreateOrUpdate() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armsitemanager.NewClientFactory("0154f7fe-df09-4981-bf82-7ad5c1f596eb", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + poller, err := clientFactory.NewSitesBySubscriptionClient().BeginCreateOrUpdate(ctx, "string", armsitemanager.Site{ + Properties: &armsitemanager.SiteProperties{ + Description: to.Ptr("string"), + AddressResourceID: to.Ptr("/subscriptions/680d0dad-59aa-4464-3df3-b34b2b42738c/resourceGroups/us-site-rg/providers/Microsoft.EdgeOrder/addresses/12343213"), + DisplayName: to.Ptr("string"), + }, + }, nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + res, err := poller.PollUntilDone(ctx, nil) + if err != nil { + log.Fatalf("failed to pull the result: %v", err) + } + // You could use response here. We use blank identifier for just demo purposes. + _ = res + // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // res = armsitemanager.SitesBySubscriptionClientCreateOrUpdateResponse{ + // Site: &armsitemanager.Site{ + // Type: to.Ptr("string"), + // ID: to.Ptr("/subscriptions/0154f7fe-df09-4981-bf82-7ad5c1f596eb/resourcegroups/EdgeSitesRG/providers/Microsoft.Edge/Sites/BellvueSite"), + // Properties: &armsitemanager.SiteProperties{ + // Description: to.Ptr("string"), + // AddressResourceID: to.Ptr("/subscriptions/680d0dad-59aa-4464-3df3-b34b2b42738c/resourceGroups/us-site-rg/providers/Microsoft.EdgeOrder/addresses/12343213"), + // DisplayName: to.Ptr("string"), + // ProvisioningState: to.Ptr(armsitemanager.ResourceProvisioningStateSucceeded), + // }, + // }, + // } +} + +// Generated from example definition: 2024-02-01-preview/SitesBySubscription_Delete.json +func ExampleSitesBySubscriptionClient_Delete() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armsitemanager.NewClientFactory("0154f7fe-df09-4981-bf82-7ad5c1f596eb", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + res, err := clientFactory.NewSitesBySubscriptionClient().Delete(ctx, "string", nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + // You could use response here. We use blank identifier for just demo purposes. + _ = res + // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // res = armsitemanager.SitesBySubscriptionClientDeleteResponse{ + // } +} + +// Generated from example definition: 2024-02-01-preview/SitesBySubscription_Get.json +func ExampleSitesBySubscriptionClient_Get() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armsitemanager.NewClientFactory("0154f7fe-df09-4981-bf82-7ad5c1f596eb", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + res, err := clientFactory.NewSitesBySubscriptionClient().Get(ctx, "string", nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + // You could use response here. We use blank identifier for just demo purposes. + _ = res + // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // res = armsitemanager.SitesBySubscriptionClientGetResponse{ + // Site: &armsitemanager.Site{ + // Type: to.Ptr("string"), + // ID: to.Ptr("/subscriptions/0154f7fe-df09-4981-bf82-7ad5c1f596eb/resourcegroups/EdgeSitesRG/providers/Microsoft.Edge/Sites/BellvueSite"), + // Properties: &armsitemanager.SiteProperties{ + // Description: to.Ptr("string"), + // AddressResourceID: to.Ptr("/subscriptions/0154f7fe-df09-4981-bf82-7ad5c1f596eb/resourceGroups/us-site-rg/providers/Microsoft.EdgeOrder/addresses/12343213"), + // DisplayName: to.Ptr("string"), + // ProvisioningState: to.Ptr(armsitemanager.ResourceProvisioningStateSucceeded), + // }, + // }, + // } +} + +// Generated from example definition: 2024-02-01-preview/SitesBySubscription_List.json +func ExampleSitesBySubscriptionClient_NewListPager() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armsitemanager.NewClientFactory("0154f7fe-df09-4981-bf82-7ad5c1f596eb", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + pager := clientFactory.NewSitesBySubscriptionClient().NewListPager(nil) + for pager.More() { + page, err := pager.NextPage(ctx) + if err != nil { + log.Fatalf("failed to advance page: %v", err) + } + for _, v := range page.Value { + // You could use page here. We use blank identifier for just demo purposes. + _ = v + } + // If the HTTP response code is 200 as defined in example definition, your page structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // page = armsitemanager.SitesBySubscriptionClientListResponse{ + // SiteListResult: armsitemanager.SiteListResult{ + // Value: []*armsitemanager.Site{ + // { + // Type: to.Ptr("string"), + // ID: to.Ptr("/subscriptions/0154f7fe-df09-4981-bf82-7ad5c1f596eb/resourcegroups/EdgeSitesRG/providers/Microsoft.Edge/Sites/BellvueSite"), + // Properties: &armsitemanager.SiteProperties{ + // Description: to.Ptr("string"), + // AddressResourceID: to.Ptr("/subscriptions/0154f7fe-df09-4981-bf82-7ad5c1f596eb/resourceGroups/us-site-rg/providers/Microsoft.EdgeOrder/addresses/12343213"), + // DisplayName: to.Ptr("string"), + // ProvisioningState: to.Ptr(armsitemanager.ResourceProvisioningStateSucceeded), + // }, + // }, + // }, + // }, + // } + } +} + +// Generated from example definition: 2024-02-01-preview/SitesBySubscription_Update.json +func ExampleSitesBySubscriptionClient_Update() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armsitemanager.NewClientFactory("0154f7fe-df09-4981-bf82-7ad5c1f596eb", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + res, err := clientFactory.NewSitesBySubscriptionClient().Update(ctx, "string", armsitemanager.SiteUpdate{ + Properties: &armsitemanager.SiteUpdateProperties{ + Description: to.Ptr("string"), + AddressResourceID: to.Ptr("/subscriptions/0154f7fe-df09-4981-bf82-7ad5c1f596eb/resourceGroups/us-site-rg/providers/Microsoft.EdgeOrder/addresses/12343213"), + DisplayName: to.Ptr("string"), + }, + }, nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + // You could use response here. We use blank identifier for just demo purposes. + _ = res + // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // res = armsitemanager.SitesBySubscriptionClientUpdateResponse{ + // Site: &armsitemanager.Site{ + // Type: to.Ptr("string"), + // ID: to.Ptr("/subscriptions/0154f7fe-df09-4981-bf82-7ad5c1f596eb/resourcegroups/EdgeSitesRG/providers/Microsoft.Edge/Sites/BellvueSite"), + // Properties: &armsitemanager.SiteProperties{ + // Description: to.Ptr("string"), + // AddressResourceID: to.Ptr("/subscriptions/0154f7fe-df09-4981-bf82-7ad5c1f596eb/resourceGroups/us-site-rg/providers/Microsoft.EdgeOrder/addresses/12343213"), + // DisplayName: to.Ptr("string"), + // ProvisioningState: to.Ptr(armsitemanager.ResourceProvisioningStateSucceeded), + // }, + // }, + // } +} diff --git a/sdk/resourcemanager/sitemanager/armsitemanager/time_rfc3339.go b/sdk/resourcemanager/sitemanager/armsitemanager/time_rfc3339.go new file mode 100644 index 000000000000..9bb638248dd2 --- /dev/null +++ b/sdk/resourcemanager/sitemanager/armsitemanager/time_rfc3339.go @@ -0,0 +1,109 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armsitemanager + +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 +} diff --git a/sdk/resourcemanager/sitemanager/armsitemanager/tsp-location.yaml b/sdk/resourcemanager/sitemanager/armsitemanager/tsp-location.yaml new file mode 100644 index 000000000000..08b809fae2ff --- /dev/null +++ b/sdk/resourcemanager/sitemanager/armsitemanager/tsp-location.yaml @@ -0,0 +1,4 @@ +directory: specification/edge/Microsoft.Edge.Sites.Management +commit: 1f578543d267d08febc1bebf4e33ffe14363ddfc +repo: Azure/azure-rest-api-specs +additionalDirectories: diff --git a/sdk/resourcemanager/trustedsigning/armtrustedsigning/CHANGELOG.md b/sdk/resourcemanager/trustedsigning/armtrustedsigning/CHANGELOG.md index 65b66c134a02..11b50a8a023f 100644 --- a/sdk/resourcemanager/trustedsigning/armtrustedsigning/CHANGELOG.md +++ b/sdk/resourcemanager/trustedsigning/armtrustedsigning/CHANGELOG.md @@ -1,5 +1,17 @@ # Release History +## 0.2.0 (2025-04-27) +### Breaking Changes + +- Type of `CodeSigningAccountPatchProperties.SKU` has been changed from `*AccountSKU` to `*AccountSKUPatch` +- Field `City`, `CommonName`, `Country`, `EnhancedKeyUsage`, `Organization`, `OrganizationUnit`, `PostalCode`, `State`, `StreetAddress` of struct `CertificateProfileProperties` has been removed + +### Features Added + +- New struct `AccountSKUPatch` +- New field `EnhancedKeyUsage` in struct `Certificate` + + ## 0.1.0 (2024-09-29) ### Other Changes diff --git a/sdk/resourcemanager/trustedsigning/armtrustedsigning/certificateprofiles_client.go b/sdk/resourcemanager/trustedsigning/armtrustedsigning/certificateprofiles_client.go index 532d09c78819..e434808aae39 100644 --- a/sdk/resourcemanager/trustedsigning/armtrustedsigning/certificateprofiles_client.go +++ b/sdk/resourcemanager/trustedsigning/armtrustedsigning/certificateprofiles_client.go @@ -42,7 +42,7 @@ func NewCertificateProfilesClient(subscriptionID string, credential azcore.Token // BeginCreate - Create a certificate profile. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2024-02-05-preview +// Generated from API version 2024-09-30-preview // - resourceGroupName - The name of the resource group. The name is case insensitive. // - accountName - Trusted Signing account name. // - profileName - Certificate profile name. @@ -70,7 +70,7 @@ func (client *CertificateProfilesClient) BeginCreate(ctx context.Context, resour // Create - Create a certificate profile. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2024-02-05-preview +// Generated from API version 2024-09-30-preview func (client *CertificateProfilesClient) create(ctx context.Context, resourceGroupName string, accountName string, profileName string, resource CertificateProfile, options *CertificateProfilesClientBeginCreateOptions) (*http.Response, error) { var err error const operationName = "CertificateProfilesClient.BeginCreate" @@ -116,7 +116,7 @@ func (client *CertificateProfilesClient) createCreateRequest(ctx context.Context return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2024-02-05-preview") + reqQP.Set("api-version", "2024-09-30-preview") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} req.Raw().Header["Content-Type"] = []string{"application/json"} @@ -129,7 +129,7 @@ func (client *CertificateProfilesClient) createCreateRequest(ctx context.Context // BeginDelete - Delete a certificate profile. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2024-02-05-preview +// Generated from API version 2024-09-30-preview // - resourceGroupName - The name of the resource group. The name is case insensitive. // - accountName - Trusted Signing account name. // - profileName - Certificate profile name. @@ -155,7 +155,7 @@ func (client *CertificateProfilesClient) BeginDelete(ctx context.Context, resour // Delete - Delete a certificate profile. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2024-02-05-preview +// Generated from API version 2024-09-30-preview func (client *CertificateProfilesClient) deleteOperation(ctx context.Context, resourceGroupName string, accountName string, profileName string, options *CertificateProfilesClientBeginDeleteOptions) (*http.Response, error) { var err error const operationName = "CertificateProfilesClient.BeginDelete" @@ -201,7 +201,7 @@ func (client *CertificateProfilesClient) deleteCreateRequest(ctx context.Context return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2024-02-05-preview") + reqQP.Set("api-version", "2024-09-30-preview") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -210,7 +210,7 @@ func (client *CertificateProfilesClient) deleteCreateRequest(ctx context.Context // Get - Get details of a certificate profile. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2024-02-05-preview +// Generated from API version 2024-09-30-preview // - resourceGroupName - The name of the resource group. The name is case insensitive. // - accountName - Trusted Signing account name. // - profileName - Certificate profile name. @@ -261,7 +261,7 @@ func (client *CertificateProfilesClient) getCreateRequest(ctx context.Context, r return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2024-02-05-preview") + reqQP.Set("api-version", "2024-09-30-preview") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -278,7 +278,7 @@ func (client *CertificateProfilesClient) getHandleResponse(resp *http.Response) // NewListByCodeSigningAccountPager - List certificate profiles under a trusted signing account. // -// Generated from API version 2024-02-05-preview +// Generated from API version 2024-09-30-preview // - resourceGroupName - The name of the resource group. The name is case insensitive. // - accountName - Trusted Signing account name. // - options - CertificateProfilesClientListByCodeSigningAccountOptions contains the optional parameters for the CertificateProfilesClient.NewListByCodeSigningAccountPager @@ -326,7 +326,7 @@ func (client *CertificateProfilesClient) listByCodeSigningAccountCreateRequest(c return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2024-02-05-preview") + reqQP.Set("api-version", "2024-09-30-preview") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -344,7 +344,7 @@ func (client *CertificateProfilesClient) listByCodeSigningAccountHandleResponse( // RevokeCertificate - Revoke a certificate under a certificate profile. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2024-02-05-preview +// Generated from API version 2024-09-30-preview // - resourceGroupName - The name of the resource group. The name is case insensitive. // - accountName - Trusted Signing account name. // - profileName - Certificate profile name. @@ -396,7 +396,7 @@ func (client *CertificateProfilesClient) revokeCertificateCreateRequest(ctx cont return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2024-02-05-preview") + reqQP.Set("api-version", "2024-09-30-preview") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} req.Raw().Header["Content-Type"] = []string{"application/json"} diff --git a/sdk/resourcemanager/trustedsigning/armtrustedsigning/certificateprofiles_client_example_test.go b/sdk/resourcemanager/trustedsigning/armtrustedsigning/certificateprofiles_client_example_test.go index 080c1b439988..0a6f5872d918 100644 --- a/sdk/resourcemanager/trustedsigning/armtrustedsigning/certificateprofiles_client_example_test.go +++ b/sdk/resourcemanager/trustedsigning/armtrustedsigning/certificateprofiles_client_example_test.go @@ -13,7 +13,7 @@ import ( "time" ) -// Generated from example definition: 2024-02-05-preview/CertificateProfiles_Create.json +// Generated from example definition: 2024-09-30-preview/CertificateProfiles_Create.json func ExampleCertificateProfilesClient_BeginCreate() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { @@ -52,35 +52,28 @@ func ExampleCertificateProfilesClient_BeginCreate() { // { // CreatedDate: to.Ptr("3/14/2023 5:27:49 PM"), // ExpiryDate: to.Ptr("3/17/2023 5:27:49 PM"), + // EnhancedKeyUsage: to.Ptr("1.3.6.1.4.1.311.yy.xxxxxxxx.xxxxxxxx.xxxxxxxxx.xxxxxxxx"), // SerialNumber: to.Ptr("xxxxxxxxxxxxxxxxxx"), // Status: to.Ptr(armtrustedsigning.CertificateStatusActive), // SubjectName: to.Ptr("CN=Contoso Inc, O=Contoso Inc, L=New York, S=New York, C=US"), // Thumbprint: to.Ptr("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"), // }, // }, - // City: to.Ptr("Dallas"), - // CommonName: to.Ptr("Contoso Inc"), - // Country: to.Ptr("US"), - // EnhancedKeyUsage: to.Ptr("1.3.6.1.4.1.311.yy.xxxxxxxx.xxxxxxxx.xxxxxxxxx.xxxxxxxx"), // IdentityValidationID: to.Ptr("00000000-1234-5678-3333-444444444444"), // IncludeCity: to.Ptr(false), // IncludeCountry: to.Ptr(false), // IncludePostalCode: to.Ptr(true), // IncludeState: to.Ptr(false), // IncludeStreetAddress: to.Ptr(false), - // Organization: to.Ptr("Contoso Inc"), - // PostalCode: to.Ptr("560090"), // ProfileType: to.Ptr(armtrustedsigning.ProfileTypePublicTrust), // ProvisioningState: to.Ptr(armtrustedsigning.ProvisioningStateSucceeded), - // State: to.Ptr("Texas"), // Status: to.Ptr(armtrustedsigning.CertificateProfileStatusActive), - // StreetAddress: to.Ptr("123 Bluebonnet"), // }, // }, // } } -// Generated from example definition: 2024-02-05-preview/CertificateProfiles_Delete.json +// Generated from example definition: 2024-09-30-preview/CertificateProfiles_Delete.json func ExampleCertificateProfilesClient_BeginDelete() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { @@ -101,7 +94,7 @@ func ExampleCertificateProfilesClient_BeginDelete() { } } -// Generated from example definition: 2024-02-05-preview/CertificateProfiles_Get.json +// Generated from example definition: 2024-09-30-preview/CertificateProfiles_Get.json func ExampleCertificateProfilesClient_Get() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { @@ -129,35 +122,28 @@ func ExampleCertificateProfilesClient_Get() { // { // CreatedDate: to.Ptr("3/14/2023 5:27:49 PM"), // ExpiryDate: to.Ptr("3/17/2023 5:27:49 PM"), + // EnhancedKeyUsage: to.Ptr("1.3.6.1.4.1.311.yy.xxxxxxxx.xxxxxxxx.xxxxxxxxx.xxxxxxxx"), // SerialNumber: to.Ptr("xxxxxxxxxxxxxxxxxx"), // Status: to.Ptr(armtrustedsigning.CertificateStatusActive), // SubjectName: to.Ptr("CN=Contoso Inc, O=Contoso Inc, L=New York, S=New York, C=US"), // Thumbprint: to.Ptr("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"), // }, // }, - // City: to.Ptr("Dallas"), - // CommonName: to.Ptr("Contoso Inc"), - // Country: to.Ptr("US"), - // EnhancedKeyUsage: to.Ptr("1.3.6.1.4.1.311.yy.xxxxxxxx.xxxxxxxx.xxxxxxxxx.xxxxxxxx"), // IdentityValidationID: to.Ptr("123456"), // IncludeCity: to.Ptr(false), // IncludeCountry: to.Ptr(false), // IncludePostalCode: to.Ptr(true), // IncludeState: to.Ptr(false), // IncludeStreetAddress: to.Ptr(false), - // Organization: to.Ptr("Contoso Inc"), - // PostalCode: to.Ptr("560090"), // ProfileType: to.Ptr(armtrustedsigning.ProfileTypePublicTrust), // ProvisioningState: to.Ptr(armtrustedsigning.ProvisioningStateSucceeded), - // State: to.Ptr("Texas"), // Status: to.Ptr(armtrustedsigning.CertificateProfileStatusActive), - // StreetAddress: to.Ptr("123 Bluebonnet"), // }, // }, // } } -// Generated from example definition: 2024-02-05-preview/CertificateProfiles_ListByCodeSigningAccount.json +// Generated from example definition: 2024-09-30-preview/CertificateProfiles_ListByCodeSigningAccount.json func ExampleCertificateProfilesClient_NewListByCodeSigningAccountPager() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { @@ -191,29 +177,22 @@ func ExampleCertificateProfilesClient_NewListByCodeSigningAccountPager() { // { // CreatedDate: to.Ptr("3/14/2023 5:27:49 PM"), // ExpiryDate: to.Ptr("3/17/2023 5:27:49 PM"), + // EnhancedKeyUsage: to.Ptr("1.3.6.1.4.1.311.yy.xxxxxxxx.xxxxxxxx.xxxxxxxxx.xxxxxxxx"), // SerialNumber: to.Ptr("xxxxxxxxxxxxxxxxxx"), // Status: to.Ptr(armtrustedsigning.CertificateStatusActive), // SubjectName: to.Ptr("CN=Contoso Inc, O=Contoso Inc, L=New York, S=New York, C=US"), // Thumbprint: to.Ptr("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"), // }, // }, - // City: to.Ptr("Dallas"), - // CommonName: to.Ptr("Microsoft Corporation"), - // Country: to.Ptr("US"), - // EnhancedKeyUsage: to.Ptr("1.3.6.1.4.1.311.yy.xxxxxxxx.xxxxxxxx.xxxxxxxxx.xxxxxxxx"), // IdentityValidationID: to.Ptr("123456"), // IncludeCity: to.Ptr(false), // IncludeCountry: to.Ptr(false), // IncludePostalCode: to.Ptr(true), // IncludeState: to.Ptr(false), // IncludeStreetAddress: to.Ptr(false), - // Organization: to.Ptr("Microsoft Corporation"), - // PostalCode: to.Ptr("560090"), // ProfileType: to.Ptr(armtrustedsigning.ProfileTypePublicTrust), // ProvisioningState: to.Ptr(armtrustedsigning.ProvisioningStateSucceeded), - // State: to.Ptr("Texas"), // Status: to.Ptr(armtrustedsigning.CertificateProfileStatusActive), - // StreetAddress: to.Ptr("123 Bluebonnet"), // }, // }, // }, @@ -222,7 +201,7 @@ func ExampleCertificateProfilesClient_NewListByCodeSigningAccountPager() { } } -// Generated from example definition: 2024-02-05-preview/CertificateProfiles_RevokeCertificate.json +// Generated from example definition: 2024-09-30-preview/CertificateProfiles_RevokeCertificate.json func ExampleCertificateProfilesClient_RevokeCertificate() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { diff --git a/sdk/resourcemanager/trustedsigning/armtrustedsigning/codesigningaccounts_client.go b/sdk/resourcemanager/trustedsigning/armtrustedsigning/codesigningaccounts_client.go index 5d80b7c400f2..fc0c2cd038d0 100644 --- a/sdk/resourcemanager/trustedsigning/armtrustedsigning/codesigningaccounts_client.go +++ b/sdk/resourcemanager/trustedsigning/armtrustedsigning/codesigningaccounts_client.go @@ -42,7 +42,7 @@ func NewCodeSigningAccountsClient(subscriptionID string, credential azcore.Token // CheckNameAvailability - Checks that the trusted signing account name is valid and is not already in use. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2024-02-05-preview +// Generated from API version 2024-09-30-preview // - body - The CheckAvailability request // - options - CodeSigningAccountsClientCheckNameAvailabilityOptions contains the optional parameters for the CodeSigningAccountsClient.CheckNameAvailability // method. @@ -80,7 +80,7 @@ func (client *CodeSigningAccountsClient) checkNameAvailabilityCreateRequest(ctx return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2024-02-05-preview") + reqQP.Set("api-version", "2024-09-30-preview") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} req.Raw().Header["Content-Type"] = []string{"application/json"} @@ -102,7 +102,7 @@ func (client *CodeSigningAccountsClient) checkNameAvailabilityHandleResponse(res // BeginCreate - Create a trusted Signing Account. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2024-02-05-preview +// Generated from API version 2024-09-30-preview // - resourceGroupName - The name of the resource group. The name is case insensitive. // - accountName - Trusted Signing account name. // - resource - Parameters to create the trusted signing account @@ -129,7 +129,7 @@ func (client *CodeSigningAccountsClient) BeginCreate(ctx context.Context, resour // Create - Create a trusted Signing Account. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2024-02-05-preview +// Generated from API version 2024-09-30-preview func (client *CodeSigningAccountsClient) create(ctx context.Context, resourceGroupName string, accountName string, resource CodeSigningAccount, options *CodeSigningAccountsClientBeginCreateOptions) (*http.Response, error) { var err error const operationName = "CodeSigningAccountsClient.BeginCreate" @@ -171,7 +171,7 @@ func (client *CodeSigningAccountsClient) createCreateRequest(ctx context.Context return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2024-02-05-preview") + reqQP.Set("api-version", "2024-09-30-preview") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} req.Raw().Header["Content-Type"] = []string{"application/json"} @@ -184,7 +184,7 @@ func (client *CodeSigningAccountsClient) createCreateRequest(ctx context.Context // BeginDelete - Delete a trusted signing account. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2024-02-05-preview +// Generated from API version 2024-09-30-preview // - resourceGroupName - The name of the resource group. The name is case insensitive. // - accountName - Trusted Signing account name. // - options - CodeSigningAccountsClientBeginDeleteOptions contains the optional parameters for the CodeSigningAccountsClient.BeginDelete @@ -209,7 +209,7 @@ func (client *CodeSigningAccountsClient) BeginDelete(ctx context.Context, resour // Delete - Delete a trusted signing account. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2024-02-05-preview +// Generated from API version 2024-09-30-preview func (client *CodeSigningAccountsClient) deleteOperation(ctx context.Context, resourceGroupName string, accountName string, options *CodeSigningAccountsClientBeginDeleteOptions) (*http.Response, error) { var err error const operationName = "CodeSigningAccountsClient.BeginDelete" @@ -251,7 +251,7 @@ func (client *CodeSigningAccountsClient) deleteCreateRequest(ctx context.Context return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2024-02-05-preview") + reqQP.Set("api-version", "2024-09-30-preview") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -260,7 +260,7 @@ func (client *CodeSigningAccountsClient) deleteCreateRequest(ctx context.Context // Get - Get a trusted Signing Account. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2024-02-05-preview +// Generated from API version 2024-09-30-preview // - resourceGroupName - The name of the resource group. The name is case insensitive. // - accountName - Trusted Signing account name. // - options - CodeSigningAccountsClientGetOptions contains the optional parameters for the CodeSigningAccountsClient.Get method. @@ -306,7 +306,7 @@ func (client *CodeSigningAccountsClient) getCreateRequest(ctx context.Context, r return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2024-02-05-preview") + reqQP.Set("api-version", "2024-09-30-preview") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -323,7 +323,7 @@ func (client *CodeSigningAccountsClient) getHandleResponse(resp *http.Response) // NewListByResourceGroupPager - Lists trusted signing accounts within a resource group. // -// Generated from API version 2024-02-05-preview +// Generated from API version 2024-09-30-preview // - resourceGroupName - The name of the resource group. The name is case insensitive. // - options - CodeSigningAccountsClientListByResourceGroupOptions contains the optional parameters for the CodeSigningAccountsClient.NewListByResourceGroupPager // method. @@ -366,7 +366,7 @@ func (client *CodeSigningAccountsClient) listByResourceGroupCreateRequest(ctx co return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2024-02-05-preview") + reqQP.Set("api-version", "2024-09-30-preview") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -383,7 +383,7 @@ func (client *CodeSigningAccountsClient) listByResourceGroupHandleResponse(resp // NewListBySubscriptionPager - Lists trusted signing accounts within a subscription. // -// Generated from API version 2024-02-05-preview +// Generated from API version 2024-09-30-preview // - options - CodeSigningAccountsClientListBySubscriptionOptions contains the optional parameters for the CodeSigningAccountsClient.NewListBySubscriptionPager // method. func (client *CodeSigningAccountsClient) NewListBySubscriptionPager(options *CodeSigningAccountsClientListBySubscriptionOptions) *runtime.Pager[CodeSigningAccountsClientListBySubscriptionResponse] { @@ -421,7 +421,7 @@ func (client *CodeSigningAccountsClient) listBySubscriptionCreateRequest(ctx con return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2024-02-05-preview") + reqQP.Set("api-version", "2024-09-30-preview") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -439,7 +439,7 @@ func (client *CodeSigningAccountsClient) listBySubscriptionHandleResponse(resp * // BeginUpdate - Update a trusted signing account. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2024-02-05-preview +// Generated from API version 2024-09-30-preview // - resourceGroupName - The name of the resource group. The name is case insensitive. // - accountName - Trusted Signing account name. // - properties - Parameters supplied to update the trusted signing account @@ -465,7 +465,7 @@ func (client *CodeSigningAccountsClient) BeginUpdate(ctx context.Context, resour // Update - Update a trusted signing account. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2024-02-05-preview +// Generated from API version 2024-09-30-preview func (client *CodeSigningAccountsClient) update(ctx context.Context, resourceGroupName string, accountName string, properties CodeSigningAccountPatch, options *CodeSigningAccountsClientBeginUpdateOptions) (*http.Response, error) { var err error const operationName = "CodeSigningAccountsClient.BeginUpdate" @@ -507,7 +507,7 @@ func (client *CodeSigningAccountsClient) updateCreateRequest(ctx context.Context return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2024-02-05-preview") + reqQP.Set("api-version", "2024-09-30-preview") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} req.Raw().Header["Content-Type"] = []string{"application/json"} diff --git a/sdk/resourcemanager/trustedsigning/armtrustedsigning/codesigningaccounts_client_example_test.go b/sdk/resourcemanager/trustedsigning/armtrustedsigning/codesigningaccounts_client_example_test.go index 5d99e26faea0..6b8df0c7182e 100644 --- a/sdk/resourcemanager/trustedsigning/armtrustedsigning/codesigningaccounts_client_example_test.go +++ b/sdk/resourcemanager/trustedsigning/armtrustedsigning/codesigningaccounts_client_example_test.go @@ -12,7 +12,7 @@ import ( "log" ) -// Generated from example definition: 2024-02-05-preview/CodeSigningAccounts_CheckNameAvailability.json +// Generated from example definition: 2024-09-30-preview/CodeSigningAccounts_CheckNameAvailability.json func ExampleCodeSigningAccountsClient_CheckNameAvailability() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { @@ -39,7 +39,7 @@ func ExampleCodeSigningAccountsClient_CheckNameAvailability() { // } } -// Generated from example definition: 2024-02-05-preview/CodeSigningAccounts_Create.json +// Generated from example definition: 2024-09-30-preview/CodeSigningAccounts_Create.json func ExampleCodeSigningAccountsClient_BeginCreate() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { @@ -84,7 +84,7 @@ func ExampleCodeSigningAccountsClient_BeginCreate() { // } } -// Generated from example definition: 2024-02-05-preview/CodeSigningAccounts_Delete.json +// Generated from example definition: 2024-09-30-preview/CodeSigningAccounts_Delete.json func ExampleCodeSigningAccountsClient_BeginDelete() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { @@ -105,7 +105,7 @@ func ExampleCodeSigningAccountsClient_BeginDelete() { } } -// Generated from example definition: 2024-02-05-preview/CodeSigningAccounts_Get.json +// Generated from example definition: 2024-09-30-preview/CodeSigningAccounts_Get.json func ExampleCodeSigningAccountsClient_Get() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { @@ -142,7 +142,7 @@ func ExampleCodeSigningAccountsClient_Get() { // } } -// Generated from example definition: 2024-02-05-preview/CodeSigningAccounts_ListByResourceGroup.json +// Generated from example definition: 2024-09-30-preview/CodeSigningAccounts_ListByResourceGroup.json func ExampleCodeSigningAccountsClient_NewListByResourceGroupPager() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { @@ -188,7 +188,7 @@ func ExampleCodeSigningAccountsClient_NewListByResourceGroupPager() { } } -// Generated from example definition: 2024-02-05-preview/CodeSigningAccounts_ListBySubscription.json +// Generated from example definition: 2024-09-30-preview/CodeSigningAccounts_ListBySubscription.json func ExampleCodeSigningAccountsClient_NewListBySubscriptionPager() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { @@ -234,7 +234,7 @@ func ExampleCodeSigningAccountsClient_NewListBySubscriptionPager() { } } -// Generated from example definition: 2024-02-05-preview/CodeSigningAccounts_Update.json +// Generated from example definition: 2024-09-30-preview/CodeSigningAccounts_Update.json func ExampleCodeSigningAccountsClient_BeginUpdate() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { diff --git a/sdk/resourcemanager/trustedsigning/armtrustedsigning/constants.go b/sdk/resourcemanager/trustedsigning/armtrustedsigning/constants.go index ff6a585fdc9d..f85c071f63ba 100644 --- a/sdk/resourcemanager/trustedsigning/armtrustedsigning/constants.go +++ b/sdk/resourcemanager/trustedsigning/armtrustedsigning/constants.go @@ -6,7 +6,7 @@ package armtrustedsigning const ( moduleName = "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/trustedsigning/armtrustedsigning" - moduleVersion = "v0.1.0" + moduleVersion = "v0.2.0" ) // ActionType - Extensible enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. diff --git a/sdk/resourcemanager/trustedsigning/armtrustedsigning/fake/certificateprofiles_server.go b/sdk/resourcemanager/trustedsigning/armtrustedsigning/fake/certificateprofiles_server.go index 50234da52fcb..94d152216852 100644 --- a/sdk/resourcemanager/trustedsigning/armtrustedsigning/fake/certificateprofiles_server.go +++ b/sdk/resourcemanager/trustedsigning/armtrustedsigning/fake/certificateprofiles_server.go @@ -25,7 +25,7 @@ type CertificateProfilesServer struct { BeginCreate func(ctx context.Context, resourceGroupName string, accountName string, profileName string, resource armtrustedsigning.CertificateProfile, options *armtrustedsigning.CertificateProfilesClientBeginCreateOptions) (resp azfake.PollerResponder[armtrustedsigning.CertificateProfilesClientCreateResponse], errResp azfake.ErrorResponder) // BeginDelete is the fake for method CertificateProfilesClient.BeginDelete - // HTTP status codes to indicate success: http.StatusAccepted, http.StatusNoContent + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent BeginDelete func(ctx context.Context, resourceGroupName string, accountName string, profileName string, options *armtrustedsigning.CertificateProfilesClientBeginDeleteOptions) (resp azfake.PollerResponder[armtrustedsigning.CertificateProfilesClientDeleteResponse], errResp azfake.ErrorResponder) // Get is the fake for method CertificateProfilesClient.Get @@ -74,25 +74,44 @@ func (c *CertificateProfilesServerTransport) Do(req *http.Request) (*http.Respon } func (c *CertificateProfilesServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { - var resp *http.Response - var err error + resultChan := make(chan result) + defer close(resultChan) - switch method { - case "CertificateProfilesClient.BeginCreate": - resp, err = c.dispatchBeginCreate(req) - case "CertificateProfilesClient.BeginDelete": - resp, err = c.dispatchBeginDelete(req) - case "CertificateProfilesClient.Get": - resp, err = c.dispatchGet(req) - case "CertificateProfilesClient.NewListByCodeSigningAccountPager": - resp, err = c.dispatchNewListByCodeSigningAccountPager(req) - case "CertificateProfilesClient.RevokeCertificate": - resp, err = c.dispatchRevokeCertificate(req) - default: - err = fmt.Errorf("unhandled API %s", method) - } + go func() { + var intercepted bool + var res result + if certificateProfilesServerTransportInterceptor != nil { + res.resp, res.err, intercepted = certificateProfilesServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "CertificateProfilesClient.BeginCreate": + res.resp, res.err = c.dispatchBeginCreate(req) + case "CertificateProfilesClient.BeginDelete": + res.resp, res.err = c.dispatchBeginDelete(req) + case "CertificateProfilesClient.Get": + res.resp, res.err = c.dispatchGet(req) + case "CertificateProfilesClient.NewListByCodeSigningAccountPager": + res.resp, res.err = c.dispatchNewListByCodeSigningAccountPager(req) + case "CertificateProfilesClient.RevokeCertificate": + res.resp, res.err = c.dispatchRevokeCertificate(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + select { + case resultChan <- res: + case <-req.Context().Done(): + } + }() - return resp, err + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } } func (c *CertificateProfilesServerTransport) dispatchBeginCreate(req *http.Request) (*http.Response, error) { @@ -184,9 +203,9 @@ func (c *CertificateProfilesServerTransport) dispatchBeginDelete(req *http.Reque return nil, err } - if !contains([]int{http.StatusAccepted, http.StatusNoContent}, resp.StatusCode) { + if !contains([]int{http.StatusOK, http.StatusAccepted, http.StatusNoContent}, resp.StatusCode) { c.beginDelete.remove(req) - return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusAccepted, http.StatusNoContent", resp.StatusCode)} + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted, http.StatusNoContent", resp.StatusCode)} } if !server.PollerResponderMore(beginDelete) { c.beginDelete.remove(req) @@ -313,3 +332,9 @@ func (c *CertificateProfilesServerTransport) dispatchRevokeCertificate(req *http } return resp, nil } + +// set this to conditionally intercept incoming requests to CertificateProfilesServerTransport +var certificateProfilesServerTransportInterceptor 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/trustedsigning/armtrustedsigning/fake/codesigningaccounts_server.go b/sdk/resourcemanager/trustedsigning/armtrustedsigning/fake/codesigningaccounts_server.go index a886f6e6372a..933abafd06b9 100644 --- a/sdk/resourcemanager/trustedsigning/armtrustedsigning/fake/codesigningaccounts_server.go +++ b/sdk/resourcemanager/trustedsigning/armtrustedsigning/fake/codesigningaccounts_server.go @@ -29,7 +29,7 @@ type CodeSigningAccountsServer struct { BeginCreate func(ctx context.Context, resourceGroupName string, accountName string, resource armtrustedsigning.CodeSigningAccount, options *armtrustedsigning.CodeSigningAccountsClientBeginCreateOptions) (resp azfake.PollerResponder[armtrustedsigning.CodeSigningAccountsClientCreateResponse], errResp azfake.ErrorResponder) // BeginDelete is the fake for method CodeSigningAccountsClient.BeginDelete - // HTTP status codes to indicate success: http.StatusAccepted, http.StatusNoContent + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent BeginDelete func(ctx context.Context, resourceGroupName string, accountName string, options *armtrustedsigning.CodeSigningAccountsClientBeginDeleteOptions) (resp azfake.PollerResponder[armtrustedsigning.CodeSigningAccountsClientDeleteResponse], errResp azfake.ErrorResponder) // Get is the fake for method CodeSigningAccountsClient.Get @@ -86,29 +86,48 @@ func (c *CodeSigningAccountsServerTransport) Do(req *http.Request) (*http.Respon } func (c *CodeSigningAccountsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { - var resp *http.Response - var err error - - switch method { - case "CodeSigningAccountsClient.CheckNameAvailability": - resp, err = c.dispatchCheckNameAvailability(req) - case "CodeSigningAccountsClient.BeginCreate": - resp, err = c.dispatchBeginCreate(req) - case "CodeSigningAccountsClient.BeginDelete": - resp, err = c.dispatchBeginDelete(req) - case "CodeSigningAccountsClient.Get": - resp, err = c.dispatchGet(req) - case "CodeSigningAccountsClient.NewListByResourceGroupPager": - resp, err = c.dispatchNewListByResourceGroupPager(req) - case "CodeSigningAccountsClient.NewListBySubscriptionPager": - resp, err = c.dispatchNewListBySubscriptionPager(req) - case "CodeSigningAccountsClient.BeginUpdate": - resp, err = c.dispatchBeginUpdate(req) - default: - err = fmt.Errorf("unhandled API %s", method) - } - - return resp, err + resultChan := make(chan result) + defer close(resultChan) + + go func() { + var intercepted bool + var res result + if codeSigningAccountsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = codeSigningAccountsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "CodeSigningAccountsClient.CheckNameAvailability": + res.resp, res.err = c.dispatchCheckNameAvailability(req) + case "CodeSigningAccountsClient.BeginCreate": + res.resp, res.err = c.dispatchBeginCreate(req) + case "CodeSigningAccountsClient.BeginDelete": + res.resp, res.err = c.dispatchBeginDelete(req) + case "CodeSigningAccountsClient.Get": + res.resp, res.err = c.dispatchGet(req) + case "CodeSigningAccountsClient.NewListByResourceGroupPager": + res.resp, res.err = c.dispatchNewListByResourceGroupPager(req) + case "CodeSigningAccountsClient.NewListBySubscriptionPager": + res.resp, res.err = c.dispatchNewListBySubscriptionPager(req) + case "CodeSigningAccountsClient.BeginUpdate": + res.resp, res.err = c.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 (c *CodeSigningAccountsServerTransport) dispatchCheckNameAvailability(req *http.Request) (*http.Response, error) { @@ -221,9 +240,9 @@ func (c *CodeSigningAccountsServerTransport) dispatchBeginDelete(req *http.Reque return nil, err } - if !contains([]int{http.StatusAccepted, http.StatusNoContent}, resp.StatusCode) { + if !contains([]int{http.StatusOK, http.StatusAccepted, http.StatusNoContent}, resp.StatusCode) { c.beginDelete.remove(req) - return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusAccepted, http.StatusNoContent", resp.StatusCode)} + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted, http.StatusNoContent", resp.StatusCode)} } if !server.PollerResponderMore(beginDelete) { c.beginDelete.remove(req) @@ -382,3 +401,9 @@ func (c *CodeSigningAccountsServerTransport) dispatchBeginUpdate(req *http.Reque return resp, nil } + +// set this to conditionally intercept incoming requests to CodeSigningAccountsServerTransport +var codeSigningAccountsServerTransportInterceptor 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/trustedsigning/armtrustedsigning/fake/internal.go b/sdk/resourcemanager/trustedsigning/armtrustedsigning/fake/internal.go index 56a8f624f5f3..7425b6a669e2 100644 --- a/sdk/resourcemanager/trustedsigning/armtrustedsigning/fake/internal.go +++ b/sdk/resourcemanager/trustedsigning/armtrustedsigning/fake/internal.go @@ -10,6 +10,11 @@ import ( "sync" ) +type result struct { + resp *http.Response + err error +} + type nonRetriableError struct { error } diff --git a/sdk/resourcemanager/trustedsigning/armtrustedsigning/fake/operations_server.go b/sdk/resourcemanager/trustedsigning/armtrustedsigning/fake/operations_server.go index dcbfc7a95dbc..dc32d5c2713e 100644 --- a/sdk/resourcemanager/trustedsigning/armtrustedsigning/fake/operations_server.go +++ b/sdk/resourcemanager/trustedsigning/armtrustedsigning/fake/operations_server.go @@ -51,17 +51,36 @@ func (o *OperationsServerTransport) Do(req *http.Request) (*http.Response, error } func (o *OperationsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { - var resp *http.Response - var err error + resultChan := make(chan result) + defer close(resultChan) - switch method { - case "OperationsClient.NewListPager": - resp, err = o.dispatchNewListPager(req) - default: - err = fmt.Errorf("unhandled API %s", method) - } + 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(): + } + }() - return resp, err + 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) { @@ -90,3 +109,9 @@ func (o *OperationsServerTransport) dispatchNewListPager(req *http.Request) (*ht } return resp, nil } + +// set this to conditionally intercept incoming requests to OperationsServerTransport +var operationsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/sdk/resourcemanager/trustedsigning/armtrustedsigning/models.go b/sdk/resourcemanager/trustedsigning/armtrustedsigning/models.go index cfb89b3234d0..0f26f0fd32b8 100644 --- a/sdk/resourcemanager/trustedsigning/armtrustedsigning/models.go +++ b/sdk/resourcemanager/trustedsigning/armtrustedsigning/models.go @@ -12,11 +12,20 @@ type AccountSKU struct { Name *SKUName } +// AccountSKUPatch - SKU of the trusted signing account. +type AccountSKUPatch struct { + // Name of the SKU. + Name *SKUName +} + // Certificate - Properties of the certificate. type Certificate struct { // Certificate created date. CreatedDate *string + // Enhanced key usage of the certificate. + EnhancedKeyUsage *string + // Certificate expiry date. ExpiryDate *string @@ -65,12 +74,12 @@ type CertificateProfileListResult struct { // CertificateProfileProperties - Properties of the certificate profile. type CertificateProfileProperties struct { + // REQUIRED; Identity validation id used for the certificate subject name. + IdentityValidationID *string + // REQUIRED; Profile type of the certificate. ProfileType *ProfileType - // Identity validation id used for the certificate subject name. - IdentityValidationID *string - // Whether to include L in the certificate subject name. Applicable only for private trust, private trust ci profile types IncludeCity *bool @@ -89,38 +98,11 @@ type CertificateProfileProperties struct { // READ-ONLY; List of renewed certificates. Certificates []*Certificate - // READ-ONLY; Used as L in the certificate subject name. - City *string - - // READ-ONLY; Used as CN in the certificate subject name. - CommonName *string - - // READ-ONLY; Used as C in the certificate subject name. - Country *string - - // READ-ONLY; Enhanced key usage of the certificate. - EnhancedKeyUsage *string - - // READ-ONLY; Used as O in the certificate subject name. - Organization *string - - // READ-ONLY; Used as OU in the private trust certificate subject name. - OrganizationUnit *string - - // READ-ONLY; Used as PC in the certificate subject name. - PostalCode *string - // READ-ONLY; Status of the current operation on certificate profile. ProvisioningState *ProvisioningState - // READ-ONLY; Used as S in the certificate subject name. - State *string - // READ-ONLY; Status of the certificate profile. Status *CertificateProfileStatus - - // READ-ONLY; Used as STREET in the certificate subject name. - StreetAddress *string } // CheckNameAvailability - The parameters used to check the availability of the trusted signing account name. @@ -188,7 +170,7 @@ type CodeSigningAccountPatch struct { // CodeSigningAccountPatchProperties - Properties of the trusted signing account. type CodeSigningAccountPatchProperties struct { // SKU of the trusted signing account. - SKU *AccountSKU + SKU *AccountSKUPatch } // CodeSigningAccountProperties - Properties of the trusted signing account. @@ -205,12 +187,12 @@ type CodeSigningAccountProperties struct { // Operation - Details of a REST API operation, returned from the Resource Provider Operations API type Operation struct { - // Extensible enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. - ActionType *ActionType - - // READ-ONLY; Localized display information for this particular operation. + // Localized display information for this particular operation. Display *OperationDisplay + // READ-ONLY; Extensible 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 Azure // Resource Manager/control-plane operations. IsDataAction *bool diff --git a/sdk/resourcemanager/trustedsigning/armtrustedsigning/models_serde.go b/sdk/resourcemanager/trustedsigning/armtrustedsigning/models_serde.go index a2b0b08cfedf..fcb032b16f18 100644 --- a/sdk/resourcemanager/trustedsigning/armtrustedsigning/models_serde.go +++ b/sdk/resourcemanager/trustedsigning/armtrustedsigning/models_serde.go @@ -38,10 +38,38 @@ func (a *AccountSKU) UnmarshalJSON(data []byte) error { return nil } +// MarshalJSON implements the json.Marshaller interface for type AccountSKUPatch. +func (a AccountSKUPatch) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", a.Name) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AccountSKUPatch. +func (a *AccountSKUPatch) 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 "name": + err = unpopulate(val, "Name", &a.Name) + 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 Certificate. func (c Certificate) MarshalJSON() ([]byte, error) { objectMap := make(map[string]any) populate(objectMap, "createdDate", c.CreatedDate) + populate(objectMap, "enhancedKeyUsage", c.EnhancedKeyUsage) populate(objectMap, "expiryDate", c.ExpiryDate) populate(objectMap, "revocation", c.Revocation) populate(objectMap, "serialNumber", c.SerialNumber) @@ -63,6 +91,9 @@ func (c *Certificate) UnmarshalJSON(data []byte) error { case "createdDate": err = unpopulate(val, "CreatedDate", &c.CreatedDate) delete(rawMsg, key) + case "enhancedKeyUsage": + err = unpopulate(val, "EnhancedKeyUsage", &c.EnhancedKeyUsage) + delete(rawMsg, key) case "expiryDate": err = unpopulate(val, "ExpiryDate", &c.ExpiryDate) delete(rawMsg, key) @@ -167,24 +198,15 @@ func (c *CertificateProfileListResult) UnmarshalJSON(data []byte) error { func (c CertificateProfileProperties) MarshalJSON() ([]byte, error) { objectMap := make(map[string]any) populate(objectMap, "certificates", c.Certificates) - populate(objectMap, "city", c.City) - populate(objectMap, "commonName", c.CommonName) - populate(objectMap, "country", c.Country) - populate(objectMap, "enhancedKeyUsage", c.EnhancedKeyUsage) populate(objectMap, "identityValidationId", c.IdentityValidationID) populate(objectMap, "includeCity", c.IncludeCity) populate(objectMap, "includeCountry", c.IncludeCountry) populate(objectMap, "includePostalCode", c.IncludePostalCode) populate(objectMap, "includeState", c.IncludeState) populate(objectMap, "includeStreetAddress", c.IncludeStreetAddress) - populate(objectMap, "organization", c.Organization) - populate(objectMap, "organizationUnit", c.OrganizationUnit) - populate(objectMap, "postalCode", c.PostalCode) populate(objectMap, "profileType", c.ProfileType) populate(objectMap, "provisioningState", c.ProvisioningState) - populate(objectMap, "state", c.State) populate(objectMap, "status", c.Status) - populate(objectMap, "streetAddress", c.StreetAddress) return json.Marshal(objectMap) } @@ -200,18 +222,6 @@ func (c *CertificateProfileProperties) UnmarshalJSON(data []byte) error { case "certificates": err = unpopulate(val, "Certificates", &c.Certificates) delete(rawMsg, key) - case "city": - err = unpopulate(val, "City", &c.City) - delete(rawMsg, key) - case "commonName": - err = unpopulate(val, "CommonName", &c.CommonName) - delete(rawMsg, key) - case "country": - err = unpopulate(val, "Country", &c.Country) - delete(rawMsg, key) - case "enhancedKeyUsage": - err = unpopulate(val, "EnhancedKeyUsage", &c.EnhancedKeyUsage) - delete(rawMsg, key) case "identityValidationId": err = unpopulate(val, "IdentityValidationID", &c.IdentityValidationID) delete(rawMsg, key) @@ -230,30 +240,15 @@ func (c *CertificateProfileProperties) UnmarshalJSON(data []byte) error { case "includeStreetAddress": err = unpopulate(val, "IncludeStreetAddress", &c.IncludeStreetAddress) delete(rawMsg, key) - case "organization": - err = unpopulate(val, "Organization", &c.Organization) - delete(rawMsg, key) - case "organizationUnit": - err = unpopulate(val, "OrganizationUnit", &c.OrganizationUnit) - delete(rawMsg, key) - case "postalCode": - err = unpopulate(val, "PostalCode", &c.PostalCode) - delete(rawMsg, key) case "profileType": err = unpopulate(val, "ProfileType", &c.ProfileType) delete(rawMsg, key) case "provisioningState": err = unpopulate(val, "ProvisioningState", &c.ProvisioningState) delete(rawMsg, key) - case "state": - err = unpopulate(val, "State", &c.State) - delete(rawMsg, key) case "status": err = unpopulate(val, "Status", &c.Status) delete(rawMsg, key) - case "streetAddress": - err = unpopulate(val, "StreetAddress", &c.StreetAddress) - delete(rawMsg, key) } if err != nil { return fmt.Errorf("unmarshalling type %T: %v", c, err) diff --git a/sdk/resourcemanager/trustedsigning/armtrustedsigning/operations_client.go b/sdk/resourcemanager/trustedsigning/armtrustedsigning/operations_client.go index 4df423270e96..ee3e36600a93 100644 --- a/sdk/resourcemanager/trustedsigning/armtrustedsigning/operations_client.go +++ b/sdk/resourcemanager/trustedsigning/armtrustedsigning/operations_client.go @@ -35,7 +35,7 @@ func NewOperationsClient(credential azcore.TokenCredential, options *arm.ClientO // NewListPager - List the operations for the provider // -// Generated from API version 2024-02-05-preview +// Generated from API version 2024-09-30-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]{ @@ -68,7 +68,7 @@ func (client *OperationsClient) listCreateRequest(ctx context.Context, _ *Operat return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2024-02-05-preview") + reqQP.Set("api-version", "2024-09-30-preview") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil diff --git a/sdk/resourcemanager/trustedsigning/armtrustedsigning/operations_client_example_test.go b/sdk/resourcemanager/trustedsigning/armtrustedsigning/operations_client_example_test.go index 8d8011d02001..886d000c955f 100644 --- a/sdk/resourcemanager/trustedsigning/armtrustedsigning/operations_client_example_test.go +++ b/sdk/resourcemanager/trustedsigning/armtrustedsigning/operations_client_example_test.go @@ -11,7 +11,7 @@ import ( "log" ) -// Generated from example definition: 2024-02-05-preview/Operations_List.json +// Generated from example definition: 2024-09-30-preview/Operations_List.json func ExampleOperationsClient_NewListPager() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { diff --git a/sdk/resourcemanager/trustedsigning/armtrustedsigning/tsp-location.yaml b/sdk/resourcemanager/trustedsigning/armtrustedsigning/tsp-location.yaml index 58a0ab9c920e..bf9049421391 100644 --- a/sdk/resourcemanager/trustedsigning/armtrustedsigning/tsp-location.yaml +++ b/sdk/resourcemanager/trustedsigning/armtrustedsigning/tsp-location.yaml @@ -1,4 +1,4 @@ directory: specification/codesigning/CodeSigning.Management -commit: 778fdb20839c487eba95a6b161812ad9d9d6337d +commit: 1f578543d267d08febc1bebf4e33ffe14363ddfc repo: Azure/azure-rest-api-specs additionalDirectories: