deps: bump

This commit is contained in:
Simon de Vlieger 2024-03-15 08:42:35 +01:00
parent 57ebfb4011
commit babf80f060
164 changed files with 61441 additions and 55390 deletions

View file

@ -135,7 +135,7 @@ func (c *AcceleratorTypesClient) Connection() *grpc.ClientConn {
return c.internalClient.Connection()
}
// AggregatedList retrieves an aggregated list of accelerator types.
// AggregatedList retrieves an aggregated list of accelerator types. To prevent failure, Google recommends that you set the returnPartialSuccess parameter to true.
func (c *AcceleratorTypesClient) AggregatedList(ctx context.Context, req *computepb.AggregatedListAcceleratorTypesRequest, opts ...gax.CallOption) *AcceleratorTypesScopedListPairIterator {
return c.internalClient.AggregatedList(ctx, req, opts...)
}
@ -223,7 +223,7 @@ func (c *acceleratorTypesRESTClient) Connection() *grpc.ClientConn {
return nil
}
// AggregatedList retrieves an aggregated list of accelerator types.
// AggregatedList retrieves an aggregated list of accelerator types. To prevent failure, Google recommends that you set the returnPartialSuccess parameter to true.
func (c *acceleratorTypesRESTClient) AggregatedList(ctx context.Context, req *computepb.AggregatedListAcceleratorTypesRequest, opts ...gax.CallOption) *AcceleratorTypesScopedListPairIterator {
it := &AcceleratorTypesScopedListPairIterator{}
req = proto.Clone(req).(*computepb.AggregatedListAcceleratorTypesRequest)

View file

@ -154,7 +154,7 @@ func (c *AddressesClient) Connection() *grpc.ClientConn {
return c.internalClient.Connection()
}
// AggregatedList retrieves an aggregated list of addresses.
// AggregatedList retrieves an aggregated list of addresses. To prevent failure, Google recommends that you set the returnPartialSuccess parameter to true.
func (c *AddressesClient) AggregatedList(ctx context.Context, req *computepb.AggregatedListAddressesRequest, opts ...gax.CallOption) *AddressesScopedListPairIterator {
return c.internalClient.AggregatedList(ctx, req, opts...)
}
@ -276,7 +276,7 @@ func (c *addressesRESTClient) Connection() *grpc.ClientConn {
return nil
}
// AggregatedList retrieves an aggregated list of addresses.
// AggregatedList retrieves an aggregated list of addresses. To prevent failure, Google recommends that you set the returnPartialSuccess parameter to true.
func (c *addressesRESTClient) AggregatedList(ctx context.Context, req *computepb.AggregatedListAddressesRequest, opts ...gax.CallOption) *AddressesScopedListPairIterator {
it := &AddressesScopedListPairIterator{}
req = proto.Clone(req).(*computepb.AggregatedListAddressesRequest)

View file

@ -154,7 +154,7 @@ func (c *AutoscalersClient) Connection() *grpc.ClientConn {
return c.internalClient.Connection()
}
// AggregatedList retrieves an aggregated list of autoscalers.
// AggregatedList retrieves an aggregated list of autoscalers. To prevent failure, Google recommends that you set the returnPartialSuccess parameter to true.
func (c *AutoscalersClient) AggregatedList(ctx context.Context, req *computepb.AggregatedListAutoscalersRequest, opts ...gax.CallOption) *AutoscalersScopedListPairIterator {
return c.internalClient.AggregatedList(ctx, req, opts...)
}
@ -276,7 +276,7 @@ func (c *autoscalersRESTClient) Connection() *grpc.ClientConn {
return nil
}
// AggregatedList retrieves an aggregated list of autoscalers.
// AggregatedList retrieves an aggregated list of autoscalers. To prevent failure, Google recommends that you set the returnPartialSuccess parameter to true.
func (c *autoscalersRESTClient) AggregatedList(ctx context.Context, req *computepb.AggregatedListAutoscalersRequest, opts ...gax.CallOption) *AutoscalersScopedListPairIterator {
it := &AutoscalersScopedListPairIterator{}
req = proto.Clone(req).(*computepb.AggregatedListAutoscalersRequest)

View file

@ -1744,6 +1744,106 @@ func (it *InstancesScopedListPairIterator) takeBuf() interface{} {
return b
}
// InstantSnapshotIterator manages a stream of *computepb.InstantSnapshot.
type InstantSnapshotIterator struct {
items []*computepb.InstantSnapshot
pageInfo *iterator.PageInfo
nextFunc func() error
// Response is the raw response for the current page.
// It must be cast to the RPC response type.
// Calling Next() or InternalFetch() updates this value.
Response interface{}
// InternalFetch is for use by the Google Cloud Libraries only.
// It is not part of the stable interface of this package.
//
// InternalFetch returns results from a single call to the underlying RPC.
// The number of results is no greater than pageSize.
// If there are no more results, nextPageToken is empty and err is nil.
InternalFetch func(pageSize int, pageToken string) (results []*computepb.InstantSnapshot, nextPageToken string, err error)
}
// PageInfo supports pagination. See the google.golang.org/api/iterator package for details.
func (it *InstantSnapshotIterator) PageInfo() *iterator.PageInfo {
return it.pageInfo
}
// Next returns the next result. Its second return value is iterator.Done if there are no more
// results. Once Next returns Done, all subsequent calls will return Done.
func (it *InstantSnapshotIterator) Next() (*computepb.InstantSnapshot, error) {
var item *computepb.InstantSnapshot
if err := it.nextFunc(); err != nil {
return item, err
}
item = it.items[0]
it.items = it.items[1:]
return item, nil
}
func (it *InstantSnapshotIterator) bufLen() int {
return len(it.items)
}
func (it *InstantSnapshotIterator) takeBuf() interface{} {
b := it.items
it.items = nil
return b
}
// InstantSnapshotsScopedListPair is a holder type for string/*computepb.InstantSnapshotsScopedList map entries
type InstantSnapshotsScopedListPair struct {
Key string
Value *computepb.InstantSnapshotsScopedList
}
// InstantSnapshotsScopedListPairIterator manages a stream of InstantSnapshotsScopedListPair.
type InstantSnapshotsScopedListPairIterator struct {
items []InstantSnapshotsScopedListPair
pageInfo *iterator.PageInfo
nextFunc func() error
// Response is the raw response for the current page.
// It must be cast to the RPC response type.
// Calling Next() or InternalFetch() updates this value.
Response interface{}
// InternalFetch is for use by the Google Cloud Libraries only.
// It is not part of the stable interface of this package.
//
// InternalFetch returns results from a single call to the underlying RPC.
// The number of results is no greater than pageSize.
// If there are no more results, nextPageToken is empty and err is nil.
InternalFetch func(pageSize int, pageToken string) (results []InstantSnapshotsScopedListPair, nextPageToken string, err error)
}
// PageInfo supports pagination. See the google.golang.org/api/iterator package for details.
func (it *InstantSnapshotsScopedListPairIterator) PageInfo() *iterator.PageInfo {
return it.pageInfo
}
// Next returns the next result. Its second return value is iterator.Done if there are no more
// results. Once Next returns Done, all subsequent calls will return Done.
func (it *InstantSnapshotsScopedListPairIterator) Next() (InstantSnapshotsScopedListPair, error) {
var item InstantSnapshotsScopedListPair
if err := it.nextFunc(); err != nil {
return item, err
}
item = it.items[0]
it.items = it.items[1:]
return item, nil
}
func (it *InstantSnapshotsScopedListPairIterator) bufLen() int {
return len(it.items)
}
func (it *InstantSnapshotsScopedListPairIterator) takeBuf() interface{} {
b := it.items
it.items = nil
return b
}
// InterconnectAttachmentIterator manages a stream of *computepb.InterconnectAttachment.
type InterconnectAttachmentIterator struct {
items []*computepb.InterconnectAttachment

View file

@ -222,7 +222,7 @@ func (c *BackendServicesClient) AddSignedUrlKey(ctx context.Context, req *comput
return c.internalClient.AddSignedUrlKey(ctx, req, opts...)
}
// AggregatedList retrieves the list of all BackendService resources, regional and global, available to the specified project.
// AggregatedList retrieves the list of all BackendService resources, regional and global, available to the specified project. To prevent failure, Google recommends that you set the returnPartialSuccess parameter to true.
func (c *BackendServicesClient) AggregatedList(ctx context.Context, req *computepb.AggregatedListBackendServicesRequest, opts ...gax.CallOption) *BackendServicesScopedListPairIterator {
return c.internalClient.AggregatedList(ctx, req, opts...)
}
@ -460,7 +460,7 @@ func (c *backendServicesRESTClient) AddSignedUrlKey(ctx context.Context, req *co
return op, nil
}
// AggregatedList retrieves the list of all BackendService resources, regional and global, available to the specified project.
// AggregatedList retrieves the list of all BackendService resources, regional and global, available to the specified project. To prevent failure, Google recommends that you set the returnPartialSuccess parameter to true.
func (c *backendServicesRESTClient) AggregatedList(ctx context.Context, req *computepb.AggregatedListBackendServicesRequest, opts ...gax.CallOption) *BackendServicesScopedListPairIterator {
it := &BackendServicesScopedListPairIterator{}
req = proto.Clone(req).(*computepb.AggregatedListBackendServicesRequest)

File diff suppressed because it is too large Load diff

View file

@ -133,7 +133,7 @@ func (c *DiskTypesClient) Connection() *grpc.ClientConn {
return c.internalClient.Connection()
}
// AggregatedList retrieves an aggregated list of disk types.
// AggregatedList retrieves an aggregated list of disk types. To prevent failure, Google recommends that you set the returnPartialSuccess parameter to true.
func (c *DiskTypesClient) AggregatedList(ctx context.Context, req *computepb.AggregatedListDiskTypesRequest, opts ...gax.CallOption) *DiskTypesScopedListPairIterator {
return c.internalClient.AggregatedList(ctx, req, opts...)
}
@ -219,7 +219,7 @@ func (c *diskTypesRESTClient) Connection() *grpc.ClientConn {
return nil
}
// AggregatedList retrieves an aggregated list of disk types.
// AggregatedList retrieves an aggregated list of disk types. To prevent failure, Google recommends that you set the returnPartialSuccess parameter to true.
func (c *diskTypesRESTClient) AggregatedList(ctx context.Context, req *computepb.AggregatedListDiskTypesRequest, opts ...gax.CallOption) *DiskTypesScopedListPairIterator {
it := &DiskTypesScopedListPairIterator{}
req = proto.Clone(req).(*computepb.AggregatedListDiskTypesRequest)

View file

@ -223,7 +223,7 @@ func (c *DisksClient) AddResourcePolicies(ctx context.Context, req *computepb.Ad
return c.internalClient.AddResourcePolicies(ctx, req, opts...)
}
// AggregatedList retrieves an aggregated list of persistent disks.
// AggregatedList retrieves an aggregated list of persistent disks. To prevent failure, Google recommends that you set the returnPartialSuccess parameter to true.
func (c *DisksClient) AggregatedList(ctx context.Context, req *computepb.AggregatedListDisksRequest, opts ...gax.CallOption) *DisksScopedListPairIterator {
return c.internalClient.AggregatedList(ctx, req, opts...)
}
@ -472,7 +472,7 @@ func (c *disksRESTClient) AddResourcePolicies(ctx context.Context, req *computep
return op, nil
}
// AggregatedList retrieves an aggregated list of persistent disks.
// AggregatedList retrieves an aggregated list of persistent disks. To prevent failure, Google recommends that you set the returnPartialSuccess parameter to true.
func (c *disksRESTClient) AggregatedList(ctx context.Context, req *computepb.AggregatedListDisksRequest, opts ...gax.CallOption) *DisksScopedListPairIterator {
it := &DisksScopedListPairIterator{}
req = proto.Clone(req).(*computepb.AggregatedListDisksRequest)

View file

@ -159,7 +159,7 @@ func (c *ForwardingRulesClient) Connection() *grpc.ClientConn {
return c.internalClient.Connection()
}
// AggregatedList retrieves an aggregated list of forwarding rules.
// AggregatedList retrieves an aggregated list of forwarding rules. To prevent failure, Google recommends that you set the returnPartialSuccess parameter to true.
func (c *ForwardingRulesClient) AggregatedList(ctx context.Context, req *computepb.AggregatedListForwardingRulesRequest, opts ...gax.CallOption) *ForwardingRulesScopedListPairIterator {
return c.internalClient.AggregatedList(ctx, req, opts...)
}
@ -286,7 +286,7 @@ func (c *forwardingRulesRESTClient) Connection() *grpc.ClientConn {
return nil
}
// AggregatedList retrieves an aggregated list of forwarding rules.
// AggregatedList retrieves an aggregated list of forwarding rules. To prevent failure, Google recommends that you set the returnPartialSuccess parameter to true.
func (c *forwardingRulesRESTClient) AggregatedList(ctx context.Context, req *computepb.AggregatedListForwardingRulesRequest, opts ...gax.CallOption) *ForwardingRulesScopedListPairIterator {
it := &ForwardingRulesScopedListPairIterator{}
req = proto.Clone(req).(*computepb.AggregatedListForwardingRulesRequest)

View file

@ -1426,6 +1426,60 @@
}
}
},
"InstantSnapshots": {
"clients": {
"rest": {
"libraryClient": "InstantSnapshotsClient",
"rpcs": {
"AggregatedList": {
"methods": [
"AggregatedList"
]
},
"Delete": {
"methods": [
"Delete"
]
},
"Get": {
"methods": [
"Get"
]
},
"GetIamPolicy": {
"methods": [
"GetIamPolicy"
]
},
"Insert": {
"methods": [
"Insert"
]
},
"List": {
"methods": [
"List"
]
},
"SetIamPolicy": {
"methods": [
"SetIamPolicy"
]
},
"SetLabels": {
"methods": [
"SetLabels"
]
},
"TestIamPermissions": {
"methods": [
"TestIamPermissions"
]
}
}
}
}
},
"InterconnectAttachments": {
"clients": {
"rest": {
@ -2234,6 +2288,11 @@
"MoveInstance"
]
},
"SetCloudArmorTier": {
"methods": [
"SetCloudArmorTier"
]
},
"SetCommonInstanceMetadata": {
"methods": [
"SetCommonInstanceMetadata"
@ -2850,6 +2909,55 @@
}
}
},
"RegionInstantSnapshots": {
"clients": {
"rest": {
"libraryClient": "RegionInstantSnapshotsClient",
"rpcs": {
"Delete": {
"methods": [
"Delete"
]
},
"Get": {
"methods": [
"Get"
]
},
"GetIamPolicy": {
"methods": [
"GetIamPolicy"
]
},
"Insert": {
"methods": [
"Insert"
]
},
"List": {
"methods": [
"List"
]
},
"SetIamPolicy": {
"methods": [
"SetIamPolicy"
]
},
"SetLabels": {
"methods": [
"SetLabels"
]
},
"TestIamPermissions": {
"methods": [
"TestIamPermissions"
]
}
}
}
}
},
"RegionNetworkEndpointGroups": {
"clients": {
"rest": {

View file

@ -143,7 +143,7 @@ func (c *GlobalOperationsClient) Connection() *grpc.ClientConn {
return c.internalClient.Connection()
}
// AggregatedList retrieves an aggregated list of all operations.
// AggregatedList retrieves an aggregated list of all operations. To prevent failure, Google recommends that you set the returnPartialSuccess parameter to true.
func (c *GlobalOperationsClient) AggregatedList(ctx context.Context, req *computepb.AggregatedListGlobalOperationsRequest, opts ...gax.CallOption) *OperationsScopedListPairIterator {
return c.internalClient.AggregatedList(ctx, req, opts...)
}
@ -239,7 +239,7 @@ func (c *globalOperationsRESTClient) Connection() *grpc.ClientConn {
return nil
}
// AggregatedList retrieves an aggregated list of all operations.
// AggregatedList retrieves an aggregated list of all operations. To prevent failure, Google recommends that you set the returnPartialSuccess parameter to true.
func (c *globalOperationsRESTClient) AggregatedList(ctx context.Context, req *computepb.AggregatedListGlobalOperationsRequest, opts ...gax.CallOption) *OperationsScopedListPairIterator {
it := &OperationsScopedListPairIterator{}
req = proto.Clone(req).(*computepb.AggregatedListGlobalOperationsRequest)

View file

@ -154,7 +154,7 @@ func (c *HealthChecksClient) Connection() *grpc.ClientConn {
return c.internalClient.Connection()
}
// AggregatedList retrieves the list of all HealthCheck resources, regional and global, available to the specified project.
// AggregatedList retrieves the list of all HealthCheck resources, regional and global, available to the specified project. To prevent failure, Google recommends that you set the returnPartialSuccess parameter to true.
func (c *HealthChecksClient) AggregatedList(ctx context.Context, req *computepb.AggregatedListHealthChecksRequest, opts ...gax.CallOption) *HealthChecksScopedListPairIterator {
return c.internalClient.AggregatedList(ctx, req, opts...)
}
@ -276,7 +276,7 @@ func (c *healthChecksRESTClient) Connection() *grpc.ClientConn {
return nil
}
// AggregatedList retrieves the list of all HealthCheck resources, regional and global, available to the specified project.
// AggregatedList retrieves the list of all HealthCheck resources, regional and global, available to the specified project. To prevent failure, Google recommends that you set the returnPartialSuccess parameter to true.
func (c *healthChecksRESTClient) AggregatedList(ctx context.Context, req *computepb.AggregatedListHealthChecksRequest, opts ...gax.CallOption) *HealthChecksScopedListPairIterator {
it := &HealthChecksScopedListPairIterator{}
req = proto.Clone(req).(*computepb.AggregatedListHealthChecksRequest)

View file

@ -233,7 +233,7 @@ func (c *InstanceGroupManagersClient) AbandonInstances(ctx context.Context, req
return c.internalClient.AbandonInstances(ctx, req, opts...)
}
// AggregatedList retrieves the list of managed instance groups and groups them by zone.
// AggregatedList retrieves the list of managed instance groups and groups them by zone. To prevent failure, Google recommends that you set the returnPartialSuccess parameter to true.
func (c *InstanceGroupManagersClient) AggregatedList(ctx context.Context, req *computepb.AggregatedListInstanceGroupManagersRequest, opts ...gax.CallOption) *InstanceGroupManagersScopedListPairIterator {
return c.internalClient.AggregatedList(ctx, req, opts...)
}
@ -492,7 +492,7 @@ func (c *instanceGroupManagersRESTClient) AbandonInstances(ctx context.Context,
return op, nil
}
// AggregatedList retrieves the list of managed instance groups and groups them by zone.
// AggregatedList retrieves the list of managed instance groups and groups them by zone. To prevent failure, Google recommends that you set the returnPartialSuccess parameter to true.
func (c *instanceGroupManagersRESTClient) AggregatedList(ctx context.Context, req *computepb.AggregatedListInstanceGroupManagersRequest, opts ...gax.CallOption) *InstanceGroupManagersScopedListPairIterator {
it := &InstanceGroupManagersScopedListPairIterator{}
req = proto.Clone(req).(*computepb.AggregatedListInstanceGroupManagersRequest)

View file

@ -169,7 +169,7 @@ func (c *InstanceGroupsClient) AddInstances(ctx context.Context, req *computepb.
return c.internalClient.AddInstances(ctx, req, opts...)
}
// AggregatedList retrieves the list of instance groups and sorts them by zone.
// AggregatedList retrieves the list of instance groups and sorts them by zone. To prevent failure, Google recommends that you set the returnPartialSuccess parameter to true.
func (c *InstanceGroupsClient) AggregatedList(ctx context.Context, req *computepb.AggregatedListInstanceGroupsRequest, opts ...gax.CallOption) *InstanceGroupsScopedListPairIterator {
return c.internalClient.AggregatedList(ctx, req, opts...)
}
@ -373,7 +373,7 @@ func (c *instanceGroupsRESTClient) AddInstances(ctx context.Context, req *comput
return op, nil
}
// AggregatedList retrieves the list of instance groups and sorts them by zone.
// AggregatedList retrieves the list of instance groups and sorts them by zone. To prevent failure, Google recommends that you set the returnPartialSuccess parameter to true.
func (c *instanceGroupsRESTClient) AggregatedList(ctx context.Context, req *computepb.AggregatedListInstanceGroupsRequest, opts ...gax.CallOption) *InstanceGroupsScopedListPairIterator {
it := &InstanceGroupsScopedListPairIterator{}
req = proto.Clone(req).(*computepb.AggregatedListInstanceGroupsRequest)

View file

@ -168,7 +168,7 @@ func (c *InstanceTemplatesClient) Connection() *grpc.ClientConn {
return c.internalClient.Connection()
}
// AggregatedList retrieves the list of all InstanceTemplates resources, regional and global, available to the specified project.
// AggregatedList retrieves the list of all InstanceTemplates resources, regional and global, available to the specified project. To prevent failure, Google recommends that you set the returnPartialSuccess parameter to true.
func (c *InstanceTemplatesClient) AggregatedList(ctx context.Context, req *computepb.AggregatedListInstanceTemplatesRequest, opts ...gax.CallOption) *InstanceTemplatesScopedListPairIterator {
return c.internalClient.AggregatedList(ctx, req, opts...)
}
@ -295,7 +295,7 @@ func (c *instanceTemplatesRESTClient) Connection() *grpc.ClientConn {
return nil
}
// AggregatedList retrieves the list of all InstanceTemplates resources, regional and global, available to the specified project.
// AggregatedList retrieves the list of all InstanceTemplates resources, regional and global, available to the specified project. To prevent failure, Google recommends that you set the returnPartialSuccess parameter to true.
func (c *instanceTemplatesRESTClient) AggregatedList(ctx context.Context, req *computepb.AggregatedListInstanceTemplatesRequest, opts ...gax.CallOption) *InstanceTemplatesScopedListPairIterator {
it := &InstanceTemplatesScopedListPairIterator{}
req = proto.Clone(req).(*computepb.AggregatedListInstanceTemplatesRequest)

View file

@ -432,7 +432,7 @@ func (c *InstancesClient) AddResourcePolicies(ctx context.Context, req *computep
return c.internalClient.AddResourcePolicies(ctx, req, opts...)
}
// AggregatedList retrieves an aggregated list of all of the instances in your project across all regions and zones. The performance of this method degrades when a filter is specified on a project that has a very large number of instances.
// AggregatedList retrieves an aggregated list of all of the instances in your project across all regions and zones. The performance of this method degrades when a filter is specified on a project that has a very large number of instances. To prevent failure, Google recommends that you set the returnPartialSuccess parameter to true.
func (c *InstancesClient) AggregatedList(ctx context.Context, req *computepb.AggregatedListInstancesRequest, opts ...gax.CallOption) *InstancesScopedListPairIterator {
return c.internalClient.AggregatedList(ctx, req, opts...)
}
@ -904,7 +904,7 @@ func (c *instancesRESTClient) AddResourcePolicies(ctx context.Context, req *comp
return op, nil
}
// AggregatedList retrieves an aggregated list of all of the instances in your project across all regions and zones. The performance of this method degrades when a filter is specified on a project that has a very large number of instances.
// AggregatedList retrieves an aggregated list of all of the instances in your project across all regions and zones. The performance of this method degrades when a filter is specified on a project that has a very large number of instances. To prevent failure, Google recommends that you set the returnPartialSuccess parameter to true.
func (c *instancesRESTClient) AggregatedList(ctx context.Context, req *computepb.AggregatedListInstancesRequest, opts ...gax.CallOption) *InstancesScopedListPairIterator {
it := &InstancesScopedListPairIterator{}
req = proto.Clone(req).(*computepb.AggregatedListInstancesRequest)

View file

@ -0,0 +1,978 @@
// Copyright 2024 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Code generated by protoc-gen-go_gapic. DO NOT EDIT.
package compute
import (
"bytes"
"context"
"fmt"
"io"
"math"
"net/http"
"net/url"
"sort"
"time"
computepb "cloud.google.com/go/compute/apiv1/computepb"
gax "github.com/googleapis/gax-go/v2"
"google.golang.org/api/googleapi"
"google.golang.org/api/iterator"
"google.golang.org/api/option"
"google.golang.org/api/option/internaloption"
httptransport "google.golang.org/api/transport/http"
"google.golang.org/grpc"
"google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/proto"
)
var newInstantSnapshotsClientHook clientHook
// InstantSnapshotsCallOptions contains the retry settings for each method of InstantSnapshotsClient.
type InstantSnapshotsCallOptions struct {
AggregatedList []gax.CallOption
Delete []gax.CallOption
Get []gax.CallOption
GetIamPolicy []gax.CallOption
Insert []gax.CallOption
List []gax.CallOption
SetIamPolicy []gax.CallOption
SetLabels []gax.CallOption
TestIamPermissions []gax.CallOption
}
func defaultInstantSnapshotsRESTCallOptions() *InstantSnapshotsCallOptions {
return &InstantSnapshotsCallOptions{
AggregatedList: []gax.CallOption{
gax.WithTimeout(600000 * time.Millisecond),
gax.WithRetry(func() gax.Retryer {
return gax.OnHTTPCodes(gax.Backoff{
Initial: 100 * time.Millisecond,
Max: 60000 * time.Millisecond,
Multiplier: 1.30,
},
http.StatusGatewayTimeout,
http.StatusServiceUnavailable)
}),
},
Delete: []gax.CallOption{
gax.WithTimeout(600000 * time.Millisecond),
},
Get: []gax.CallOption{
gax.WithTimeout(600000 * time.Millisecond),
gax.WithRetry(func() gax.Retryer {
return gax.OnHTTPCodes(gax.Backoff{
Initial: 100 * time.Millisecond,
Max: 60000 * time.Millisecond,
Multiplier: 1.30,
},
http.StatusGatewayTimeout,
http.StatusServiceUnavailable)
}),
},
GetIamPolicy: []gax.CallOption{
gax.WithTimeout(600000 * time.Millisecond),
gax.WithRetry(func() gax.Retryer {
return gax.OnHTTPCodes(gax.Backoff{
Initial: 100 * time.Millisecond,
Max: 60000 * time.Millisecond,
Multiplier: 1.30,
},
http.StatusGatewayTimeout,
http.StatusServiceUnavailable)
}),
},
Insert: []gax.CallOption{
gax.WithTimeout(600000 * time.Millisecond),
},
List: []gax.CallOption{
gax.WithTimeout(600000 * time.Millisecond),
gax.WithRetry(func() gax.Retryer {
return gax.OnHTTPCodes(gax.Backoff{
Initial: 100 * time.Millisecond,
Max: 60000 * time.Millisecond,
Multiplier: 1.30,
},
http.StatusGatewayTimeout,
http.StatusServiceUnavailable)
}),
},
SetIamPolicy: []gax.CallOption{
gax.WithTimeout(600000 * time.Millisecond),
},
SetLabels: []gax.CallOption{
gax.WithTimeout(600000 * time.Millisecond),
},
TestIamPermissions: []gax.CallOption{
gax.WithTimeout(600000 * time.Millisecond),
},
}
}
// internalInstantSnapshotsClient is an interface that defines the methods available from Google Compute Engine API.
type internalInstantSnapshotsClient interface {
Close() error
setGoogleClientInfo(...string)
Connection() *grpc.ClientConn
AggregatedList(context.Context, *computepb.AggregatedListInstantSnapshotsRequest, ...gax.CallOption) *InstantSnapshotsScopedListPairIterator
Delete(context.Context, *computepb.DeleteInstantSnapshotRequest, ...gax.CallOption) (*Operation, error)
Get(context.Context, *computepb.GetInstantSnapshotRequest, ...gax.CallOption) (*computepb.InstantSnapshot, error)
GetIamPolicy(context.Context, *computepb.GetIamPolicyInstantSnapshotRequest, ...gax.CallOption) (*computepb.Policy, error)
Insert(context.Context, *computepb.InsertInstantSnapshotRequest, ...gax.CallOption) (*Operation, error)
List(context.Context, *computepb.ListInstantSnapshotsRequest, ...gax.CallOption) *InstantSnapshotIterator
SetIamPolicy(context.Context, *computepb.SetIamPolicyInstantSnapshotRequest, ...gax.CallOption) (*computepb.Policy, error)
SetLabels(context.Context, *computepb.SetLabelsInstantSnapshotRequest, ...gax.CallOption) (*Operation, error)
TestIamPermissions(context.Context, *computepb.TestIamPermissionsInstantSnapshotRequest, ...gax.CallOption) (*computepb.TestPermissionsResponse, error)
}
// InstantSnapshotsClient is a client for interacting with Google Compute Engine API.
// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls.
//
// The InstantSnapshots API.
type InstantSnapshotsClient struct {
// The internal transport-dependent client.
internalClient internalInstantSnapshotsClient
// The call options for this service.
CallOptions *InstantSnapshotsCallOptions
}
// Wrapper methods routed to the internal client.
// Close closes the connection to the API service. The user should invoke this when
// the client is no longer required.
func (c *InstantSnapshotsClient) Close() error {
return c.internalClient.Close()
}
// setGoogleClientInfo sets the name and version of the application in
// the `x-goog-api-client` header passed on each request. Intended for
// use by Google-written clients.
func (c *InstantSnapshotsClient) setGoogleClientInfo(keyval ...string) {
c.internalClient.setGoogleClientInfo(keyval...)
}
// Connection returns a connection to the API service.
//
// Deprecated: Connections are now pooled so this method does not always
// return the same resource.
func (c *InstantSnapshotsClient) Connection() *grpc.ClientConn {
return c.internalClient.Connection()
}
// AggregatedList retrieves an aggregated list of instantSnapshots. To prevent failure, Google recommends that you set the returnPartialSuccess parameter to true.
func (c *InstantSnapshotsClient) AggregatedList(ctx context.Context, req *computepb.AggregatedListInstantSnapshotsRequest, opts ...gax.CallOption) *InstantSnapshotsScopedListPairIterator {
return c.internalClient.AggregatedList(ctx, req, opts...)
}
// Delete deletes the specified InstantSnapshot resource. Keep in mind that deleting a single instantSnapshot might not necessarily delete all the data on that instantSnapshot. If any data on the instantSnapshot that is marked for deletion is needed for subsequent instantSnapshots, the data will be moved to the next corresponding instantSnapshot. For more information, see Deleting instantSnapshots.
func (c *InstantSnapshotsClient) Delete(ctx context.Context, req *computepb.DeleteInstantSnapshotRequest, opts ...gax.CallOption) (*Operation, error) {
return c.internalClient.Delete(ctx, req, opts...)
}
// Get returns the specified InstantSnapshot resource in the specified zone.
func (c *InstantSnapshotsClient) Get(ctx context.Context, req *computepb.GetInstantSnapshotRequest, opts ...gax.CallOption) (*computepb.InstantSnapshot, error) {
return c.internalClient.Get(ctx, req, opts...)
}
// GetIamPolicy gets the access control policy for a resource. May be empty if no such policy or resource exists.
func (c *InstantSnapshotsClient) GetIamPolicy(ctx context.Context, req *computepb.GetIamPolicyInstantSnapshotRequest, opts ...gax.CallOption) (*computepb.Policy, error) {
return c.internalClient.GetIamPolicy(ctx, req, opts...)
}
// Insert creates an instant snapshot in the specified zone.
func (c *InstantSnapshotsClient) Insert(ctx context.Context, req *computepb.InsertInstantSnapshotRequest, opts ...gax.CallOption) (*Operation, error) {
return c.internalClient.Insert(ctx, req, opts...)
}
// List retrieves the list of InstantSnapshot resources contained within the specified zone.
func (c *InstantSnapshotsClient) List(ctx context.Context, req *computepb.ListInstantSnapshotsRequest, opts ...gax.CallOption) *InstantSnapshotIterator {
return c.internalClient.List(ctx, req, opts...)
}
// SetIamPolicy sets the access control policy on the specified resource. Replaces any existing policy.
func (c *InstantSnapshotsClient) SetIamPolicy(ctx context.Context, req *computepb.SetIamPolicyInstantSnapshotRequest, opts ...gax.CallOption) (*computepb.Policy, error) {
return c.internalClient.SetIamPolicy(ctx, req, opts...)
}
// SetLabels sets the labels on a instantSnapshot in the given zone. To learn more about labels, read the Labeling Resources documentation.
func (c *InstantSnapshotsClient) SetLabels(ctx context.Context, req *computepb.SetLabelsInstantSnapshotRequest, opts ...gax.CallOption) (*Operation, error) {
return c.internalClient.SetLabels(ctx, req, opts...)
}
// TestIamPermissions returns permissions that a caller has on the specified resource.
func (c *InstantSnapshotsClient) TestIamPermissions(ctx context.Context, req *computepb.TestIamPermissionsInstantSnapshotRequest, opts ...gax.CallOption) (*computepb.TestPermissionsResponse, error) {
return c.internalClient.TestIamPermissions(ctx, req, opts...)
}
// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls.
type instantSnapshotsRESTClient struct {
// The http endpoint to connect to.
endpoint string
// The http client.
httpClient *http.Client
// operationClient is used to call the operation-specific management service.
operationClient *ZoneOperationsClient
// The x-goog-* headers to be sent with each request.
xGoogHeaders []string
// Points back to the CallOptions field of the containing InstantSnapshotsClient
CallOptions **InstantSnapshotsCallOptions
}
// NewInstantSnapshotsRESTClient creates a new instant snapshots rest client.
//
// The InstantSnapshots API.
func NewInstantSnapshotsRESTClient(ctx context.Context, opts ...option.ClientOption) (*InstantSnapshotsClient, error) {
clientOpts := append(defaultInstantSnapshotsRESTClientOptions(), opts...)
httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...)
if err != nil {
return nil, err
}
callOpts := defaultInstantSnapshotsRESTCallOptions()
c := &instantSnapshotsRESTClient{
endpoint: endpoint,
httpClient: httpClient,
CallOptions: &callOpts,
}
c.setGoogleClientInfo()
o := []option.ClientOption{
option.WithHTTPClient(httpClient),
option.WithEndpoint(endpoint),
}
opC, err := NewZoneOperationsRESTClient(ctx, o...)
if err != nil {
return nil, err
}
c.operationClient = opC
return &InstantSnapshotsClient{internalClient: c, CallOptions: callOpts}, nil
}
func defaultInstantSnapshotsRESTClientOptions() []option.ClientOption {
return []option.ClientOption{
internaloption.WithDefaultEndpoint("https://compute.googleapis.com"),
internaloption.WithDefaultEndpointTemplate("https://compute.UNIVERSE_DOMAIN"),
internaloption.WithDefaultMTLSEndpoint("https://compute.mtls.googleapis.com"),
internaloption.WithDefaultUniverseDomain("googleapis.com"),
internaloption.WithDefaultAudience("https://compute.googleapis.com/"),
internaloption.WithDefaultScopes(DefaultAuthScopes()...),
}
}
// setGoogleClientInfo sets the name and version of the application in
// the `x-goog-api-client` header passed on each request. Intended for
// use by Google-written clients.
func (c *instantSnapshotsRESTClient) setGoogleClientInfo(keyval ...string) {
kv := append([]string{"gl-go", gax.GoVersion}, keyval...)
kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN")
c.xGoogHeaders = []string{"x-goog-api-client", gax.XGoogHeader(kv...)}
}
// Close closes the connection to the API service. The user should invoke this when
// the client is no longer required.
func (c *instantSnapshotsRESTClient) Close() error {
// Replace httpClient with nil to force cleanup.
c.httpClient = nil
if err := c.operationClient.Close(); err != nil {
return err
}
return nil
}
// Connection returns a connection to the API service.
//
// Deprecated: This method always returns nil.
func (c *instantSnapshotsRESTClient) Connection() *grpc.ClientConn {
return nil
}
// AggregatedList retrieves an aggregated list of instantSnapshots. To prevent failure, Google recommends that you set the returnPartialSuccess parameter to true.
func (c *instantSnapshotsRESTClient) AggregatedList(ctx context.Context, req *computepb.AggregatedListInstantSnapshotsRequest, opts ...gax.CallOption) *InstantSnapshotsScopedListPairIterator {
it := &InstantSnapshotsScopedListPairIterator{}
req = proto.Clone(req).(*computepb.AggregatedListInstantSnapshotsRequest)
unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true}
it.InternalFetch = func(pageSize int, pageToken string) ([]InstantSnapshotsScopedListPair, string, error) {
resp := &computepb.InstantSnapshotAggregatedList{}
if pageToken != "" {
req.PageToken = proto.String(pageToken)
}
if pageSize > math.MaxInt32 {
req.MaxResults = proto.Uint32(math.MaxInt32)
} else if pageSize != 0 {
req.MaxResults = proto.Uint32(uint32(pageSize))
}
baseUrl, err := url.Parse(c.endpoint)
if err != nil {
return nil, "", err
}
baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/aggregated/instantSnapshots", req.GetProject())
params := url.Values{}
if req != nil && req.Filter != nil {
params.Add("filter", fmt.Sprintf("%v", req.GetFilter()))
}
if req != nil && req.IncludeAllScopes != nil {
params.Add("includeAllScopes", fmt.Sprintf("%v", req.GetIncludeAllScopes()))
}
if req != nil && req.MaxResults != nil {
params.Add("maxResults", fmt.Sprintf("%v", req.GetMaxResults()))
}
if req != nil && req.OrderBy != nil {
params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy()))
}
if req != nil && req.PageToken != nil {
params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken()))
}
if req != nil && req.ReturnPartialSuccess != nil {
params.Add("returnPartialSuccess", fmt.Sprintf("%v", req.GetReturnPartialSuccess()))
}
if req != nil && req.ServiceProjectNumber != nil {
params.Add("serviceProjectNumber", fmt.Sprintf("%v", req.GetServiceProjectNumber()))
}
baseUrl.RawQuery = params.Encode()
// Build HTTP headers from client and context metadata.
hds := append(c.xGoogHeaders, "Content-Type", "application/json")
headers := gax.BuildHeaders(ctx, hds...)
e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
if settings.Path != "" {
baseUrl.Path = settings.Path
}
httpReq, err := http.NewRequest("GET", baseUrl.String(), nil)
if err != nil {
return err
}
httpReq.Header = headers
httpRsp, err := c.httpClient.Do(httpReq)
if err != nil {
return err
}
defer httpRsp.Body.Close()
if err = googleapi.CheckResponse(httpRsp); err != nil {
return err
}
buf, err := io.ReadAll(httpRsp.Body)
if err != nil {
return err
}
if err := unm.Unmarshal(buf, resp); err != nil {
return err
}
return nil
}, opts...)
if e != nil {
return nil, "", e
}
it.Response = resp
elems := make([]InstantSnapshotsScopedListPair, 0, len(resp.GetItems()))
for k, v := range resp.GetItems() {
elems = append(elems, InstantSnapshotsScopedListPair{k, v})
}
sort.Slice(elems, func(i, j int) bool { return elems[i].Key < elems[j].Key })
return elems, resp.GetNextPageToken(), nil
}
fetch := func(pageSize int, pageToken string) (string, error) {
items, nextPageToken, err := it.InternalFetch(pageSize, pageToken)
if err != nil {
return "", err
}
it.items = append(it.items, items...)
return nextPageToken, nil
}
it.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf)
it.pageInfo.MaxSize = int(req.GetMaxResults())
it.pageInfo.Token = req.GetPageToken()
return it
}
// Delete deletes the specified InstantSnapshot resource. Keep in mind that deleting a single instantSnapshot might not necessarily delete all the data on that instantSnapshot. If any data on the instantSnapshot that is marked for deletion is needed for subsequent instantSnapshots, the data will be moved to the next corresponding instantSnapshot. For more information, see Deleting instantSnapshots.
func (c *instantSnapshotsRESTClient) Delete(ctx context.Context, req *computepb.DeleteInstantSnapshotRequest, opts ...gax.CallOption) (*Operation, error) {
baseUrl, err := url.Parse(c.endpoint)
if err != nil {
return nil, err
}
baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/instantSnapshots/%v", req.GetProject(), req.GetZone(), req.GetInstantSnapshot())
params := url.Values{}
if req != nil && req.RequestId != nil {
params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId()))
}
baseUrl.RawQuery = params.Encode()
// Build HTTP headers from client and context metadata.
hds := []string{"x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "zone", url.QueryEscape(req.GetZone()), "instant_snapshot", url.QueryEscape(req.GetInstantSnapshot()))}
hds = append(c.xGoogHeaders, hds...)
hds = append(hds, "Content-Type", "application/json")
headers := gax.BuildHeaders(ctx, hds...)
opts = append((*c.CallOptions).Delete[0:len((*c.CallOptions).Delete):len((*c.CallOptions).Delete)], opts...)
unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true}
resp := &computepb.Operation{}
e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
if settings.Path != "" {
baseUrl.Path = settings.Path
}
httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil)
if err != nil {
return err
}
httpReq = httpReq.WithContext(ctx)
httpReq.Header = headers
httpRsp, err := c.httpClient.Do(httpReq)
if err != nil {
return err
}
defer httpRsp.Body.Close()
if err = googleapi.CheckResponse(httpRsp); err != nil {
return err
}
buf, err := io.ReadAll(httpRsp.Body)
if err != nil {
return err
}
if err := unm.Unmarshal(buf, resp); err != nil {
return err
}
return nil
}, opts...)
if e != nil {
return nil, e
}
op := &Operation{
&zoneOperationsHandle{
c: c.operationClient,
proto: resp,
project: req.GetProject(),
zone: req.GetZone(),
},
}
return op, nil
}
// Get returns the specified InstantSnapshot resource in the specified zone.
func (c *instantSnapshotsRESTClient) Get(ctx context.Context, req *computepb.GetInstantSnapshotRequest, opts ...gax.CallOption) (*computepb.InstantSnapshot, error) {
baseUrl, err := url.Parse(c.endpoint)
if err != nil {
return nil, err
}
baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/instantSnapshots/%v", req.GetProject(), req.GetZone(), req.GetInstantSnapshot())
// Build HTTP headers from client and context metadata.
hds := []string{"x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "zone", url.QueryEscape(req.GetZone()), "instant_snapshot", url.QueryEscape(req.GetInstantSnapshot()))}
hds = append(c.xGoogHeaders, hds...)
hds = append(hds, "Content-Type", "application/json")
headers := gax.BuildHeaders(ctx, hds...)
opts = append((*c.CallOptions).Get[0:len((*c.CallOptions).Get):len((*c.CallOptions).Get)], opts...)
unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true}
resp := &computepb.InstantSnapshot{}
e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
if settings.Path != "" {
baseUrl.Path = settings.Path
}
httpReq, err := http.NewRequest("GET", baseUrl.String(), nil)
if err != nil {
return err
}
httpReq = httpReq.WithContext(ctx)
httpReq.Header = headers
httpRsp, err := c.httpClient.Do(httpReq)
if err != nil {
return err
}
defer httpRsp.Body.Close()
if err = googleapi.CheckResponse(httpRsp); err != nil {
return err
}
buf, err := io.ReadAll(httpRsp.Body)
if err != nil {
return err
}
if err := unm.Unmarshal(buf, resp); err != nil {
return err
}
return nil
}, opts...)
if e != nil {
return nil, e
}
return resp, nil
}
// GetIamPolicy gets the access control policy for a resource. May be empty if no such policy or resource exists.
func (c *instantSnapshotsRESTClient) GetIamPolicy(ctx context.Context, req *computepb.GetIamPolicyInstantSnapshotRequest, opts ...gax.CallOption) (*computepb.Policy, error) {
baseUrl, err := url.Parse(c.endpoint)
if err != nil {
return nil, err
}
baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/instantSnapshots/%v/getIamPolicy", req.GetProject(), req.GetZone(), req.GetResource())
params := url.Values{}
if req != nil && req.OptionsRequestedPolicyVersion != nil {
params.Add("optionsRequestedPolicyVersion", fmt.Sprintf("%v", req.GetOptionsRequestedPolicyVersion()))
}
baseUrl.RawQuery = params.Encode()
// Build HTTP headers from client and context metadata.
hds := []string{"x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "zone", url.QueryEscape(req.GetZone()), "resource", url.QueryEscape(req.GetResource()))}
hds = append(c.xGoogHeaders, hds...)
hds = append(hds, "Content-Type", "application/json")
headers := gax.BuildHeaders(ctx, hds...)
opts = append((*c.CallOptions).GetIamPolicy[0:len((*c.CallOptions).GetIamPolicy):len((*c.CallOptions).GetIamPolicy)], opts...)
unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true}
resp := &computepb.Policy{}
e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
if settings.Path != "" {
baseUrl.Path = settings.Path
}
httpReq, err := http.NewRequest("GET", baseUrl.String(), nil)
if err != nil {
return err
}
httpReq = httpReq.WithContext(ctx)
httpReq.Header = headers
httpRsp, err := c.httpClient.Do(httpReq)
if err != nil {
return err
}
defer httpRsp.Body.Close()
if err = googleapi.CheckResponse(httpRsp); err != nil {
return err
}
buf, err := io.ReadAll(httpRsp.Body)
if err != nil {
return err
}
if err := unm.Unmarshal(buf, resp); err != nil {
return err
}
return nil
}, opts...)
if e != nil {
return nil, e
}
return resp, nil
}
// Insert creates an instant snapshot in the specified zone.
func (c *instantSnapshotsRESTClient) Insert(ctx context.Context, req *computepb.InsertInstantSnapshotRequest, opts ...gax.CallOption) (*Operation, error) {
m := protojson.MarshalOptions{AllowPartial: true}
body := req.GetInstantSnapshotResource()
jsonReq, err := m.Marshal(body)
if err != nil {
return nil, err
}
baseUrl, err := url.Parse(c.endpoint)
if err != nil {
return nil, err
}
baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/instantSnapshots", req.GetProject(), req.GetZone())
params := url.Values{}
if req != nil && req.RequestId != nil {
params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId()))
}
baseUrl.RawQuery = params.Encode()
// Build HTTP headers from client and context metadata.
hds := []string{"x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "zone", url.QueryEscape(req.GetZone()))}
hds = append(c.xGoogHeaders, hds...)
hds = append(hds, "Content-Type", "application/json")
headers := gax.BuildHeaders(ctx, hds...)
opts = append((*c.CallOptions).Insert[0:len((*c.CallOptions).Insert):len((*c.CallOptions).Insert)], opts...)
unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true}
resp := &computepb.Operation{}
e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
if settings.Path != "" {
baseUrl.Path = settings.Path
}
httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq))
if err != nil {
return err
}
httpReq = httpReq.WithContext(ctx)
httpReq.Header = headers
httpRsp, err := c.httpClient.Do(httpReq)
if err != nil {
return err
}
defer httpRsp.Body.Close()
if err = googleapi.CheckResponse(httpRsp); err != nil {
return err
}
buf, err := io.ReadAll(httpRsp.Body)
if err != nil {
return err
}
if err := unm.Unmarshal(buf, resp); err != nil {
return err
}
return nil
}, opts...)
if e != nil {
return nil, e
}
op := &Operation{
&zoneOperationsHandle{
c: c.operationClient,
proto: resp,
project: req.GetProject(),
zone: req.GetZone(),
},
}
return op, nil
}
// List retrieves the list of InstantSnapshot resources contained within the specified zone.
func (c *instantSnapshotsRESTClient) List(ctx context.Context, req *computepb.ListInstantSnapshotsRequest, opts ...gax.CallOption) *InstantSnapshotIterator {
it := &InstantSnapshotIterator{}
req = proto.Clone(req).(*computepb.ListInstantSnapshotsRequest)
unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true}
it.InternalFetch = func(pageSize int, pageToken string) ([]*computepb.InstantSnapshot, string, error) {
resp := &computepb.InstantSnapshotList{}
if pageToken != "" {
req.PageToken = proto.String(pageToken)
}
if pageSize > math.MaxInt32 {
req.MaxResults = proto.Uint32(math.MaxInt32)
} else if pageSize != 0 {
req.MaxResults = proto.Uint32(uint32(pageSize))
}
baseUrl, err := url.Parse(c.endpoint)
if err != nil {
return nil, "", err
}
baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/instantSnapshots", req.GetProject(), req.GetZone())
params := url.Values{}
if req != nil && req.Filter != nil {
params.Add("filter", fmt.Sprintf("%v", req.GetFilter()))
}
if req != nil && req.MaxResults != nil {
params.Add("maxResults", fmt.Sprintf("%v", req.GetMaxResults()))
}
if req != nil && req.OrderBy != nil {
params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy()))
}
if req != nil && req.PageToken != nil {
params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken()))
}
if req != nil && req.ReturnPartialSuccess != nil {
params.Add("returnPartialSuccess", fmt.Sprintf("%v", req.GetReturnPartialSuccess()))
}
baseUrl.RawQuery = params.Encode()
// Build HTTP headers from client and context metadata.
hds := append(c.xGoogHeaders, "Content-Type", "application/json")
headers := gax.BuildHeaders(ctx, hds...)
e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
if settings.Path != "" {
baseUrl.Path = settings.Path
}
httpReq, err := http.NewRequest("GET", baseUrl.String(), nil)
if err != nil {
return err
}
httpReq.Header = headers
httpRsp, err := c.httpClient.Do(httpReq)
if err != nil {
return err
}
defer httpRsp.Body.Close()
if err = googleapi.CheckResponse(httpRsp); err != nil {
return err
}
buf, err := io.ReadAll(httpRsp.Body)
if err != nil {
return err
}
if err := unm.Unmarshal(buf, resp); err != nil {
return err
}
return nil
}, opts...)
if e != nil {
return nil, "", e
}
it.Response = resp
return resp.GetItems(), resp.GetNextPageToken(), nil
}
fetch := func(pageSize int, pageToken string) (string, error) {
items, nextPageToken, err := it.InternalFetch(pageSize, pageToken)
if err != nil {
return "", err
}
it.items = append(it.items, items...)
return nextPageToken, nil
}
it.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf)
it.pageInfo.MaxSize = int(req.GetMaxResults())
it.pageInfo.Token = req.GetPageToken()
return it
}
// SetIamPolicy sets the access control policy on the specified resource. Replaces any existing policy.
func (c *instantSnapshotsRESTClient) SetIamPolicy(ctx context.Context, req *computepb.SetIamPolicyInstantSnapshotRequest, opts ...gax.CallOption) (*computepb.Policy, error) {
m := protojson.MarshalOptions{AllowPartial: true}
body := req.GetZoneSetPolicyRequestResource()
jsonReq, err := m.Marshal(body)
if err != nil {
return nil, err
}
baseUrl, err := url.Parse(c.endpoint)
if err != nil {
return nil, err
}
baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/instantSnapshots/%v/setIamPolicy", req.GetProject(), req.GetZone(), req.GetResource())
// Build HTTP headers from client and context metadata.
hds := []string{"x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "zone", url.QueryEscape(req.GetZone()), "resource", url.QueryEscape(req.GetResource()))}
hds = append(c.xGoogHeaders, hds...)
hds = append(hds, "Content-Type", "application/json")
headers := gax.BuildHeaders(ctx, hds...)
opts = append((*c.CallOptions).SetIamPolicy[0:len((*c.CallOptions).SetIamPolicy):len((*c.CallOptions).SetIamPolicy)], opts...)
unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true}
resp := &computepb.Policy{}
e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
if settings.Path != "" {
baseUrl.Path = settings.Path
}
httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq))
if err != nil {
return err
}
httpReq = httpReq.WithContext(ctx)
httpReq.Header = headers
httpRsp, err := c.httpClient.Do(httpReq)
if err != nil {
return err
}
defer httpRsp.Body.Close()
if err = googleapi.CheckResponse(httpRsp); err != nil {
return err
}
buf, err := io.ReadAll(httpRsp.Body)
if err != nil {
return err
}
if err := unm.Unmarshal(buf, resp); err != nil {
return err
}
return nil
}, opts...)
if e != nil {
return nil, e
}
return resp, nil
}
// SetLabels sets the labels on a instantSnapshot in the given zone. To learn more about labels, read the Labeling Resources documentation.
func (c *instantSnapshotsRESTClient) SetLabels(ctx context.Context, req *computepb.SetLabelsInstantSnapshotRequest, opts ...gax.CallOption) (*Operation, error) {
m := protojson.MarshalOptions{AllowPartial: true}
body := req.GetZoneSetLabelsRequestResource()
jsonReq, err := m.Marshal(body)
if err != nil {
return nil, err
}
baseUrl, err := url.Parse(c.endpoint)
if err != nil {
return nil, err
}
baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/instantSnapshots/%v/setLabels", req.GetProject(), req.GetZone(), req.GetResource())
params := url.Values{}
if req != nil && req.RequestId != nil {
params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId()))
}
baseUrl.RawQuery = params.Encode()
// Build HTTP headers from client and context metadata.
hds := []string{"x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "zone", url.QueryEscape(req.GetZone()), "resource", url.QueryEscape(req.GetResource()))}
hds = append(c.xGoogHeaders, hds...)
hds = append(hds, "Content-Type", "application/json")
headers := gax.BuildHeaders(ctx, hds...)
opts = append((*c.CallOptions).SetLabels[0:len((*c.CallOptions).SetLabels):len((*c.CallOptions).SetLabels)], opts...)
unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true}
resp := &computepb.Operation{}
e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
if settings.Path != "" {
baseUrl.Path = settings.Path
}
httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq))
if err != nil {
return err
}
httpReq = httpReq.WithContext(ctx)
httpReq.Header = headers
httpRsp, err := c.httpClient.Do(httpReq)
if err != nil {
return err
}
defer httpRsp.Body.Close()
if err = googleapi.CheckResponse(httpRsp); err != nil {
return err
}
buf, err := io.ReadAll(httpRsp.Body)
if err != nil {
return err
}
if err := unm.Unmarshal(buf, resp); err != nil {
return err
}
return nil
}, opts...)
if e != nil {
return nil, e
}
op := &Operation{
&zoneOperationsHandle{
c: c.operationClient,
proto: resp,
project: req.GetProject(),
zone: req.GetZone(),
},
}
return op, nil
}
// TestIamPermissions returns permissions that a caller has on the specified resource.
func (c *instantSnapshotsRESTClient) TestIamPermissions(ctx context.Context, req *computepb.TestIamPermissionsInstantSnapshotRequest, opts ...gax.CallOption) (*computepb.TestPermissionsResponse, error) {
m := protojson.MarshalOptions{AllowPartial: true}
body := req.GetTestPermissionsRequestResource()
jsonReq, err := m.Marshal(body)
if err != nil {
return nil, err
}
baseUrl, err := url.Parse(c.endpoint)
if err != nil {
return nil, err
}
baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/instantSnapshots/%v/testIamPermissions", req.GetProject(), req.GetZone(), req.GetResource())
// Build HTTP headers from client and context metadata.
hds := []string{"x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "zone", url.QueryEscape(req.GetZone()), "resource", url.QueryEscape(req.GetResource()))}
hds = append(c.xGoogHeaders, hds...)
hds = append(hds, "Content-Type", "application/json")
headers := gax.BuildHeaders(ctx, hds...)
opts = append((*c.CallOptions).TestIamPermissions[0:len((*c.CallOptions).TestIamPermissions):len((*c.CallOptions).TestIamPermissions)], opts...)
unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true}
resp := &computepb.TestPermissionsResponse{}
e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
if settings.Path != "" {
baseUrl.Path = settings.Path
}
httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq))
if err != nil {
return err
}
httpReq = httpReq.WithContext(ctx)
httpReq.Header = headers
httpRsp, err := c.httpClient.Do(httpReq)
if err != nil {
return err
}
defer httpRsp.Body.Close()
if err = googleapi.CheckResponse(httpRsp); err != nil {
return err
}
buf, err := io.ReadAll(httpRsp.Body)
if err != nil {
return err
}
if err := unm.Unmarshal(buf, resp); err != nil {
return err
}
return nil
}, opts...)
if e != nil {
return nil, e
}
return resp, nil
}

View file

@ -154,7 +154,7 @@ func (c *InterconnectAttachmentsClient) Connection() *grpc.ClientConn {
return c.internalClient.Connection()
}
// AggregatedList retrieves an aggregated list of interconnect attachments.
// AggregatedList retrieves an aggregated list of interconnect attachments. To prevent failure, Google recommends that you set the returnPartialSuccess parameter to true.
func (c *InterconnectAttachmentsClient) AggregatedList(ctx context.Context, req *computepb.AggregatedListInterconnectAttachmentsRequest, opts ...gax.CallOption) *InterconnectAttachmentsScopedListPairIterator {
return c.internalClient.AggregatedList(ctx, req, opts...)
}
@ -276,7 +276,7 @@ func (c *interconnectAttachmentsRESTClient) Connection() *grpc.ClientConn {
return nil
}
// AggregatedList retrieves an aggregated list of interconnect attachments.
// AggregatedList retrieves an aggregated list of interconnect attachments. To prevent failure, Google recommends that you set the returnPartialSuccess parameter to true.
func (c *interconnectAttachmentsRESTClient) AggregatedList(ctx context.Context, req *computepb.AggregatedListInterconnectAttachmentsRequest, opts ...gax.CallOption) *InterconnectAttachmentsScopedListPairIterator {
it := &InterconnectAttachmentsScopedListPairIterator{}
req = proto.Clone(req).(*computepb.AggregatedListInterconnectAttachmentsRequest)

View file

@ -133,7 +133,7 @@ func (c *MachineTypesClient) Connection() *grpc.ClientConn {
return c.internalClient.Connection()
}
// AggregatedList retrieves an aggregated list of machine types.
// AggregatedList retrieves an aggregated list of machine types. To prevent failure, Google recommends that you set the returnPartialSuccess parameter to true.
func (c *MachineTypesClient) AggregatedList(ctx context.Context, req *computepb.AggregatedListMachineTypesRequest, opts ...gax.CallOption) *MachineTypesScopedListPairIterator {
return c.internalClient.AggregatedList(ctx, req, opts...)
}
@ -219,7 +219,7 @@ func (c *machineTypesRESTClient) Connection() *grpc.ClientConn {
return nil
}
// AggregatedList retrieves an aggregated list of machine types.
// AggregatedList retrieves an aggregated list of machine types. To prevent failure, Google recommends that you set the returnPartialSuccess parameter to true.
func (c *machineTypesRESTClient) AggregatedList(ctx context.Context, req *computepb.AggregatedListMachineTypesRequest, opts ...gax.CallOption) *MachineTypesScopedListPairIterator {
it := &MachineTypesScopedListPairIterator{}
req = proto.Clone(req).(*computepb.AggregatedListMachineTypesRequest)

View file

@ -173,7 +173,7 @@ func (c *NetworkAttachmentsClient) Connection() *grpc.ClientConn {
return c.internalClient.Connection()
}
// AggregatedList retrieves the list of all NetworkAttachment resources, regional and global, available to the specified project.
// AggregatedList retrieves the list of all NetworkAttachment resources, regional and global, available to the specified project. To prevent failure, Google recommends that you set the returnPartialSuccess parameter to true.
func (c *NetworkAttachmentsClient) AggregatedList(ctx context.Context, req *computepb.AggregatedListNetworkAttachmentsRequest, opts ...gax.CallOption) *NetworkAttachmentsScopedListPairIterator {
return c.internalClient.AggregatedList(ctx, req, opts...)
}
@ -305,7 +305,7 @@ func (c *networkAttachmentsRESTClient) Connection() *grpc.ClientConn {
return nil
}
// AggregatedList retrieves the list of all NetworkAttachment resources, regional and global, available to the specified project.
// AggregatedList retrieves the list of all NetworkAttachment resources, regional and global, available to the specified project. To prevent failure, Google recommends that you set the returnPartialSuccess parameter to true.
func (c *networkAttachmentsRESTClient) AggregatedList(ctx context.Context, req *computepb.AggregatedListNetworkAttachmentsRequest, opts ...gax.CallOption) *NetworkAttachmentsScopedListPairIterator {
it := &NetworkAttachmentsScopedListPairIterator{}
req = proto.Clone(req).(*computepb.AggregatedListNetworkAttachmentsRequest)

View file

@ -135,7 +135,7 @@ func (c *NetworkEdgeSecurityServicesClient) Connection() *grpc.ClientConn {
return c.internalClient.Connection()
}
// AggregatedList retrieves the list of all NetworkEdgeSecurityService resources available to the specified project.
// AggregatedList retrieves the list of all NetworkEdgeSecurityService resources available to the specified project. To prevent failure, Google recommends that you set the returnPartialSuccess parameter to true.
func (c *NetworkEdgeSecurityServicesClient) AggregatedList(ctx context.Context, req *computepb.AggregatedListNetworkEdgeSecurityServicesRequest, opts ...gax.CallOption) *NetworkEdgeSecurityServicesScopedListPairIterator {
return c.internalClient.AggregatedList(ctx, req, opts...)
}
@ -247,7 +247,7 @@ func (c *networkEdgeSecurityServicesRESTClient) Connection() *grpc.ClientConn {
return nil
}
// AggregatedList retrieves the list of all NetworkEdgeSecurityService resources available to the specified project.
// AggregatedList retrieves the list of all NetworkEdgeSecurityService resources available to the specified project. To prevent failure, Google recommends that you set the returnPartialSuccess parameter to true.
func (c *networkEdgeSecurityServicesRESTClient) AggregatedList(ctx context.Context, req *computepb.AggregatedListNetworkEdgeSecurityServicesRequest, opts ...gax.CallOption) *NetworkEdgeSecurityServicesScopedListPairIterator {
it := &NetworkEdgeSecurityServicesScopedListPairIterator{}
req = proto.Clone(req).(*computepb.AggregatedListNetworkEdgeSecurityServicesRequest)

View file

@ -164,7 +164,7 @@ func (c *NetworkEndpointGroupsClient) Connection() *grpc.ClientConn {
return c.internalClient.Connection()
}
// AggregatedList retrieves the list of network endpoint groups and sorts them by zone.
// AggregatedList retrieves the list of network endpoint groups and sorts them by zone. To prevent failure, Google recommends that you set the returnPartialSuccess parameter to true.
func (c *NetworkEndpointGroupsClient) AggregatedList(ctx context.Context, req *computepb.AggregatedListNetworkEndpointGroupsRequest, opts ...gax.CallOption) *NetworkEndpointGroupsScopedListPairIterator {
return c.internalClient.AggregatedList(ctx, req, opts...)
}
@ -296,7 +296,7 @@ func (c *networkEndpointGroupsRESTClient) Connection() *grpc.ClientConn {
return nil
}
// AggregatedList retrieves the list of network endpoint groups and sorts them by zone.
// AggregatedList retrieves the list of network endpoint groups and sorts them by zone. To prevent failure, Google recommends that you set the returnPartialSuccess parameter to true.
func (c *networkEndpointGroupsRESTClient) AggregatedList(ctx context.Context, req *computepb.AggregatedListNetworkEndpointGroupsRequest, opts ...gax.CallOption) *NetworkEndpointGroupsScopedListPairIterator {
it := &NetworkEndpointGroupsScopedListPairIterator{}
req = proto.Clone(req).(*computepb.AggregatedListNetworkEndpointGroupsRequest)

View file

@ -203,7 +203,7 @@ func (c *NodeGroupsClient) AddNodes(ctx context.Context, req *computepb.AddNodes
return c.internalClient.AddNodes(ctx, req, opts...)
}
// AggregatedList retrieves an aggregated list of node groups. Note: use nodeGroups.listNodes for more details about each group.
// AggregatedList retrieves an aggregated list of node groups. Note: use nodeGroups.listNodes for more details about each group. To prevent failure, Google recommends that you set the returnPartialSuccess parameter to true.
func (c *NodeGroupsClient) AggregatedList(ctx context.Context, req *computepb.AggregatedListNodeGroupsRequest, opts ...gax.CallOption) *NodeGroupsScopedListPairIterator {
return c.internalClient.AggregatedList(ctx, req, opts...)
}
@ -432,7 +432,7 @@ func (c *nodeGroupsRESTClient) AddNodes(ctx context.Context, req *computepb.AddN
return op, nil
}
// AggregatedList retrieves an aggregated list of node groups. Note: use nodeGroups.listNodes for more details about each group.
// AggregatedList retrieves an aggregated list of node groups. Note: use nodeGroups.listNodes for more details about each group. To prevent failure, Google recommends that you set the returnPartialSuccess parameter to true.
func (c *nodeGroupsRESTClient) AggregatedList(ctx context.Context, req *computepb.AggregatedListNodeGroupsRequest, opts ...gax.CallOption) *NodeGroupsScopedListPairIterator {
it := &NodeGroupsScopedListPairIterator{}
req = proto.Clone(req).(*computepb.AggregatedListNodeGroupsRequest)

View file

@ -168,7 +168,7 @@ func (c *NodeTemplatesClient) Connection() *grpc.ClientConn {
return c.internalClient.Connection()
}
// AggregatedList retrieves an aggregated list of node templates.
// AggregatedList retrieves an aggregated list of node templates. To prevent failure, Google recommends that you set the returnPartialSuccess parameter to true.
func (c *NodeTemplatesClient) AggregatedList(ctx context.Context, req *computepb.AggregatedListNodeTemplatesRequest, opts ...gax.CallOption) *NodeTemplatesScopedListPairIterator {
return c.internalClient.AggregatedList(ctx, req, opts...)
}
@ -295,7 +295,7 @@ func (c *nodeTemplatesRESTClient) Connection() *grpc.ClientConn {
return nil
}
// AggregatedList retrieves an aggregated list of node templates.
// AggregatedList retrieves an aggregated list of node templates. To prevent failure, Google recommends that you set the returnPartialSuccess parameter to true.
func (c *nodeTemplatesRESTClient) AggregatedList(ctx context.Context, req *computepb.AggregatedListNodeTemplatesRequest, opts ...gax.CallOption) *NodeTemplatesScopedListPairIterator {
it := &NodeTemplatesScopedListPairIterator{}
req = proto.Clone(req).(*computepb.AggregatedListNodeTemplatesRequest)

View file

@ -133,7 +133,7 @@ func (c *NodeTypesClient) Connection() *grpc.ClientConn {
return c.internalClient.Connection()
}
// AggregatedList retrieves an aggregated list of node types.
// AggregatedList retrieves an aggregated list of node types. To prevent failure, Google recommends that you set the returnPartialSuccess parameter to true.
func (c *NodeTypesClient) AggregatedList(ctx context.Context, req *computepb.AggregatedListNodeTypesRequest, opts ...gax.CallOption) *NodeTypesScopedListPairIterator {
return c.internalClient.AggregatedList(ctx, req, opts...)
}
@ -219,7 +219,7 @@ func (c *nodeTypesRESTClient) Connection() *grpc.ClientConn {
return nil
}
// AggregatedList retrieves an aggregated list of node types.
// AggregatedList retrieves an aggregated list of node types. To prevent failure, Google recommends that you set the returnPartialSuccess parameter to true.
func (c *nodeTypesRESTClient) AggregatedList(ctx context.Context, req *computepb.AggregatedListNodeTypesRequest, opts ...gax.CallOption) *NodeTypesScopedListPairIterator {
it := &NodeTypesScopedListPairIterator{}
req = proto.Clone(req).(*computepb.AggregatedListNodeTypesRequest)

View file

@ -154,7 +154,7 @@ func (c *PacketMirroringsClient) Connection() *grpc.ClientConn {
return c.internalClient.Connection()
}
// AggregatedList retrieves an aggregated list of packetMirrorings.
// AggregatedList retrieves an aggregated list of packetMirrorings. To prevent failure, Google recommends that you set the returnPartialSuccess parameter to true.
func (c *PacketMirroringsClient) AggregatedList(ctx context.Context, req *computepb.AggregatedListPacketMirroringsRequest, opts ...gax.CallOption) *PacketMirroringsScopedListPairIterator {
return c.internalClient.AggregatedList(ctx, req, opts...)
}
@ -276,7 +276,7 @@ func (c *packetMirroringsRESTClient) Connection() *grpc.ClientConn {
return nil
}
// AggregatedList retrieves an aggregated list of packetMirrorings.
// AggregatedList retrieves an aggregated list of packetMirrorings. To prevent failure, Google recommends that you set the returnPartialSuccess parameter to true.
func (c *packetMirroringsRESTClient) AggregatedList(ctx context.Context, req *computepb.AggregatedListPacketMirroringsRequest, opts ...gax.CallOption) *PacketMirroringsScopedListPairIterator {
it := &PacketMirroringsScopedListPairIterator{}
req = proto.Clone(req).(*computepb.AggregatedListPacketMirroringsRequest)

View file

@ -52,6 +52,7 @@ type ProjectsCallOptions struct {
ListXpnHosts []gax.CallOption
MoveDisk []gax.CallOption
MoveInstance []gax.CallOption
SetCloudArmorTier []gax.CallOption
SetCommonInstanceMetadata []gax.CallOption
SetDefaultNetworkTier []gax.CallOption
SetUsageExportBucket []gax.CallOption
@ -116,6 +117,9 @@ func defaultProjectsRESTCallOptions() *ProjectsCallOptions {
MoveInstance: []gax.CallOption{
gax.WithTimeout(600000 * time.Millisecond),
},
SetCloudArmorTier: []gax.CallOption{
gax.WithTimeout(600000 * time.Millisecond),
},
SetCommonInstanceMetadata: []gax.CallOption{
gax.WithTimeout(600000 * time.Millisecond),
},
@ -143,6 +147,7 @@ type internalProjectsClient interface {
ListXpnHosts(context.Context, *computepb.ListXpnHostsProjectsRequest, ...gax.CallOption) *ProjectIterator
MoveDisk(context.Context, *computepb.MoveDiskProjectRequest, ...gax.CallOption) (*Operation, error)
MoveInstance(context.Context, *computepb.MoveInstanceProjectRequest, ...gax.CallOption) (*Operation, error)
SetCloudArmorTier(context.Context, *computepb.SetCloudArmorTierProjectRequest, ...gax.CallOption) (*Operation, error)
SetCommonInstanceMetadata(context.Context, *computepb.SetCommonInstanceMetadataProjectRequest, ...gax.CallOption) (*Operation, error)
SetDefaultNetworkTier(context.Context, *computepb.SetDefaultNetworkTierProjectRequest, ...gax.CallOption) (*Operation, error)
SetUsageExportBucket(context.Context, *computepb.SetUsageExportBucketProjectRequest, ...gax.CallOption) (*Operation, error)
@ -233,6 +238,11 @@ func (c *ProjectsClient) MoveInstance(ctx context.Context, req *computepb.MoveIn
return c.internalClient.MoveInstance(ctx, req, opts...)
}
// SetCloudArmorTier sets the Cloud Armor tier of the project. To set ENTERPRISE or above the billing account of the project must be subscribed to Cloud Armor Enterprise. See Subscribing to Cloud Armor Enterprise for more information.
func (c *ProjectsClient) SetCloudArmorTier(ctx context.Context, req *computepb.SetCloudArmorTierProjectRequest, opts ...gax.CallOption) (*Operation, error) {
return c.internalClient.SetCloudArmorTier(ctx, req, opts...)
}
// SetCommonInstanceMetadata sets metadata common to all instances within the specified project using the data included in the request.
func (c *ProjectsClient) SetCommonInstanceMetadata(ctx context.Context, req *computepb.SetCommonInstanceMetadataProjectRequest, opts ...gax.CallOption) (*Operation, error) {
return c.internalClient.SetCommonInstanceMetadata(ctx, req, opts...)
@ -1087,6 +1097,82 @@ func (c *projectsRESTClient) MoveInstance(ctx context.Context, req *computepb.Mo
return op, nil
}
// SetCloudArmorTier sets the Cloud Armor tier of the project. To set ENTERPRISE or above the billing account of the project must be subscribed to Cloud Armor Enterprise. See Subscribing to Cloud Armor Enterprise for more information.
func (c *projectsRESTClient) SetCloudArmorTier(ctx context.Context, req *computepb.SetCloudArmorTierProjectRequest, opts ...gax.CallOption) (*Operation, error) {
m := protojson.MarshalOptions{AllowPartial: true}
body := req.GetProjectsSetCloudArmorTierRequestResource()
jsonReq, err := m.Marshal(body)
if err != nil {
return nil, err
}
baseUrl, err := url.Parse(c.endpoint)
if err != nil {
return nil, err
}
baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/setCloudArmorTier", req.GetProject())
params := url.Values{}
if req != nil && req.RequestId != nil {
params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId()))
}
baseUrl.RawQuery = params.Encode()
// Build HTTP headers from client and context metadata.
hds := []string{"x-goog-request-params", fmt.Sprintf("%s=%v", "project", url.QueryEscape(req.GetProject()))}
hds = append(c.xGoogHeaders, hds...)
hds = append(hds, "Content-Type", "application/json")
headers := gax.BuildHeaders(ctx, hds...)
opts = append((*c.CallOptions).SetCloudArmorTier[0:len((*c.CallOptions).SetCloudArmorTier):len((*c.CallOptions).SetCloudArmorTier)], opts...)
unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true}
resp := &computepb.Operation{}
e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
if settings.Path != "" {
baseUrl.Path = settings.Path
}
httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq))
if err != nil {
return err
}
httpReq = httpReq.WithContext(ctx)
httpReq.Header = headers
httpRsp, err := c.httpClient.Do(httpReq)
if err != nil {
return err
}
defer httpRsp.Body.Close()
if err = googleapi.CheckResponse(httpRsp); err != nil {
return err
}
buf, err := io.ReadAll(httpRsp.Body)
if err != nil {
return err
}
if err := unm.Unmarshal(buf, resp); err != nil {
return err
}
return nil
}, opts...)
if e != nil {
return nil, e
}
op := &Operation{
&globalOperationsHandle{
c: c.operationClient,
proto: resp,
project: req.GetProject(),
},
}
return op, nil
}
// SetCommonInstanceMetadata sets metadata common to all instances within the specified project using the data included in the request.
func (c *projectsRESTClient) SetCommonInstanceMetadata(ctx context.Context, req *computepb.SetCommonInstanceMetadataProjectRequest, opts ...gax.CallOption) (*Operation, error) {
m := protojson.MarshalOptions{AllowPartial: true}

View file

@ -159,7 +159,7 @@ func (c *PublicDelegatedPrefixesClient) Connection() *grpc.ClientConn {
return c.internalClient.Connection()
}
// AggregatedList lists all PublicDelegatedPrefix resources owned by the specific project across all scopes.
// AggregatedList lists all PublicDelegatedPrefix resources owned by the specific project across all scopes. To prevent failure, Google recommends that you set the returnPartialSuccess parameter to true.
func (c *PublicDelegatedPrefixesClient) AggregatedList(ctx context.Context, req *computepb.AggregatedListPublicDelegatedPrefixesRequest, opts ...gax.CallOption) *PublicDelegatedPrefixesScopedListPairIterator {
return c.internalClient.AggregatedList(ctx, req, opts...)
}
@ -286,7 +286,7 @@ func (c *publicDelegatedPrefixesRESTClient) Connection() *grpc.ClientConn {
return nil
}
// AggregatedList lists all PublicDelegatedPrefix resources owned by the specific project across all scopes.
// AggregatedList lists all PublicDelegatedPrefix resources owned by the specific project across all scopes. To prevent failure, Google recommends that you set the returnPartialSuccess parameter to true.
func (c *publicDelegatedPrefixesRESTClient) AggregatedList(ctx context.Context, req *computepb.AggregatedListPublicDelegatedPrefixesRequest, opts ...gax.CallOption) *PublicDelegatedPrefixesScopedListPairIterator {
it := &PublicDelegatedPrefixesScopedListPairIterator{}
req = proto.Clone(req).(*computepb.AggregatedListPublicDelegatedPrefixesRequest)

View file

@ -144,7 +144,7 @@ func (c *RegionCommitmentsClient) Connection() *grpc.ClientConn {
return c.internalClient.Connection()
}
// AggregatedList retrieves an aggregated list of commitments by region.
// AggregatedList retrieves an aggregated list of commitments by region. To prevent failure, Google recommends that you set the returnPartialSuccess parameter to true.
func (c *RegionCommitmentsClient) AggregatedList(ctx context.Context, req *computepb.AggregatedListRegionCommitmentsRequest, opts ...gax.CallOption) *CommitmentsScopedListPairIterator {
return c.internalClient.AggregatedList(ctx, req, opts...)
}
@ -256,7 +256,7 @@ func (c *regionCommitmentsRESTClient) Connection() *grpc.ClientConn {
return nil
}
// AggregatedList retrieves an aggregated list of commitments by region.
// AggregatedList retrieves an aggregated list of commitments by region. To prevent failure, Google recommends that you set the returnPartialSuccess parameter to true.
func (c *regionCommitmentsRESTClient) AggregatedList(ctx context.Context, req *computepb.AggregatedListRegionCommitmentsRequest, opts ...gax.CallOption) *CommitmentsScopedListPairIterator {
it := &CommitmentsScopedListPairIterator{}
req = proto.Clone(req).(*computepb.AggregatedListRegionCommitmentsRequest)

View file

@ -0,0 +1,848 @@
// Copyright 2024 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Code generated by protoc-gen-go_gapic. DO NOT EDIT.
package compute
import (
"bytes"
"context"
"fmt"
"io"
"math"
"net/http"
"net/url"
"time"
computepb "cloud.google.com/go/compute/apiv1/computepb"
gax "github.com/googleapis/gax-go/v2"
"google.golang.org/api/googleapi"
"google.golang.org/api/iterator"
"google.golang.org/api/option"
"google.golang.org/api/option/internaloption"
httptransport "google.golang.org/api/transport/http"
"google.golang.org/grpc"
"google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/proto"
)
var newRegionInstantSnapshotsClientHook clientHook
// RegionInstantSnapshotsCallOptions contains the retry settings for each method of RegionInstantSnapshotsClient.
type RegionInstantSnapshotsCallOptions struct {
Delete []gax.CallOption
Get []gax.CallOption
GetIamPolicy []gax.CallOption
Insert []gax.CallOption
List []gax.CallOption
SetIamPolicy []gax.CallOption
SetLabels []gax.CallOption
TestIamPermissions []gax.CallOption
}
func defaultRegionInstantSnapshotsRESTCallOptions() *RegionInstantSnapshotsCallOptions {
return &RegionInstantSnapshotsCallOptions{
Delete: []gax.CallOption{
gax.WithTimeout(600000 * time.Millisecond),
},
Get: []gax.CallOption{
gax.WithTimeout(600000 * time.Millisecond),
gax.WithRetry(func() gax.Retryer {
return gax.OnHTTPCodes(gax.Backoff{
Initial: 100 * time.Millisecond,
Max: 60000 * time.Millisecond,
Multiplier: 1.30,
},
http.StatusGatewayTimeout,
http.StatusServiceUnavailable)
}),
},
GetIamPolicy: []gax.CallOption{
gax.WithTimeout(600000 * time.Millisecond),
gax.WithRetry(func() gax.Retryer {
return gax.OnHTTPCodes(gax.Backoff{
Initial: 100 * time.Millisecond,
Max: 60000 * time.Millisecond,
Multiplier: 1.30,
},
http.StatusGatewayTimeout,
http.StatusServiceUnavailable)
}),
},
Insert: []gax.CallOption{
gax.WithTimeout(600000 * time.Millisecond),
},
List: []gax.CallOption{
gax.WithTimeout(600000 * time.Millisecond),
gax.WithRetry(func() gax.Retryer {
return gax.OnHTTPCodes(gax.Backoff{
Initial: 100 * time.Millisecond,
Max: 60000 * time.Millisecond,
Multiplier: 1.30,
},
http.StatusGatewayTimeout,
http.StatusServiceUnavailable)
}),
},
SetIamPolicy: []gax.CallOption{
gax.WithTimeout(600000 * time.Millisecond),
},
SetLabels: []gax.CallOption{
gax.WithTimeout(600000 * time.Millisecond),
},
TestIamPermissions: []gax.CallOption{
gax.WithTimeout(600000 * time.Millisecond),
},
}
}
// internalRegionInstantSnapshotsClient is an interface that defines the methods available from Google Compute Engine API.
type internalRegionInstantSnapshotsClient interface {
Close() error
setGoogleClientInfo(...string)
Connection() *grpc.ClientConn
Delete(context.Context, *computepb.DeleteRegionInstantSnapshotRequest, ...gax.CallOption) (*Operation, error)
Get(context.Context, *computepb.GetRegionInstantSnapshotRequest, ...gax.CallOption) (*computepb.InstantSnapshot, error)
GetIamPolicy(context.Context, *computepb.GetIamPolicyRegionInstantSnapshotRequest, ...gax.CallOption) (*computepb.Policy, error)
Insert(context.Context, *computepb.InsertRegionInstantSnapshotRequest, ...gax.CallOption) (*Operation, error)
List(context.Context, *computepb.ListRegionInstantSnapshotsRequest, ...gax.CallOption) *InstantSnapshotIterator
SetIamPolicy(context.Context, *computepb.SetIamPolicyRegionInstantSnapshotRequest, ...gax.CallOption) (*computepb.Policy, error)
SetLabels(context.Context, *computepb.SetLabelsRegionInstantSnapshotRequest, ...gax.CallOption) (*Operation, error)
TestIamPermissions(context.Context, *computepb.TestIamPermissionsRegionInstantSnapshotRequest, ...gax.CallOption) (*computepb.TestPermissionsResponse, error)
}
// RegionInstantSnapshotsClient is a client for interacting with Google Compute Engine API.
// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls.
//
// The RegionInstantSnapshots API.
type RegionInstantSnapshotsClient struct {
// The internal transport-dependent client.
internalClient internalRegionInstantSnapshotsClient
// The call options for this service.
CallOptions *RegionInstantSnapshotsCallOptions
}
// Wrapper methods routed to the internal client.
// Close closes the connection to the API service. The user should invoke this when
// the client is no longer required.
func (c *RegionInstantSnapshotsClient) Close() error {
return c.internalClient.Close()
}
// setGoogleClientInfo sets the name and version of the application in
// the `x-goog-api-client` header passed on each request. Intended for
// use by Google-written clients.
func (c *RegionInstantSnapshotsClient) setGoogleClientInfo(keyval ...string) {
c.internalClient.setGoogleClientInfo(keyval...)
}
// Connection returns a connection to the API service.
//
// Deprecated: Connections are now pooled so this method does not always
// return the same resource.
func (c *RegionInstantSnapshotsClient) Connection() *grpc.ClientConn {
return c.internalClient.Connection()
}
// Delete deletes the specified InstantSnapshot resource. Keep in mind that deleting a single instantSnapshot might not necessarily delete all the data on that instantSnapshot. If any data on the instantSnapshot that is marked for deletion is needed for subsequent instantSnapshots, the data will be moved to the next corresponding instantSnapshot. For more information, see Deleting instantSnapshots.
func (c *RegionInstantSnapshotsClient) Delete(ctx context.Context, req *computepb.DeleteRegionInstantSnapshotRequest, opts ...gax.CallOption) (*Operation, error) {
return c.internalClient.Delete(ctx, req, opts...)
}
// Get returns the specified InstantSnapshot resource in the specified region.
func (c *RegionInstantSnapshotsClient) Get(ctx context.Context, req *computepb.GetRegionInstantSnapshotRequest, opts ...gax.CallOption) (*computepb.InstantSnapshot, error) {
return c.internalClient.Get(ctx, req, opts...)
}
// GetIamPolicy gets the access control policy for a resource. May be empty if no such policy or resource exists.
func (c *RegionInstantSnapshotsClient) GetIamPolicy(ctx context.Context, req *computepb.GetIamPolicyRegionInstantSnapshotRequest, opts ...gax.CallOption) (*computepb.Policy, error) {
return c.internalClient.GetIamPolicy(ctx, req, opts...)
}
// Insert creates an instant snapshot in the specified region.
func (c *RegionInstantSnapshotsClient) Insert(ctx context.Context, req *computepb.InsertRegionInstantSnapshotRequest, opts ...gax.CallOption) (*Operation, error) {
return c.internalClient.Insert(ctx, req, opts...)
}
// List retrieves the list of InstantSnapshot resources contained within the specified region.
func (c *RegionInstantSnapshotsClient) List(ctx context.Context, req *computepb.ListRegionInstantSnapshotsRequest, opts ...gax.CallOption) *InstantSnapshotIterator {
return c.internalClient.List(ctx, req, opts...)
}
// SetIamPolicy sets the access control policy on the specified resource. Replaces any existing policy.
func (c *RegionInstantSnapshotsClient) SetIamPolicy(ctx context.Context, req *computepb.SetIamPolicyRegionInstantSnapshotRequest, opts ...gax.CallOption) (*computepb.Policy, error) {
return c.internalClient.SetIamPolicy(ctx, req, opts...)
}
// SetLabels sets the labels on a instantSnapshot in the given region. To learn more about labels, read the Labeling Resources documentation.
func (c *RegionInstantSnapshotsClient) SetLabels(ctx context.Context, req *computepb.SetLabelsRegionInstantSnapshotRequest, opts ...gax.CallOption) (*Operation, error) {
return c.internalClient.SetLabels(ctx, req, opts...)
}
// TestIamPermissions returns permissions that a caller has on the specified resource.
func (c *RegionInstantSnapshotsClient) TestIamPermissions(ctx context.Context, req *computepb.TestIamPermissionsRegionInstantSnapshotRequest, opts ...gax.CallOption) (*computepb.TestPermissionsResponse, error) {
return c.internalClient.TestIamPermissions(ctx, req, opts...)
}
// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls.
type regionInstantSnapshotsRESTClient struct {
// The http endpoint to connect to.
endpoint string
// The http client.
httpClient *http.Client
// operationClient is used to call the operation-specific management service.
operationClient *RegionOperationsClient
// The x-goog-* headers to be sent with each request.
xGoogHeaders []string
// Points back to the CallOptions field of the containing RegionInstantSnapshotsClient
CallOptions **RegionInstantSnapshotsCallOptions
}
// NewRegionInstantSnapshotsRESTClient creates a new region instant snapshots rest client.
//
// The RegionInstantSnapshots API.
func NewRegionInstantSnapshotsRESTClient(ctx context.Context, opts ...option.ClientOption) (*RegionInstantSnapshotsClient, error) {
clientOpts := append(defaultRegionInstantSnapshotsRESTClientOptions(), opts...)
httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...)
if err != nil {
return nil, err
}
callOpts := defaultRegionInstantSnapshotsRESTCallOptions()
c := &regionInstantSnapshotsRESTClient{
endpoint: endpoint,
httpClient: httpClient,
CallOptions: &callOpts,
}
c.setGoogleClientInfo()
o := []option.ClientOption{
option.WithHTTPClient(httpClient),
option.WithEndpoint(endpoint),
}
opC, err := NewRegionOperationsRESTClient(ctx, o...)
if err != nil {
return nil, err
}
c.operationClient = opC
return &RegionInstantSnapshotsClient{internalClient: c, CallOptions: callOpts}, nil
}
func defaultRegionInstantSnapshotsRESTClientOptions() []option.ClientOption {
return []option.ClientOption{
internaloption.WithDefaultEndpoint("https://compute.googleapis.com"),
internaloption.WithDefaultEndpointTemplate("https://compute.UNIVERSE_DOMAIN"),
internaloption.WithDefaultMTLSEndpoint("https://compute.mtls.googleapis.com"),
internaloption.WithDefaultUniverseDomain("googleapis.com"),
internaloption.WithDefaultAudience("https://compute.googleapis.com/"),
internaloption.WithDefaultScopes(DefaultAuthScopes()...),
}
}
// setGoogleClientInfo sets the name and version of the application in
// the `x-goog-api-client` header passed on each request. Intended for
// use by Google-written clients.
func (c *regionInstantSnapshotsRESTClient) setGoogleClientInfo(keyval ...string) {
kv := append([]string{"gl-go", gax.GoVersion}, keyval...)
kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN")
c.xGoogHeaders = []string{"x-goog-api-client", gax.XGoogHeader(kv...)}
}
// Close closes the connection to the API service. The user should invoke this when
// the client is no longer required.
func (c *regionInstantSnapshotsRESTClient) Close() error {
// Replace httpClient with nil to force cleanup.
c.httpClient = nil
if err := c.operationClient.Close(); err != nil {
return err
}
return nil
}
// Connection returns a connection to the API service.
//
// Deprecated: This method always returns nil.
func (c *regionInstantSnapshotsRESTClient) Connection() *grpc.ClientConn {
return nil
}
// Delete deletes the specified InstantSnapshot resource. Keep in mind that deleting a single instantSnapshot might not necessarily delete all the data on that instantSnapshot. If any data on the instantSnapshot that is marked for deletion is needed for subsequent instantSnapshots, the data will be moved to the next corresponding instantSnapshot. For more information, see Deleting instantSnapshots.
func (c *regionInstantSnapshotsRESTClient) Delete(ctx context.Context, req *computepb.DeleteRegionInstantSnapshotRequest, opts ...gax.CallOption) (*Operation, error) {
baseUrl, err := url.Parse(c.endpoint)
if err != nil {
return nil, err
}
baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/instantSnapshots/%v", req.GetProject(), req.GetRegion(), req.GetInstantSnapshot())
params := url.Values{}
if req != nil && req.RequestId != nil {
params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId()))
}
baseUrl.RawQuery = params.Encode()
// Build HTTP headers from client and context metadata.
hds := []string{"x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "region", url.QueryEscape(req.GetRegion()), "instant_snapshot", url.QueryEscape(req.GetInstantSnapshot()))}
hds = append(c.xGoogHeaders, hds...)
hds = append(hds, "Content-Type", "application/json")
headers := gax.BuildHeaders(ctx, hds...)
opts = append((*c.CallOptions).Delete[0:len((*c.CallOptions).Delete):len((*c.CallOptions).Delete)], opts...)
unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true}
resp := &computepb.Operation{}
e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
if settings.Path != "" {
baseUrl.Path = settings.Path
}
httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil)
if err != nil {
return err
}
httpReq = httpReq.WithContext(ctx)
httpReq.Header = headers
httpRsp, err := c.httpClient.Do(httpReq)
if err != nil {
return err
}
defer httpRsp.Body.Close()
if err = googleapi.CheckResponse(httpRsp); err != nil {
return err
}
buf, err := io.ReadAll(httpRsp.Body)
if err != nil {
return err
}
if err := unm.Unmarshal(buf, resp); err != nil {
return err
}
return nil
}, opts...)
if e != nil {
return nil, e
}
op := &Operation{
&regionOperationsHandle{
c: c.operationClient,
proto: resp,
project: req.GetProject(),
region: req.GetRegion(),
},
}
return op, nil
}
// Get returns the specified InstantSnapshot resource in the specified region.
func (c *regionInstantSnapshotsRESTClient) Get(ctx context.Context, req *computepb.GetRegionInstantSnapshotRequest, opts ...gax.CallOption) (*computepb.InstantSnapshot, error) {
baseUrl, err := url.Parse(c.endpoint)
if err != nil {
return nil, err
}
baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/instantSnapshots/%v", req.GetProject(), req.GetRegion(), req.GetInstantSnapshot())
// Build HTTP headers from client and context metadata.
hds := []string{"x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "region", url.QueryEscape(req.GetRegion()), "instant_snapshot", url.QueryEscape(req.GetInstantSnapshot()))}
hds = append(c.xGoogHeaders, hds...)
hds = append(hds, "Content-Type", "application/json")
headers := gax.BuildHeaders(ctx, hds...)
opts = append((*c.CallOptions).Get[0:len((*c.CallOptions).Get):len((*c.CallOptions).Get)], opts...)
unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true}
resp := &computepb.InstantSnapshot{}
e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
if settings.Path != "" {
baseUrl.Path = settings.Path
}
httpReq, err := http.NewRequest("GET", baseUrl.String(), nil)
if err != nil {
return err
}
httpReq = httpReq.WithContext(ctx)
httpReq.Header = headers
httpRsp, err := c.httpClient.Do(httpReq)
if err != nil {
return err
}
defer httpRsp.Body.Close()
if err = googleapi.CheckResponse(httpRsp); err != nil {
return err
}
buf, err := io.ReadAll(httpRsp.Body)
if err != nil {
return err
}
if err := unm.Unmarshal(buf, resp); err != nil {
return err
}
return nil
}, opts...)
if e != nil {
return nil, e
}
return resp, nil
}
// GetIamPolicy gets the access control policy for a resource. May be empty if no such policy or resource exists.
func (c *regionInstantSnapshotsRESTClient) GetIamPolicy(ctx context.Context, req *computepb.GetIamPolicyRegionInstantSnapshotRequest, opts ...gax.CallOption) (*computepb.Policy, error) {
baseUrl, err := url.Parse(c.endpoint)
if err != nil {
return nil, err
}
baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/instantSnapshots/%v/getIamPolicy", req.GetProject(), req.GetRegion(), req.GetResource())
params := url.Values{}
if req != nil && req.OptionsRequestedPolicyVersion != nil {
params.Add("optionsRequestedPolicyVersion", fmt.Sprintf("%v", req.GetOptionsRequestedPolicyVersion()))
}
baseUrl.RawQuery = params.Encode()
// Build HTTP headers from client and context metadata.
hds := []string{"x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "region", url.QueryEscape(req.GetRegion()), "resource", url.QueryEscape(req.GetResource()))}
hds = append(c.xGoogHeaders, hds...)
hds = append(hds, "Content-Type", "application/json")
headers := gax.BuildHeaders(ctx, hds...)
opts = append((*c.CallOptions).GetIamPolicy[0:len((*c.CallOptions).GetIamPolicy):len((*c.CallOptions).GetIamPolicy)], opts...)
unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true}
resp := &computepb.Policy{}
e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
if settings.Path != "" {
baseUrl.Path = settings.Path
}
httpReq, err := http.NewRequest("GET", baseUrl.String(), nil)
if err != nil {
return err
}
httpReq = httpReq.WithContext(ctx)
httpReq.Header = headers
httpRsp, err := c.httpClient.Do(httpReq)
if err != nil {
return err
}
defer httpRsp.Body.Close()
if err = googleapi.CheckResponse(httpRsp); err != nil {
return err
}
buf, err := io.ReadAll(httpRsp.Body)
if err != nil {
return err
}
if err := unm.Unmarshal(buf, resp); err != nil {
return err
}
return nil
}, opts...)
if e != nil {
return nil, e
}
return resp, nil
}
// Insert creates an instant snapshot in the specified region.
func (c *regionInstantSnapshotsRESTClient) Insert(ctx context.Context, req *computepb.InsertRegionInstantSnapshotRequest, opts ...gax.CallOption) (*Operation, error) {
m := protojson.MarshalOptions{AllowPartial: true}
body := req.GetInstantSnapshotResource()
jsonReq, err := m.Marshal(body)
if err != nil {
return nil, err
}
baseUrl, err := url.Parse(c.endpoint)
if err != nil {
return nil, err
}
baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/instantSnapshots", req.GetProject(), req.GetRegion())
params := url.Values{}
if req != nil && req.RequestId != nil {
params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId()))
}
baseUrl.RawQuery = params.Encode()
// Build HTTP headers from client and context metadata.
hds := []string{"x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "region", url.QueryEscape(req.GetRegion()))}
hds = append(c.xGoogHeaders, hds...)
hds = append(hds, "Content-Type", "application/json")
headers := gax.BuildHeaders(ctx, hds...)
opts = append((*c.CallOptions).Insert[0:len((*c.CallOptions).Insert):len((*c.CallOptions).Insert)], opts...)
unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true}
resp := &computepb.Operation{}
e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
if settings.Path != "" {
baseUrl.Path = settings.Path
}
httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq))
if err != nil {
return err
}
httpReq = httpReq.WithContext(ctx)
httpReq.Header = headers
httpRsp, err := c.httpClient.Do(httpReq)
if err != nil {
return err
}
defer httpRsp.Body.Close()
if err = googleapi.CheckResponse(httpRsp); err != nil {
return err
}
buf, err := io.ReadAll(httpRsp.Body)
if err != nil {
return err
}
if err := unm.Unmarshal(buf, resp); err != nil {
return err
}
return nil
}, opts...)
if e != nil {
return nil, e
}
op := &Operation{
&regionOperationsHandle{
c: c.operationClient,
proto: resp,
project: req.GetProject(),
region: req.GetRegion(),
},
}
return op, nil
}
// List retrieves the list of InstantSnapshot resources contained within the specified region.
func (c *regionInstantSnapshotsRESTClient) List(ctx context.Context, req *computepb.ListRegionInstantSnapshotsRequest, opts ...gax.CallOption) *InstantSnapshotIterator {
it := &InstantSnapshotIterator{}
req = proto.Clone(req).(*computepb.ListRegionInstantSnapshotsRequest)
unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true}
it.InternalFetch = func(pageSize int, pageToken string) ([]*computepb.InstantSnapshot, string, error) {
resp := &computepb.InstantSnapshotList{}
if pageToken != "" {
req.PageToken = proto.String(pageToken)
}
if pageSize > math.MaxInt32 {
req.MaxResults = proto.Uint32(math.MaxInt32)
} else if pageSize != 0 {
req.MaxResults = proto.Uint32(uint32(pageSize))
}
baseUrl, err := url.Parse(c.endpoint)
if err != nil {
return nil, "", err
}
baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/instantSnapshots", req.GetProject(), req.GetRegion())
params := url.Values{}
if req != nil && req.Filter != nil {
params.Add("filter", fmt.Sprintf("%v", req.GetFilter()))
}
if req != nil && req.MaxResults != nil {
params.Add("maxResults", fmt.Sprintf("%v", req.GetMaxResults()))
}
if req != nil && req.OrderBy != nil {
params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy()))
}
if req != nil && req.PageToken != nil {
params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken()))
}
if req != nil && req.ReturnPartialSuccess != nil {
params.Add("returnPartialSuccess", fmt.Sprintf("%v", req.GetReturnPartialSuccess()))
}
baseUrl.RawQuery = params.Encode()
// Build HTTP headers from client and context metadata.
hds := append(c.xGoogHeaders, "Content-Type", "application/json")
headers := gax.BuildHeaders(ctx, hds...)
e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
if settings.Path != "" {
baseUrl.Path = settings.Path
}
httpReq, err := http.NewRequest("GET", baseUrl.String(), nil)
if err != nil {
return err
}
httpReq.Header = headers
httpRsp, err := c.httpClient.Do(httpReq)
if err != nil {
return err
}
defer httpRsp.Body.Close()
if err = googleapi.CheckResponse(httpRsp); err != nil {
return err
}
buf, err := io.ReadAll(httpRsp.Body)
if err != nil {
return err
}
if err := unm.Unmarshal(buf, resp); err != nil {
return err
}
return nil
}, opts...)
if e != nil {
return nil, "", e
}
it.Response = resp
return resp.GetItems(), resp.GetNextPageToken(), nil
}
fetch := func(pageSize int, pageToken string) (string, error) {
items, nextPageToken, err := it.InternalFetch(pageSize, pageToken)
if err != nil {
return "", err
}
it.items = append(it.items, items...)
return nextPageToken, nil
}
it.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf)
it.pageInfo.MaxSize = int(req.GetMaxResults())
it.pageInfo.Token = req.GetPageToken()
return it
}
// SetIamPolicy sets the access control policy on the specified resource. Replaces any existing policy.
func (c *regionInstantSnapshotsRESTClient) SetIamPolicy(ctx context.Context, req *computepb.SetIamPolicyRegionInstantSnapshotRequest, opts ...gax.CallOption) (*computepb.Policy, error) {
m := protojson.MarshalOptions{AllowPartial: true}
body := req.GetRegionSetPolicyRequestResource()
jsonReq, err := m.Marshal(body)
if err != nil {
return nil, err
}
baseUrl, err := url.Parse(c.endpoint)
if err != nil {
return nil, err
}
baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/instantSnapshots/%v/setIamPolicy", req.GetProject(), req.GetRegion(), req.GetResource())
// Build HTTP headers from client and context metadata.
hds := []string{"x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "region", url.QueryEscape(req.GetRegion()), "resource", url.QueryEscape(req.GetResource()))}
hds = append(c.xGoogHeaders, hds...)
hds = append(hds, "Content-Type", "application/json")
headers := gax.BuildHeaders(ctx, hds...)
opts = append((*c.CallOptions).SetIamPolicy[0:len((*c.CallOptions).SetIamPolicy):len((*c.CallOptions).SetIamPolicy)], opts...)
unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true}
resp := &computepb.Policy{}
e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
if settings.Path != "" {
baseUrl.Path = settings.Path
}
httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq))
if err != nil {
return err
}
httpReq = httpReq.WithContext(ctx)
httpReq.Header = headers
httpRsp, err := c.httpClient.Do(httpReq)
if err != nil {
return err
}
defer httpRsp.Body.Close()
if err = googleapi.CheckResponse(httpRsp); err != nil {
return err
}
buf, err := io.ReadAll(httpRsp.Body)
if err != nil {
return err
}
if err := unm.Unmarshal(buf, resp); err != nil {
return err
}
return nil
}, opts...)
if e != nil {
return nil, e
}
return resp, nil
}
// SetLabels sets the labels on a instantSnapshot in the given region. To learn more about labels, read the Labeling Resources documentation.
func (c *regionInstantSnapshotsRESTClient) SetLabels(ctx context.Context, req *computepb.SetLabelsRegionInstantSnapshotRequest, opts ...gax.CallOption) (*Operation, error) {
m := protojson.MarshalOptions{AllowPartial: true}
body := req.GetRegionSetLabelsRequestResource()
jsonReq, err := m.Marshal(body)
if err != nil {
return nil, err
}
baseUrl, err := url.Parse(c.endpoint)
if err != nil {
return nil, err
}
baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/instantSnapshots/%v/setLabels", req.GetProject(), req.GetRegion(), req.GetResource())
params := url.Values{}
if req != nil && req.RequestId != nil {
params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId()))
}
baseUrl.RawQuery = params.Encode()
// Build HTTP headers from client and context metadata.
hds := []string{"x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "region", url.QueryEscape(req.GetRegion()), "resource", url.QueryEscape(req.GetResource()))}
hds = append(c.xGoogHeaders, hds...)
hds = append(hds, "Content-Type", "application/json")
headers := gax.BuildHeaders(ctx, hds...)
opts = append((*c.CallOptions).SetLabels[0:len((*c.CallOptions).SetLabels):len((*c.CallOptions).SetLabels)], opts...)
unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true}
resp := &computepb.Operation{}
e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
if settings.Path != "" {
baseUrl.Path = settings.Path
}
httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq))
if err != nil {
return err
}
httpReq = httpReq.WithContext(ctx)
httpReq.Header = headers
httpRsp, err := c.httpClient.Do(httpReq)
if err != nil {
return err
}
defer httpRsp.Body.Close()
if err = googleapi.CheckResponse(httpRsp); err != nil {
return err
}
buf, err := io.ReadAll(httpRsp.Body)
if err != nil {
return err
}
if err := unm.Unmarshal(buf, resp); err != nil {
return err
}
return nil
}, opts...)
if e != nil {
return nil, e
}
op := &Operation{
&regionOperationsHandle{
c: c.operationClient,
proto: resp,
project: req.GetProject(),
region: req.GetRegion(),
},
}
return op, nil
}
// TestIamPermissions returns permissions that a caller has on the specified resource.
func (c *regionInstantSnapshotsRESTClient) TestIamPermissions(ctx context.Context, req *computepb.TestIamPermissionsRegionInstantSnapshotRequest, opts ...gax.CallOption) (*computepb.TestPermissionsResponse, error) {
m := protojson.MarshalOptions{AllowPartial: true}
body := req.GetTestPermissionsRequestResource()
jsonReq, err := m.Marshal(body)
if err != nil {
return nil, err
}
baseUrl, err := url.Parse(c.endpoint)
if err != nil {
return nil, err
}
baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/instantSnapshots/%v/testIamPermissions", req.GetProject(), req.GetRegion(), req.GetResource())
// Build HTTP headers from client and context metadata.
hds := []string{"x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "region", url.QueryEscape(req.GetRegion()), "resource", url.QueryEscape(req.GetResource()))}
hds = append(c.xGoogHeaders, hds...)
hds = append(hds, "Content-Type", "application/json")
headers := gax.BuildHeaders(ctx, hds...)
opts = append((*c.CallOptions).TestIamPermissions[0:len((*c.CallOptions).TestIamPermissions):len((*c.CallOptions).TestIamPermissions)], opts...)
unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true}
resp := &computepb.TestPermissionsResponse{}
e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
if settings.Path != "" {
baseUrl.Path = settings.Path
}
httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq))
if err != nil {
return err
}
httpReq = httpReq.WithContext(ctx)
httpReq.Header = headers
httpRsp, err := c.httpClient.Do(httpReq)
if err != nil {
return err
}
defer httpRsp.Body.Close()
if err = googleapi.CheckResponse(httpRsp); err != nil {
return err
}
buf, err := io.ReadAll(httpRsp.Body)
if err != nil {
return err
}
if err := unm.Unmarshal(buf, resp); err != nil {
return err
}
return nil
}, opts...)
if e != nil {
return nil, e
}
return resp, nil
}

View file

@ -178,7 +178,7 @@ func (c *ReservationsClient) Connection() *grpc.ClientConn {
return c.internalClient.Connection()
}
// AggregatedList retrieves an aggregated list of reservations.
// AggregatedList retrieves an aggregated list of reservations. To prevent failure, Google recommends that you set the returnPartialSuccess parameter to true.
func (c *ReservationsClient) AggregatedList(ctx context.Context, req *computepb.AggregatedListReservationsRequest, opts ...gax.CallOption) *ReservationsScopedListPairIterator {
return c.internalClient.AggregatedList(ctx, req, opts...)
}
@ -315,7 +315,7 @@ func (c *reservationsRESTClient) Connection() *grpc.ClientConn {
return nil
}
// AggregatedList retrieves an aggregated list of reservations.
// AggregatedList retrieves an aggregated list of reservations. To prevent failure, Google recommends that you set the returnPartialSuccess parameter to true.
func (c *reservationsRESTClient) AggregatedList(ctx context.Context, req *computepb.AggregatedListReservationsRequest, opts ...gax.CallOption) *ReservationsScopedListPairIterator {
it := &ReservationsScopedListPairIterator{}
req = proto.Clone(req).(*computepb.AggregatedListReservationsRequest)

View file

@ -173,7 +173,7 @@ func (c *ResourcePoliciesClient) Connection() *grpc.ClientConn {
return c.internalClient.Connection()
}
// AggregatedList retrieves an aggregated list of resource policies.
// AggregatedList retrieves an aggregated list of resource policies. To prevent failure, Google recommends that you set the returnPartialSuccess parameter to true.
func (c *ResourcePoliciesClient) AggregatedList(ctx context.Context, req *computepb.AggregatedListResourcePoliciesRequest, opts ...gax.CallOption) *ResourcePoliciesScopedListPairIterator {
return c.internalClient.AggregatedList(ctx, req, opts...)
}
@ -305,7 +305,7 @@ func (c *resourcePoliciesRESTClient) Connection() *grpc.ClientConn {
return nil
}
// AggregatedList retrieves an aggregated list of resource policies.
// AggregatedList retrieves an aggregated list of resource policies. To prevent failure, Google recommends that you set the returnPartialSuccess parameter to true.
func (c *resourcePoliciesRESTClient) AggregatedList(ctx context.Context, req *computepb.AggregatedListResourcePoliciesRequest, opts ...gax.CallOption) *ResourcePoliciesScopedListPairIterator {
it := &ResourcePoliciesScopedListPairIterator{}
req = proto.Clone(req).(*computepb.AggregatedListResourcePoliciesRequest)

View file

@ -201,7 +201,7 @@ func (c *RoutersClient) Connection() *grpc.ClientConn {
return c.internalClient.Connection()
}
// AggregatedList retrieves an aggregated list of routers.
// AggregatedList retrieves an aggregated list of routers. To prevent failure, Google recommends that you set the returnPartialSuccess parameter to true.
func (c *RoutersClient) AggregatedList(ctx context.Context, req *computepb.AggregatedListRoutersRequest, opts ...gax.CallOption) *RoutersScopedListPairIterator {
return c.internalClient.AggregatedList(ctx, req, opts...)
}
@ -343,7 +343,7 @@ func (c *routersRESTClient) Connection() *grpc.ClientConn {
return nil
}
// AggregatedList retrieves an aggregated list of routers.
// AggregatedList retrieves an aggregated list of routers. To prevent failure, Google recommends that you set the returnPartialSuccess parameter to true.
func (c *routersRESTClient) AggregatedList(ctx context.Context, req *computepb.AggregatedListRoutersRequest, opts ...gax.CallOption) *RoutersScopedListPairIterator {
it := &RoutersScopedListPairIterator{}
req = proto.Clone(req).(*computepb.AggregatedListRoutersRequest)

View file

@ -202,7 +202,7 @@ func (c *SecurityPoliciesClient) AddRule(ctx context.Context, req *computepb.Add
return c.internalClient.AddRule(ctx, req, opts...)
}
// AggregatedList retrieves the list of all SecurityPolicy resources, regional and global, available to the specified project.
// AggregatedList retrieves the list of all SecurityPolicy resources, regional and global, available to the specified project. To prevent failure, Google recommends that you set the returnPartialSuccess parameter to true.
func (c *SecurityPoliciesClient) AggregatedList(ctx context.Context, req *computepb.AggregatedListSecurityPoliciesRequest, opts ...gax.CallOption) *SecurityPoliciesScopedListPairIterator {
return c.internalClient.AggregatedList(ctx, req, opts...)
}
@ -420,7 +420,7 @@ func (c *securityPoliciesRESTClient) AddRule(ctx context.Context, req *computepb
return op, nil
}
// AggregatedList retrieves the list of all SecurityPolicy resources, regional and global, available to the specified project.
// AggregatedList retrieves the list of all SecurityPolicy resources, regional and global, available to the specified project. To prevent failure, Google recommends that you set the returnPartialSuccess parameter to true.
func (c *securityPoliciesRESTClient) AggregatedList(ctx context.Context, req *computepb.AggregatedListSecurityPoliciesRequest, opts ...gax.CallOption) *SecurityPoliciesScopedListPairIterator {
it := &SecurityPoliciesScopedListPairIterator{}
req = proto.Clone(req).(*computepb.AggregatedListSecurityPoliciesRequest)

View file

@ -173,7 +173,7 @@ func (c *ServiceAttachmentsClient) Connection() *grpc.ClientConn {
return c.internalClient.Connection()
}
// AggregatedList retrieves the list of all ServiceAttachment resources, regional and global, available to the specified project.
// AggregatedList retrieves the list of all ServiceAttachment resources, regional and global, available to the specified project. To prevent failure, Google recommends that you set the returnPartialSuccess parameter to true.
func (c *ServiceAttachmentsClient) AggregatedList(ctx context.Context, req *computepb.AggregatedListServiceAttachmentsRequest, opts ...gax.CallOption) *ServiceAttachmentsScopedListPairIterator {
return c.internalClient.AggregatedList(ctx, req, opts...)
}
@ -305,7 +305,7 @@ func (c *serviceAttachmentsRESTClient) Connection() *grpc.ClientConn {
return nil
}
// AggregatedList retrieves the list of all ServiceAttachment resources, regional and global, available to the specified project.
// AggregatedList retrieves the list of all ServiceAttachment resources, regional and global, available to the specified project. To prevent failure, Google recommends that you set the returnPartialSuccess parameter to true.
func (c *serviceAttachmentsRESTClient) AggregatedList(ctx context.Context, req *computepb.AggregatedListServiceAttachmentsRequest, opts ...gax.CallOption) *ServiceAttachmentsScopedListPairIterator {
it := &ServiceAttachmentsScopedListPairIterator{}
req = proto.Clone(req).(*computepb.AggregatedListServiceAttachmentsRequest)

View file

@ -144,7 +144,7 @@ func (c *SslCertificatesClient) Connection() *grpc.ClientConn {
return c.internalClient.Connection()
}
// AggregatedList retrieves the list of all SslCertificate resources, regional and global, available to the specified project.
// AggregatedList retrieves the list of all SslCertificate resources, regional and global, available to the specified project. To prevent failure, Google recommends that you set the returnPartialSuccess parameter to true.
func (c *SslCertificatesClient) AggregatedList(ctx context.Context, req *computepb.AggregatedListSslCertificatesRequest, opts ...gax.CallOption) *SslCertificatesScopedListPairIterator {
return c.internalClient.AggregatedList(ctx, req, opts...)
}
@ -256,7 +256,7 @@ func (c *sslCertificatesRESTClient) Connection() *grpc.ClientConn {
return nil
}
// AggregatedList retrieves the list of all SslCertificate resources, regional and global, available to the specified project.
// AggregatedList retrieves the list of all SslCertificate resources, regional and global, available to the specified project. To prevent failure, Google recommends that you set the returnPartialSuccess parameter to true.
func (c *sslCertificatesRESTClient) AggregatedList(ctx context.Context, req *computepb.AggregatedListSslCertificatesRequest, opts ...gax.CallOption) *SslCertificatesScopedListPairIterator {
it := &SslCertificatesScopedListPairIterator{}
req = proto.Clone(req).(*computepb.AggregatedListSslCertificatesRequest)

View file

@ -163,7 +163,7 @@ func (c *SslPoliciesClient) Connection() *grpc.ClientConn {
return c.internalClient.Connection()
}
// AggregatedList retrieves the list of all SslPolicy resources, regional and global, available to the specified project.
// AggregatedList retrieves the list of all SslPolicy resources, regional and global, available to the specified project. To prevent failure, Google recommends that you set the returnPartialSuccess parameter to true.
func (c *SslPoliciesClient) AggregatedList(ctx context.Context, req *computepb.AggregatedListSslPoliciesRequest, opts ...gax.CallOption) *SslPoliciesScopedListPairIterator {
return c.internalClient.AggregatedList(ctx, req, opts...)
}
@ -285,7 +285,7 @@ func (c *sslPoliciesRESTClient) Connection() *grpc.ClientConn {
return nil
}
// AggregatedList retrieves the list of all SslPolicy resources, regional and global, available to the specified project.
// AggregatedList retrieves the list of all SslPolicy resources, regional and global, available to the specified project. To prevent failure, Google recommends that you set the returnPartialSuccess parameter to true.
func (c *sslPoliciesRESTClient) AggregatedList(ctx context.Context, req *computepb.AggregatedListSslPoliciesRequest, opts ...gax.CallOption) *SslPoliciesScopedListPairIterator {
it := &SslPoliciesScopedListPairIterator{}
req = proto.Clone(req).(*computepb.AggregatedListSslPoliciesRequest)

View file

@ -197,7 +197,7 @@ func (c *SubnetworksClient) Connection() *grpc.ClientConn {
return c.internalClient.Connection()
}
// AggregatedList retrieves an aggregated list of subnetworks.
// AggregatedList retrieves an aggregated list of subnetworks. To prevent failure, Google recommends that you set the returnPartialSuccess parameter to true.
func (c *SubnetworksClient) AggregatedList(ctx context.Context, req *computepb.AggregatedListSubnetworksRequest, opts ...gax.CallOption) *SubnetworksScopedListPairIterator {
return c.internalClient.AggregatedList(ctx, req, opts...)
}
@ -344,7 +344,7 @@ func (c *subnetworksRESTClient) Connection() *grpc.ClientConn {
return nil
}
// AggregatedList retrieves an aggregated list of subnetworks.
// AggregatedList retrieves an aggregated list of subnetworks. To prevent failure, Google recommends that you set the returnPartialSuccess parameter to true.
func (c *subnetworksRESTClient) AggregatedList(ctx context.Context, req *computepb.AggregatedListSubnetworksRequest, opts ...gax.CallOption) *SubnetworksScopedListPairIterator {
it := &SubnetworksScopedListPairIterator{}
req = proto.Clone(req).(*computepb.AggregatedListSubnetworksRequest)

View file

@ -154,7 +154,7 @@ func (c *TargetHttpProxiesClient) Connection() *grpc.ClientConn {
return c.internalClient.Connection()
}
// AggregatedList retrieves the list of all TargetHttpProxy resources, regional and global, available to the specified project.
// AggregatedList retrieves the list of all TargetHttpProxy resources, regional and global, available to the specified project. To prevent failure, Google recommends that you set the returnPartialSuccess parameter to true.
func (c *TargetHttpProxiesClient) AggregatedList(ctx context.Context, req *computepb.AggregatedListTargetHttpProxiesRequest, opts ...gax.CallOption) *TargetHttpProxiesScopedListPairIterator {
return c.internalClient.AggregatedList(ctx, req, opts...)
}
@ -276,7 +276,7 @@ func (c *targetHttpProxiesRESTClient) Connection() *grpc.ClientConn {
return nil
}
// AggregatedList retrieves the list of all TargetHttpProxy resources, regional and global, available to the specified project.
// AggregatedList retrieves the list of all TargetHttpProxy resources, regional and global, available to the specified project. To prevent failure, Google recommends that you set the returnPartialSuccess parameter to true.
func (c *targetHttpProxiesRESTClient) AggregatedList(ctx context.Context, req *computepb.AggregatedListTargetHttpProxiesRequest, opts ...gax.CallOption) *TargetHttpProxiesScopedListPairIterator {
it := &TargetHttpProxiesScopedListPairIterator{}
req = proto.Clone(req).(*computepb.AggregatedListTargetHttpProxiesRequest)

View file

@ -174,7 +174,7 @@ func (c *TargetHttpsProxiesClient) Connection() *grpc.ClientConn {
return c.internalClient.Connection()
}
// AggregatedList retrieves the list of all TargetHttpsProxy resources, regional and global, available to the specified project.
// AggregatedList retrieves the list of all TargetHttpsProxy resources, regional and global, available to the specified project. To prevent failure, Google recommends that you set the returnPartialSuccess parameter to true.
func (c *TargetHttpsProxiesClient) AggregatedList(ctx context.Context, req *computepb.AggregatedListTargetHttpsProxiesRequest, opts ...gax.CallOption) *TargetHttpsProxiesScopedListPairIterator {
return c.internalClient.AggregatedList(ctx, req, opts...)
}
@ -316,7 +316,7 @@ func (c *targetHttpsProxiesRESTClient) Connection() *grpc.ClientConn {
return nil
}
// AggregatedList retrieves the list of all TargetHttpsProxy resources, regional and global, available to the specified project.
// AggregatedList retrieves the list of all TargetHttpsProxy resources, regional and global, available to the specified project. To prevent failure, Google recommends that you set the returnPartialSuccess parameter to true.
func (c *targetHttpsProxiesRESTClient) AggregatedList(ctx context.Context, req *computepb.AggregatedListTargetHttpsProxiesRequest, opts ...gax.CallOption) *TargetHttpsProxiesScopedListPairIterator {
it := &TargetHttpsProxiesScopedListPairIterator{}
req = proto.Clone(req).(*computepb.AggregatedListTargetHttpsProxiesRequest)

View file

@ -149,7 +149,7 @@ func (c *TargetInstancesClient) Connection() *grpc.ClientConn {
return c.internalClient.Connection()
}
// AggregatedList retrieves an aggregated list of target instances.
// AggregatedList retrieves an aggregated list of target instances. To prevent failure, Google recommends that you set the returnPartialSuccess parameter to true.
func (c *TargetInstancesClient) AggregatedList(ctx context.Context, req *computepb.AggregatedListTargetInstancesRequest, opts ...gax.CallOption) *TargetInstancesScopedListPairIterator {
return c.internalClient.AggregatedList(ctx, req, opts...)
}
@ -266,7 +266,7 @@ func (c *targetInstancesRESTClient) Connection() *grpc.ClientConn {
return nil
}
// AggregatedList retrieves an aggregated list of target instances.
// AggregatedList retrieves an aggregated list of target instances. To prevent failure, Google recommends that you set the returnPartialSuccess parameter to true.
func (c *targetInstancesRESTClient) AggregatedList(ctx context.Context, req *computepb.AggregatedListTargetInstancesRequest, opts ...gax.CallOption) *TargetInstancesScopedListPairIterator {
it := &TargetInstancesScopedListPairIterator{}
req = proto.Clone(req).(*computepb.AggregatedListTargetInstancesRequest)

View file

@ -189,7 +189,7 @@ func (c *TargetPoolsClient) AddInstance(ctx context.Context, req *computepb.AddI
return c.internalClient.AddInstance(ctx, req, opts...)
}
// AggregatedList retrieves an aggregated list of target pools.
// AggregatedList retrieves an aggregated list of target pools. To prevent failure, Google recommends that you set the returnPartialSuccess parameter to true.
func (c *TargetPoolsClient) AggregatedList(ctx context.Context, req *computepb.AggregatedListTargetPoolsRequest, opts ...gax.CallOption) *TargetPoolsScopedListPairIterator {
return c.internalClient.AggregatedList(ctx, req, opts...)
}
@ -480,7 +480,7 @@ func (c *targetPoolsRESTClient) AddInstance(ctx context.Context, req *computepb.
return op, nil
}
// AggregatedList retrieves an aggregated list of target pools.
// AggregatedList retrieves an aggregated list of target pools. To prevent failure, Google recommends that you set the returnPartialSuccess parameter to true.
func (c *targetPoolsRESTClient) AggregatedList(ctx context.Context, req *computepb.AggregatedListTargetPoolsRequest, opts ...gax.CallOption) *TargetPoolsScopedListPairIterator {
it := &TargetPoolsScopedListPairIterator{}
req = proto.Clone(req).(*computepb.AggregatedListTargetPoolsRequest)

View file

@ -154,7 +154,7 @@ func (c *TargetTcpProxiesClient) Connection() *grpc.ClientConn {
return c.internalClient.Connection()
}
// AggregatedList retrieves the list of all TargetTcpProxy resources, regional and global, available to the specified project.
// AggregatedList retrieves the list of all TargetTcpProxy resources, regional and global, available to the specified project. To prevent failure, Google recommends that you set the returnPartialSuccess parameter to true.
func (c *TargetTcpProxiesClient) AggregatedList(ctx context.Context, req *computepb.AggregatedListTargetTcpProxiesRequest, opts ...gax.CallOption) *TargetTcpProxiesScopedListPairIterator {
return c.internalClient.AggregatedList(ctx, req, opts...)
}
@ -276,7 +276,7 @@ func (c *targetTcpProxiesRESTClient) Connection() *grpc.ClientConn {
return nil
}
// AggregatedList retrieves the list of all TargetTcpProxy resources, regional and global, available to the specified project.
// AggregatedList retrieves the list of all TargetTcpProxy resources, regional and global, available to the specified project. To prevent failure, Google recommends that you set the returnPartialSuccess parameter to true.
func (c *targetTcpProxiesRESTClient) AggregatedList(ctx context.Context, req *computepb.AggregatedListTargetTcpProxiesRequest, opts ...gax.CallOption) *TargetTcpProxiesScopedListPairIterator {
it := &TargetTcpProxiesScopedListPairIterator{}
req = proto.Clone(req).(*computepb.AggregatedListTargetTcpProxiesRequest)

View file

@ -149,7 +149,7 @@ func (c *TargetVpnGatewaysClient) Connection() *grpc.ClientConn {
return c.internalClient.Connection()
}
// AggregatedList retrieves an aggregated list of target VPN gateways.
// AggregatedList retrieves an aggregated list of target VPN gateways. To prevent failure, Google recommends that you set the returnPartialSuccess parameter to true.
func (c *TargetVpnGatewaysClient) AggregatedList(ctx context.Context, req *computepb.AggregatedListTargetVpnGatewaysRequest, opts ...gax.CallOption) *TargetVpnGatewaysScopedListPairIterator {
return c.internalClient.AggregatedList(ctx, req, opts...)
}
@ -266,7 +266,7 @@ func (c *targetVpnGatewaysRESTClient) Connection() *grpc.ClientConn {
return nil
}
// AggregatedList retrieves an aggregated list of target VPN gateways.
// AggregatedList retrieves an aggregated list of target VPN gateways. To prevent failure, Google recommends that you set the returnPartialSuccess parameter to true.
func (c *targetVpnGatewaysRESTClient) AggregatedList(ctx context.Context, req *computepb.AggregatedListTargetVpnGatewaysRequest, opts ...gax.CallOption) *TargetVpnGatewaysScopedListPairIterator {
it := &TargetVpnGatewaysScopedListPairIterator{}
req = proto.Clone(req).(*computepb.AggregatedListTargetVpnGatewaysRequest)

View file

@ -164,7 +164,7 @@ func (c *UrlMapsClient) Connection() *grpc.ClientConn {
return c.internalClient.Connection()
}
// AggregatedList retrieves the list of all UrlMap resources, regional and global, available to the specified project.
// AggregatedList retrieves the list of all UrlMap resources, regional and global, available to the specified project. To prevent failure, Google recommends that you set the returnPartialSuccess parameter to true.
func (c *UrlMapsClient) AggregatedList(ctx context.Context, req *computepb.AggregatedListUrlMapsRequest, opts ...gax.CallOption) *UrlMapsScopedListPairIterator {
return c.internalClient.AggregatedList(ctx, req, opts...)
}
@ -296,7 +296,7 @@ func (c *urlMapsRESTClient) Connection() *grpc.ClientConn {
return nil
}
// AggregatedList retrieves the list of all UrlMap resources, regional and global, available to the specified project.
// AggregatedList retrieves the list of all UrlMap resources, regional and global, available to the specified project. To prevent failure, Google recommends that you set the returnPartialSuccess parameter to true.
func (c *urlMapsRESTClient) AggregatedList(ctx context.Context, req *computepb.AggregatedListUrlMapsRequest, opts ...gax.CallOption) *UrlMapsScopedListPairIterator {
it := &UrlMapsScopedListPairIterator{}
req = proto.Clone(req).(*computepb.AggregatedListUrlMapsRequest)

View file

@ -168,7 +168,7 @@ func (c *VpnGatewaysClient) Connection() *grpc.ClientConn {
return c.internalClient.Connection()
}
// AggregatedList retrieves an aggregated list of VPN gateways.
// AggregatedList retrieves an aggregated list of VPN gateways. To prevent failure, Google recommends that you set the returnPartialSuccess parameter to true.
func (c *VpnGatewaysClient) AggregatedList(ctx context.Context, req *computepb.AggregatedListVpnGatewaysRequest, opts ...gax.CallOption) *VpnGatewaysScopedListPairIterator {
return c.internalClient.AggregatedList(ctx, req, opts...)
}
@ -295,7 +295,7 @@ func (c *vpnGatewaysRESTClient) Connection() *grpc.ClientConn {
return nil
}
// AggregatedList retrieves an aggregated list of VPN gateways.
// AggregatedList retrieves an aggregated list of VPN gateways. To prevent failure, Google recommends that you set the returnPartialSuccess parameter to true.
func (c *vpnGatewaysRESTClient) AggregatedList(ctx context.Context, req *computepb.AggregatedListVpnGatewaysRequest, opts ...gax.CallOption) *VpnGatewaysScopedListPairIterator {
it := &VpnGatewaysScopedListPairIterator{}
req = proto.Clone(req).(*computepb.AggregatedListVpnGatewaysRequest)

View file

@ -149,7 +149,7 @@ func (c *VpnTunnelsClient) Connection() *grpc.ClientConn {
return c.internalClient.Connection()
}
// AggregatedList retrieves an aggregated list of VPN tunnels.
// AggregatedList retrieves an aggregated list of VPN tunnels. To prevent failure, Google recommends that you set the returnPartialSuccess parameter to true.
func (c *VpnTunnelsClient) AggregatedList(ctx context.Context, req *computepb.AggregatedListVpnTunnelsRequest, opts ...gax.CallOption) *VpnTunnelsScopedListPairIterator {
return c.internalClient.AggregatedList(ctx, req, opts...)
}
@ -266,7 +266,7 @@ func (c *vpnTunnelsRESTClient) Connection() *grpc.ClientConn {
return nil
}
// AggregatedList retrieves an aggregated list of VPN tunnels.
// AggregatedList retrieves an aggregated list of VPN tunnels. To prevent failure, Google recommends that you set the returnPartialSuccess parameter to true.
func (c *vpnTunnelsRESTClient) AggregatedList(ctx context.Context, req *computepb.AggregatedListVpnTunnelsRequest, opts ...gax.CallOption) *VpnTunnelsScopedListPairIterator {
it := &VpnTunnelsScopedListPairIterator{}
req = proto.Clone(req).(*computepb.AggregatedListVpnTunnelsRequest)

View file

@ -15,4 +15,4 @@
package internal
// Version is the current tagged release of the library.
const Version = "1.24.0"
const Version = "1.25.0"

View file

@ -199,6 +199,26 @@
"release_level": "stable",
"library_type": "GAPIC_AUTO"
},
"cloud.google.com/go/apps/events/subscriptions/apiv1": {
"api_shortname": "workspaceevents",
"distribution_name": "cloud.google.com/go/apps/events/subscriptions/apiv1",
"description": "Google Workspace Events API",
"language": "go",
"client_library_type": "generated",
"client_documentation": "https://cloud.google.com/go/docs/reference/cloud.google.com/go/apps/latest/events/subscriptions/apiv1",
"release_level": "preview",
"library_type": "GAPIC_AUTO"
},
"cloud.google.com/go/apps/meet/apiv2": {
"api_shortname": "meet",
"distribution_name": "cloud.google.com/go/apps/meet/apiv2",
"description": "Google Meet API",
"language": "go",
"client_library_type": "generated",
"client_documentation": "https://cloud.google.com/go/docs/reference/cloud.google.com/go/apps/latest/meet/apiv2",
"release_level": "preview",
"library_type": "GAPIC_AUTO"
},
"cloud.google.com/go/apps/meet/apiv2beta": {
"api_shortname": "meet",
"distribution_name": "cloud.google.com/go/apps/meet/apiv2beta",
@ -1779,6 +1799,16 @@
"release_level": "preview",
"library_type": "GAPIC_AUTO"
},
"cloud.google.com/go/parallelstore/apiv1beta": {
"api_shortname": "parallelstore",
"distribution_name": "cloud.google.com/go/parallelstore/apiv1beta",
"description": "Parallelstore API",
"language": "go",
"client_library_type": "generated",
"client_documentation": "https://cloud.google.com/go/docs/reference/cloud.google.com/go/parallelstore/latest/apiv1beta",
"release_level": "preview",
"library_type": "GAPIC_AUTO"
},
"cloud.google.com/go/phishingprotection/apiv1beta1": {
"api_shortname": "phishingprotection",
"distribution_name": "cloud.google.com/go/phishingprotection/apiv1beta1",
@ -2159,6 +2189,16 @@
"release_level": "preview",
"library_type": "GAPIC_AUTO"
},
"cloud.google.com/go/securityposture/apiv1": {
"api_shortname": "securityposture",
"distribution_name": "cloud.google.com/go/securityposture/apiv1",
"description": "Security Posture API",
"language": "go",
"client_library_type": "generated",
"client_documentation": "https://cloud.google.com/go/docs/reference/cloud.google.com/go/securityposture/latest/apiv1",
"release_level": "preview",
"library_type": "GAPIC_AUTO"
},
"cloud.google.com/go/servicecontrol/apiv1": {
"api_shortname": "servicecontrol",
"distribution_name": "cloud.google.com/go/servicecontrol/apiv1",
@ -2189,6 +2229,16 @@
"release_level": "preview",
"library_type": "GAPIC_AUTO"
},
"cloud.google.com/go/servicehealth/apiv1": {
"api_shortname": "servicehealth",
"distribution_name": "cloud.google.com/go/servicehealth/apiv1",
"description": "Service Health API",
"language": "go",
"client_library_type": "generated",
"client_documentation": "https://cloud.google.com/go/docs/reference/cloud.google.com/go/servicehealth/latest/apiv1",
"release_level": "preview",
"library_type": "GAPIC_AUTO"
},
"cloud.google.com/go/servicemanagement/apiv1": {
"api_shortname": "servicemanagement",
"distribution_name": "cloud.google.com/go/servicemanagement/apiv1",
@ -2529,6 +2579,16 @@
"release_level": "preview",
"library_type": "GAPIC_AUTO"
},
"cloud.google.com/go/visionai/apiv1": {
"api_shortname": "visionai",
"distribution_name": "cloud.google.com/go/visionai/apiv1",
"description": "Vision AI API",
"language": "go",
"client_library_type": "generated",
"client_documentation": "https://cloud.google.com/go/docs/reference/cloud.google.com/go/visionai/latest/apiv1",
"release_level": "stable",
"library_type": "GAPIC_AUTO"
},
"cloud.google.com/go/vmmigration/apiv1": {
"api_shortname": "vmmigration",
"distribution_name": "cloud.google.com/go/vmmigration/apiv1",

View file

@ -20,6 +20,7 @@ import (
"fmt"
"os"
"strings"
"sync"
"go.opencensus.io/trace"
"go.opentelemetry.io/otel"
@ -50,17 +51,23 @@ const (
)
var (
// OpenTelemetryTracingEnabled is true if the environment variable
// openTelemetryTracingEnabledMu guards access to openTelemetryTracingEnabled field
openTelemetryTracingEnabledMu = sync.RWMutex{}
// openTelemetryTracingEnabled is true if the environment variable
// GOOGLE_API_GO_EXPERIMENTAL_TELEMETRY_PLATFORM_TRACING is set to the
// case-insensitive value "opentelemetry".
//
// Do not access directly. Use instead IsOpenTelemetryTracingEnabled or
// IsOpenCensusTracingEnabled. Intended for use only in unit tests. Restore
// original value after each test.
OpenTelemetryTracingEnabled bool = strings.EqualFold(strings.TrimSpace(
openTelemetryTracingEnabled bool = strings.EqualFold(strings.TrimSpace(
os.Getenv(TelemetryPlatformTracingVar)), TelemetryPlatformTracingOpenTelemetry)
)
// SetOpenTelemetryTracingEnabledField programmatically sets the value provided by GOOGLE_API_GO_EXPERIMENTAL_TELEMETRY_PLATFORM_TRACING for the purpose of unit testing.
// Do not invoke it directly. Intended for use only in unit tests. Restore original value after each test.
func SetOpenTelemetryTracingEnabledField(enabled bool) {
openTelemetryTracingEnabledMu.Lock()
defer openTelemetryTracingEnabledMu.Unlock()
openTelemetryTracingEnabled = enabled
}
// IsOpenCensusTracingEnabled returns true if the environment variable
// GOOGLE_API_GO_EXPERIMENTAL_TELEMETRY_PLATFORM_TRACING is NOT set to the
// case-insensitive value "opentelemetry".
@ -72,7 +79,9 @@ func IsOpenCensusTracingEnabled() bool {
// GOOGLE_API_GO_EXPERIMENTAL_TELEMETRY_PLATFORM_TRACING is set to the
// case-insensitive value "opentelemetry".
func IsOpenTelemetryTracingEnabled() bool {
return OpenTelemetryTracingEnabled
openTelemetryTracingEnabledMu.RLock()
defer openTelemetryTracingEnabledMu.RUnlock()
return openTelemetryTracingEnabled
}
// StartSpan adds a span to the trace with the given name. If IsOpenCensusTracingEnabled

View file

@ -5,4 +5,4 @@ package aws
const SDKName = "aws-sdk-go"
// SDKVersion is the version of this SDK
const SDKVersion = "1.50.30"
const SDKVersion = "1.50.31"

201
vendor/github.com/golang/glog/glog.go generated vendored
View file

@ -15,8 +15,26 @@
// limitations under the License.
// Package glog implements logging analogous to the Google-internal C++ INFO/ERROR/V setup.
// It provides functions Info, Warning, Error, Fatal, plus formatting variants such as
// Infof. It also provides V-style logging controlled by the -v and -vmodule=file=2 flags.
// It provides functions that have a name matched by regex:
//
// (Info|Warning|Error|Fatal)(Context)?(Depth)?(f)?
//
// If Context is present, function takes context.Context argument. The
// context is used to pass through the Trace Context to log sinks that can make use
// of it.
// It is recommended to use the context variant of the functions over the non-context
// variants if a context is available to make sure the Trace Contexts are present
// in logs.
//
// If Depth is present, this function calls log from a different depth in the call stack.
// This enables a callee to emit logs that use the callsite information of its caller
// or any other callers in the stack. When depth == 0, the original callee's line
// information is emitted. When depth > 0, depth frames are skipped in the call stack
// and the final frame is treated like the original callee to Info.
//
// If 'f' is present, function formats according to a format specifier.
//
// This package also provides V-style logging controlled by the -v and -vmodule=file=2 flags.
//
// Basic examples:
//
@ -82,6 +100,7 @@ package glog
import (
"bytes"
"context"
"errors"
"fmt"
stdLog "log"
@ -182,9 +201,14 @@ func appendBacktrace(depth int, format string, args []any) (string, []any) {
return format, args
}
// logf writes a log message for a log function call (or log function wrapper)
// at the given depth in the current goroutine's stack.
// logf acts as ctxlogf, but doesn't expect a context.
func logf(depth int, severity logsink.Severity, verbose bool, stack stack, format string, args ...any) {
ctxlogf(nil, depth+1, severity, verbose, stack, format, args...)
}
// ctxlogf writes a log message for a log function call (or log function wrapper)
// at the given depth in the current goroutine's stack.
func ctxlogf(ctx context.Context, depth int, severity logsink.Severity, verbose bool, stack stack, format string, args ...any) {
now := timeNow()
_, file, line, ok := runtime.Caller(depth + 1)
if !ok {
@ -198,6 +222,7 @@ func logf(depth int, severity logsink.Severity, verbose bool, stack stack, forma
metai, meta := metaPoolGet()
*meta = logsink.Meta{
Context: ctx,
Time: now,
File: file,
Line: line,
@ -207,6 +232,9 @@ func logf(depth int, severity logsink.Severity, verbose bool, stack stack, forma
Thread: int64(pid),
}
sinkf(meta, format, args...)
// Clear pointer fields so they can be garbage collected early.
meta.Context = nil
meta.Stack = nil
metaPool.Put(metai)
}
@ -418,6 +446,36 @@ func (v Verbose) Infof(format string, args ...any) {
}
}
// InfoContext is equivalent to the global InfoContext function, guarded by the value of v.
// See the documentation of V for usage.
func (v Verbose) InfoContext(ctx context.Context, args ...any) {
v.InfoContextDepth(ctx, 1, args...)
}
// InfoContextf is equivalent to the global InfoContextf function, guarded by the value of v.
// See the documentation of V for usage.
func (v Verbose) InfoContextf(ctx context.Context, format string, args ...any) {
if v {
ctxlogf(ctx, 1, logsink.Info, true, noStack, format, args...)
}
}
// InfoContextDepth is equivalent to the global InfoContextDepth function, guarded by the value of v.
// See the documentation of V for usage.
func (v Verbose) InfoContextDepth(ctx context.Context, depth int, args ...any) {
if v {
ctxlogf(ctx, depth+1, logsink.Info, true, noStack, defaultFormat(args), args...)
}
}
// InfoContextDepthf is equivalent to the global InfoContextDepthf function, guarded by the value of v.
// See the documentation of V for usage.
func (v Verbose) InfoContextDepthf(ctx context.Context, depth int, format string, args ...any) {
if v {
ctxlogf(ctx, depth+1, logsink.Info, true, noStack, format, args...)
}
}
// Info logs to the INFO log.
// Arguments are handled in the manner of fmt.Print; a newline is appended if missing.
func Info(args ...any) {
@ -450,6 +508,30 @@ func Infof(format string, args ...any) {
logf(1, logsink.Info, false, noStack, format, args...)
}
// InfoContext is like [Info], but with an extra [context.Context] parameter. The
// context is used to pass the Trace Context to log sinks.
func InfoContext(ctx context.Context, args ...any) {
InfoContextDepth(ctx, 1, args...)
}
// InfoContextf is like [Infof], but with an extra [context.Context] parameter. The
// context is used to pass the Trace Context to log sinks.
func InfoContextf(ctx context.Context, format string, args ...any) {
ctxlogf(ctx, 1, logsink.Info, false, noStack, format, args...)
}
// InfoContextDepth is like [InfoDepth], but with an extra [context.Context] parameter. The
// context is used to pass the Trace Context to log sinks.
func InfoContextDepth(ctx context.Context, depth int, args ...any) {
ctxlogf(ctx, depth+1, logsink.Info, false, noStack, defaultFormat(args), args...)
}
// InfoContextDepthf is like [InfoDepthf], but with an extra [context.Context] parameter. The
// context is used to pass the Trace Context to log sinks.
func InfoContextDepthf(ctx context.Context, depth int, format string, args ...any) {
ctxlogf(ctx, depth+1, logsink.Info, false, noStack, format, args...)
}
// Warning logs to the WARNING and INFO logs.
// Arguments are handled in the manner of fmt.Print; a newline is appended if missing.
func Warning(args ...any) {
@ -480,6 +562,30 @@ func Warningf(format string, args ...any) {
logf(1, logsink.Warning, false, noStack, format, args...)
}
// WarningContext is like [Warning], but with an extra [context.Context] parameter. The
// context is used to pass the Trace Context to log sinks.
func WarningContext(ctx context.Context, args ...any) {
WarningContextDepth(ctx, 1, args...)
}
// WarningContextf is like [Warningf], but with an extra [context.Context] parameter. The
// context is used to pass the Trace Context to log sinks.
func WarningContextf(ctx context.Context, format string, args ...any) {
ctxlogf(ctx, 1, logsink.Warning, false, noStack, format, args...)
}
// WarningContextDepth is like [WarningDepth], but with an extra [context.Context] parameter. The
// context is used to pass the Trace Context to log sinks.
func WarningContextDepth(ctx context.Context, depth int, args ...any) {
ctxlogf(ctx, depth+1, logsink.Warning, false, noStack, defaultFormat(args), args...)
}
// WarningContextDepthf is like [WarningDepthf], but with an extra [context.Context] parameter. The
// context is used to pass the Trace Context to log sinks.
func WarningContextDepthf(ctx context.Context, depth int, format string, args ...any) {
ctxlogf(ctx, depth+1, logsink.Warning, false, noStack, format, args...)
}
// Error logs to the ERROR, WARNING, and INFO logs.
// Arguments are handled in the manner of fmt.Print; a newline is appended if missing.
func Error(args ...any) {
@ -510,8 +616,32 @@ func Errorf(format string, args ...any) {
logf(1, logsink.Error, false, noStack, format, args...)
}
func fatalf(depth int, format string, args ...any) {
logf(depth+1, logsink.Fatal, false, withStack, format, args...)
// ErrorContext is like [Error], but with an extra [context.Context] parameter. The
// context is used to pass the Trace Context to log sinks.
func ErrorContext(ctx context.Context, args ...any) {
ErrorContextDepth(ctx, 1, args...)
}
// ErrorContextf is like [Errorf], but with an extra [context.Context] parameter. The
// context is used to pass the Trace Context to log sinks.
func ErrorContextf(ctx context.Context, format string, args ...any) {
ctxlogf(ctx, 1, logsink.Error, false, noStack, format, args...)
}
// ErrorContextDepth is like [ErrorDepth], but with an extra [context.Context] parameter. The
// context is used to pass the Trace Context to log sinks.
func ErrorContextDepth(ctx context.Context, depth int, args ...any) {
ctxlogf(ctx, depth+1, logsink.Error, false, noStack, defaultFormat(args), args...)
}
// ErrorContextDepthf is like [ErrorDepthf], but with an extra [context.Context] parameter. The
// context is used to pass the Trace Context to log sinks.
func ErrorContextDepthf(ctx context.Context, depth int, format string, args ...any) {
ctxlogf(ctx, depth+1, logsink.Error, false, noStack, format, args...)
}
func ctxfatalf(ctx context.Context, depth int, format string, args ...any) {
ctxlogf(ctx, depth+1, logsink.Fatal, false, withStack, format, args...)
sinks.file.Flush()
err := abortProcess() // Should not return.
@ -523,6 +653,10 @@ func fatalf(depth int, format string, args ...any) {
os.Exit(2) // Exit with the same code as the default SIGABRT handler.
}
func fatalf(depth int, format string, args ...any) {
ctxfatalf(nil, depth+1, format, args...)
}
// Fatal logs to the FATAL, ERROR, WARNING, and INFO logs,
// including a stack trace of all running goroutines, then calls os.Exit(2).
// Arguments are handled in the manner of fmt.Print; a newline is appended if missing.
@ -556,12 +690,39 @@ func Fatalf(format string, args ...any) {
fatalf(1, format, args...)
}
func exitf(depth int, format string, args ...any) {
logf(depth+1, logsink.Fatal, false, noStack, format, args...)
// FatalContext is like [Fatal], but with an extra [context.Context] parameter. The
// context is used to pass the Trace Context to log sinks.
func FatalContext(ctx context.Context, args ...any) {
FatalContextDepth(ctx, 1, args...)
}
// FatalContextf is like [Fatalf], but with an extra [context.Context] parameter. The
// context is used to pass the Trace Context to log sinks.
func FatalContextf(ctx context.Context, format string, args ...any) {
ctxfatalf(ctx, 1, format, args...)
}
// FatalContextDepth is like [FatalDepth], but with an extra [context.Context] parameter. The
// context is used to pass the Trace Context to log sinks.
func FatalContextDepth(ctx context.Context, depth int, args ...any) {
ctxfatalf(ctx, depth+1, defaultFormat(args), args...)
}
// FatalContextDepthf is like [FatalDepthf], but with an extra [context.Context] parameter.
func FatalContextDepthf(ctx context.Context, depth int, format string, args ...any) {
ctxfatalf(ctx, depth+1, format, args...)
}
func ctxexitf(ctx context.Context, depth int, format string, args ...any) {
ctxlogf(ctx, depth+1, logsink.Fatal, false, noStack, format, args...)
sinks.file.Flush()
os.Exit(1)
}
func exitf(depth int, format string, args ...any) {
ctxexitf(nil, depth+1, format, args...)
}
// Exit logs to the FATAL, ERROR, WARNING, and INFO logs, then calls os.Exit(1).
// Arguments are handled in the manner of fmt.Print; a newline is appended if missing.
func Exit(args ...any) {
@ -590,3 +751,27 @@ func Exitln(args ...any) {
func Exitf(format string, args ...any) {
exitf(1, format, args...)
}
// ExitContext is like [Exit], but with an extra [context.Context] parameter. The
// context is used to pass the Trace Context to log sinks.
func ExitContext(ctx context.Context, args ...any) {
ExitContextDepth(ctx, 1, args...)
}
// ExitContextf is like [Exitf], but with an extra [context.Context] parameter. The
// context is used to pass the Trace Context to log sinks.
func ExitContextf(ctx context.Context, format string, args ...any) {
ctxexitf(ctx, 1, format, args...)
}
// ExitContextDepth is like [ExitDepth], but with an extra [context.Context] parameter. The
// context is used to pass the Trace Context to log sinks.
func ExitContextDepth(ctx context.Context, depth int, args ...any) {
ctxexitf(ctx, depth+1, defaultFormat(args), args...)
}
// ExitContextDepthf is like [ExitDepthf], but with an extra [context.Context] parameter. The
// context is used to pass the Trace Context to log sinks.
func ExitContextDepthf(ctx context.Context, depth int, format string, args ...any) {
ctxexitf(ctx, depth+1, format, args...)
}

View file

@ -16,6 +16,7 @@ package logsink
import (
"bytes"
"context"
"fmt"
"strconv"
"strings"
@ -77,6 +78,11 @@ func ParseSeverity(name string) (Severity, error) {
// Meta is metadata about a logging call.
type Meta struct {
// The context with which the log call was made (or nil). If set, the context
// is only valid during the logsink.Structured.Printf call, it should not be
// retained.
Context context.Context
// Time is the time at which the log call was made.
Time time.Time

View file

@ -1,530 +0,0 @@
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package jsonpb
import (
"encoding/json"
"errors"
"fmt"
"io"
"math"
"reflect"
"strconv"
"strings"
"time"
"github.com/golang/protobuf/proto"
"google.golang.org/protobuf/encoding/protojson"
protoV2 "google.golang.org/protobuf/proto"
"google.golang.org/protobuf/reflect/protoreflect"
"google.golang.org/protobuf/reflect/protoregistry"
)
const wrapJSONUnmarshalV2 = false
// UnmarshalNext unmarshals the next JSON object from d into m.
func UnmarshalNext(d *json.Decoder, m proto.Message) error {
return new(Unmarshaler).UnmarshalNext(d, m)
}
// Unmarshal unmarshals a JSON object from r into m.
func Unmarshal(r io.Reader, m proto.Message) error {
return new(Unmarshaler).Unmarshal(r, m)
}
// UnmarshalString unmarshals a JSON object from s into m.
func UnmarshalString(s string, m proto.Message) error {
return new(Unmarshaler).Unmarshal(strings.NewReader(s), m)
}
// Unmarshaler is a configurable object for converting from a JSON
// representation to a protocol buffer object.
type Unmarshaler struct {
// AllowUnknownFields specifies whether to allow messages to contain
// unknown JSON fields, as opposed to failing to unmarshal.
AllowUnknownFields bool
// AnyResolver is used to resolve the google.protobuf.Any well-known type.
// If unset, the global registry is used by default.
AnyResolver AnyResolver
}
// JSONPBUnmarshaler is implemented by protobuf messages that customize the way
// they are unmarshaled from JSON. Messages that implement this should also
// implement JSONPBMarshaler so that the custom format can be produced.
//
// The JSON unmarshaling must follow the JSON to proto specification:
// https://developers.google.com/protocol-buffers/docs/proto3#json
//
// Deprecated: Custom types should implement protobuf reflection instead.
type JSONPBUnmarshaler interface {
UnmarshalJSONPB(*Unmarshaler, []byte) error
}
// Unmarshal unmarshals a JSON object from r into m.
func (u *Unmarshaler) Unmarshal(r io.Reader, m proto.Message) error {
return u.UnmarshalNext(json.NewDecoder(r), m)
}
// UnmarshalNext unmarshals the next JSON object from d into m.
func (u *Unmarshaler) UnmarshalNext(d *json.Decoder, m proto.Message) error {
if m == nil {
return errors.New("invalid nil message")
}
// Parse the next JSON object from the stream.
raw := json.RawMessage{}
if err := d.Decode(&raw); err != nil {
return err
}
// Check for custom unmarshalers first since they may not properly
// implement protobuf reflection that the logic below relies on.
if jsu, ok := m.(JSONPBUnmarshaler); ok {
return jsu.UnmarshalJSONPB(u, raw)
}
mr := proto.MessageReflect(m)
// NOTE: For historical reasons, a top-level null is treated as a noop.
// This is incorrect, but kept for compatibility.
if string(raw) == "null" && mr.Descriptor().FullName() != "google.protobuf.Value" {
return nil
}
if wrapJSONUnmarshalV2 {
// NOTE: If input message is non-empty, we need to preserve merge semantics
// of the old jsonpb implementation. These semantics are not supported by
// the protobuf JSON specification.
isEmpty := true
mr.Range(func(protoreflect.FieldDescriptor, protoreflect.Value) bool {
isEmpty = false // at least one iteration implies non-empty
return false
})
if !isEmpty {
// Perform unmarshaling into a newly allocated, empty message.
mr = mr.New()
// Use a defer to copy all unmarshaled fields into the original message.
dst := proto.MessageReflect(m)
defer mr.Range(func(fd protoreflect.FieldDescriptor, v protoreflect.Value) bool {
dst.Set(fd, v)
return true
})
}
// Unmarshal using the v2 JSON unmarshaler.
opts := protojson.UnmarshalOptions{
DiscardUnknown: u.AllowUnknownFields,
}
if u.AnyResolver != nil {
opts.Resolver = anyResolver{u.AnyResolver}
}
return opts.Unmarshal(raw, mr.Interface())
} else {
if err := u.unmarshalMessage(mr, raw); err != nil {
return err
}
return protoV2.CheckInitialized(mr.Interface())
}
}
func (u *Unmarshaler) unmarshalMessage(m protoreflect.Message, in []byte) error {
md := m.Descriptor()
fds := md.Fields()
if jsu, ok := proto.MessageV1(m.Interface()).(JSONPBUnmarshaler); ok {
return jsu.UnmarshalJSONPB(u, in)
}
if string(in) == "null" && md.FullName() != "google.protobuf.Value" {
return nil
}
switch wellKnownType(md.FullName()) {
case "Any":
var jsonObject map[string]json.RawMessage
if err := json.Unmarshal(in, &jsonObject); err != nil {
return err
}
rawTypeURL, ok := jsonObject["@type"]
if !ok {
return errors.New("Any JSON doesn't have '@type'")
}
typeURL, err := unquoteString(string(rawTypeURL))
if err != nil {
return fmt.Errorf("can't unmarshal Any's '@type': %q", rawTypeURL)
}
m.Set(fds.ByNumber(1), protoreflect.ValueOfString(typeURL))
var m2 protoreflect.Message
if u.AnyResolver != nil {
mi, err := u.AnyResolver.Resolve(typeURL)
if err != nil {
return err
}
m2 = proto.MessageReflect(mi)
} else {
mt, err := protoregistry.GlobalTypes.FindMessageByURL(typeURL)
if err != nil {
if err == protoregistry.NotFound {
return fmt.Errorf("could not resolve Any message type: %v", typeURL)
}
return err
}
m2 = mt.New()
}
if wellKnownType(m2.Descriptor().FullName()) != "" {
rawValue, ok := jsonObject["value"]
if !ok {
return errors.New("Any JSON doesn't have 'value'")
}
if err := u.unmarshalMessage(m2, rawValue); err != nil {
return fmt.Errorf("can't unmarshal Any nested proto %v: %v", typeURL, err)
}
} else {
delete(jsonObject, "@type")
rawJSON, err := json.Marshal(jsonObject)
if err != nil {
return fmt.Errorf("can't generate JSON for Any's nested proto to be unmarshaled: %v", err)
}
if err = u.unmarshalMessage(m2, rawJSON); err != nil {
return fmt.Errorf("can't unmarshal Any nested proto %v: %v", typeURL, err)
}
}
rawWire, err := protoV2.Marshal(m2.Interface())
if err != nil {
return fmt.Errorf("can't marshal proto %v into Any.Value: %v", typeURL, err)
}
m.Set(fds.ByNumber(2), protoreflect.ValueOfBytes(rawWire))
return nil
case "BoolValue", "BytesValue", "StringValue",
"Int32Value", "UInt32Value", "FloatValue",
"Int64Value", "UInt64Value", "DoubleValue":
fd := fds.ByNumber(1)
v, err := u.unmarshalValue(m.NewField(fd), in, fd)
if err != nil {
return err
}
m.Set(fd, v)
return nil
case "Duration":
v, err := unquoteString(string(in))
if err != nil {
return err
}
d, err := time.ParseDuration(v)
if err != nil {
return fmt.Errorf("bad Duration: %v", err)
}
sec := d.Nanoseconds() / 1e9
nsec := d.Nanoseconds() % 1e9
m.Set(fds.ByNumber(1), protoreflect.ValueOfInt64(int64(sec)))
m.Set(fds.ByNumber(2), protoreflect.ValueOfInt32(int32(nsec)))
return nil
case "Timestamp":
v, err := unquoteString(string(in))
if err != nil {
return err
}
t, err := time.Parse(time.RFC3339Nano, v)
if err != nil {
return fmt.Errorf("bad Timestamp: %v", err)
}
sec := t.Unix()
nsec := t.Nanosecond()
m.Set(fds.ByNumber(1), protoreflect.ValueOfInt64(int64(sec)))
m.Set(fds.ByNumber(2), protoreflect.ValueOfInt32(int32(nsec)))
return nil
case "Value":
switch {
case string(in) == "null":
m.Set(fds.ByNumber(1), protoreflect.ValueOfEnum(0))
case string(in) == "true":
m.Set(fds.ByNumber(4), protoreflect.ValueOfBool(true))
case string(in) == "false":
m.Set(fds.ByNumber(4), protoreflect.ValueOfBool(false))
case hasPrefixAndSuffix('"', in, '"'):
s, err := unquoteString(string(in))
if err != nil {
return fmt.Errorf("unrecognized type for Value %q", in)
}
m.Set(fds.ByNumber(3), protoreflect.ValueOfString(s))
case hasPrefixAndSuffix('[', in, ']'):
v := m.Mutable(fds.ByNumber(6))
return u.unmarshalMessage(v.Message(), in)
case hasPrefixAndSuffix('{', in, '}'):
v := m.Mutable(fds.ByNumber(5))
return u.unmarshalMessage(v.Message(), in)
default:
f, err := strconv.ParseFloat(string(in), 0)
if err != nil {
return fmt.Errorf("unrecognized type for Value %q", in)
}
m.Set(fds.ByNumber(2), protoreflect.ValueOfFloat64(f))
}
return nil
case "ListValue":
var jsonArray []json.RawMessage
if err := json.Unmarshal(in, &jsonArray); err != nil {
return fmt.Errorf("bad ListValue: %v", err)
}
lv := m.Mutable(fds.ByNumber(1)).List()
for _, raw := range jsonArray {
ve := lv.NewElement()
if err := u.unmarshalMessage(ve.Message(), raw); err != nil {
return err
}
lv.Append(ve)
}
return nil
case "Struct":
var jsonObject map[string]json.RawMessage
if err := json.Unmarshal(in, &jsonObject); err != nil {
return fmt.Errorf("bad StructValue: %v", err)
}
mv := m.Mutable(fds.ByNumber(1)).Map()
for key, raw := range jsonObject {
kv := protoreflect.ValueOf(key).MapKey()
vv := mv.NewValue()
if err := u.unmarshalMessage(vv.Message(), raw); err != nil {
return fmt.Errorf("bad value in StructValue for key %q: %v", key, err)
}
mv.Set(kv, vv)
}
return nil
}
var jsonObject map[string]json.RawMessage
if err := json.Unmarshal(in, &jsonObject); err != nil {
return err
}
// Handle known fields.
for i := 0; i < fds.Len(); i++ {
fd := fds.Get(i)
if fd.IsWeak() && fd.Message().IsPlaceholder() {
continue // weak reference is not linked in
}
// Search for any raw JSON value associated with this field.
var raw json.RawMessage
name := string(fd.Name())
if fd.Kind() == protoreflect.GroupKind {
name = string(fd.Message().Name())
}
if v, ok := jsonObject[name]; ok {
delete(jsonObject, name)
raw = v
}
name = string(fd.JSONName())
if v, ok := jsonObject[name]; ok {
delete(jsonObject, name)
raw = v
}
field := m.NewField(fd)
// Unmarshal the field value.
if raw == nil || (string(raw) == "null" && !isSingularWellKnownValue(fd) && !isSingularJSONPBUnmarshaler(field, fd)) {
continue
}
v, err := u.unmarshalValue(field, raw, fd)
if err != nil {
return err
}
m.Set(fd, v)
}
// Handle extension fields.
for name, raw := range jsonObject {
if !strings.HasPrefix(name, "[") || !strings.HasSuffix(name, "]") {
continue
}
// Resolve the extension field by name.
xname := protoreflect.FullName(name[len("[") : len(name)-len("]")])
xt, _ := protoregistry.GlobalTypes.FindExtensionByName(xname)
if xt == nil && isMessageSet(md) {
xt, _ = protoregistry.GlobalTypes.FindExtensionByName(xname.Append("message_set_extension"))
}
if xt == nil {
continue
}
delete(jsonObject, name)
fd := xt.TypeDescriptor()
if fd.ContainingMessage().FullName() != m.Descriptor().FullName() {
return fmt.Errorf("extension field %q does not extend message %q", xname, m.Descriptor().FullName())
}
field := m.NewField(fd)
// Unmarshal the field value.
if raw == nil || (string(raw) == "null" && !isSingularWellKnownValue(fd) && !isSingularJSONPBUnmarshaler(field, fd)) {
continue
}
v, err := u.unmarshalValue(field, raw, fd)
if err != nil {
return err
}
m.Set(fd, v)
}
if !u.AllowUnknownFields && len(jsonObject) > 0 {
for name := range jsonObject {
return fmt.Errorf("unknown field %q in %v", name, md.FullName())
}
}
return nil
}
func isSingularWellKnownValue(fd protoreflect.FieldDescriptor) bool {
if fd.Cardinality() == protoreflect.Repeated {
return false
}
if md := fd.Message(); md != nil {
return md.FullName() == "google.protobuf.Value"
}
if ed := fd.Enum(); ed != nil {
return ed.FullName() == "google.protobuf.NullValue"
}
return false
}
func isSingularJSONPBUnmarshaler(v protoreflect.Value, fd protoreflect.FieldDescriptor) bool {
if fd.Message() != nil && fd.Cardinality() != protoreflect.Repeated {
_, ok := proto.MessageV1(v.Interface()).(JSONPBUnmarshaler)
return ok
}
return false
}
func (u *Unmarshaler) unmarshalValue(v protoreflect.Value, in []byte, fd protoreflect.FieldDescriptor) (protoreflect.Value, error) {
switch {
case fd.IsList():
var jsonArray []json.RawMessage
if err := json.Unmarshal(in, &jsonArray); err != nil {
return v, err
}
lv := v.List()
for _, raw := range jsonArray {
ve, err := u.unmarshalSingularValue(lv.NewElement(), raw, fd)
if err != nil {
return v, err
}
lv.Append(ve)
}
return v, nil
case fd.IsMap():
var jsonObject map[string]json.RawMessage
if err := json.Unmarshal(in, &jsonObject); err != nil {
return v, err
}
kfd := fd.MapKey()
vfd := fd.MapValue()
mv := v.Map()
for key, raw := range jsonObject {
var kv protoreflect.MapKey
if kfd.Kind() == protoreflect.StringKind {
kv = protoreflect.ValueOf(key).MapKey()
} else {
v, err := u.unmarshalSingularValue(kfd.Default(), []byte(key), kfd)
if err != nil {
return v, err
}
kv = v.MapKey()
}
vv, err := u.unmarshalSingularValue(mv.NewValue(), raw, vfd)
if err != nil {
return v, err
}
mv.Set(kv, vv)
}
return v, nil
default:
return u.unmarshalSingularValue(v, in, fd)
}
}
var nonFinite = map[string]float64{
`"NaN"`: math.NaN(),
`"Infinity"`: math.Inf(+1),
`"-Infinity"`: math.Inf(-1),
}
func (u *Unmarshaler) unmarshalSingularValue(v protoreflect.Value, in []byte, fd protoreflect.FieldDescriptor) (protoreflect.Value, error) {
switch fd.Kind() {
case protoreflect.BoolKind:
return unmarshalValue(in, new(bool))
case protoreflect.Int32Kind, protoreflect.Sint32Kind, protoreflect.Sfixed32Kind:
return unmarshalValue(trimQuote(in), new(int32))
case protoreflect.Int64Kind, protoreflect.Sint64Kind, protoreflect.Sfixed64Kind:
return unmarshalValue(trimQuote(in), new(int64))
case protoreflect.Uint32Kind, protoreflect.Fixed32Kind:
return unmarshalValue(trimQuote(in), new(uint32))
case protoreflect.Uint64Kind, protoreflect.Fixed64Kind:
return unmarshalValue(trimQuote(in), new(uint64))
case protoreflect.FloatKind:
if f, ok := nonFinite[string(in)]; ok {
return protoreflect.ValueOfFloat32(float32(f)), nil
}
return unmarshalValue(trimQuote(in), new(float32))
case protoreflect.DoubleKind:
if f, ok := nonFinite[string(in)]; ok {
return protoreflect.ValueOfFloat64(float64(f)), nil
}
return unmarshalValue(trimQuote(in), new(float64))
case protoreflect.StringKind:
return unmarshalValue(in, new(string))
case protoreflect.BytesKind:
return unmarshalValue(in, new([]byte))
case protoreflect.EnumKind:
if hasPrefixAndSuffix('"', in, '"') {
vd := fd.Enum().Values().ByName(protoreflect.Name(trimQuote(in)))
if vd == nil {
return v, fmt.Errorf("unknown value %q for enum %s", in, fd.Enum().FullName())
}
return protoreflect.ValueOfEnum(vd.Number()), nil
}
return unmarshalValue(in, new(protoreflect.EnumNumber))
case protoreflect.MessageKind, protoreflect.GroupKind:
err := u.unmarshalMessage(v.Message(), in)
return v, err
default:
panic(fmt.Sprintf("invalid kind %v", fd.Kind()))
}
}
func unmarshalValue(in []byte, v interface{}) (protoreflect.Value, error) {
err := json.Unmarshal(in, v)
return protoreflect.ValueOf(reflect.ValueOf(v).Elem().Interface()), err
}
func unquoteString(in string) (out string, err error) {
err = json.Unmarshal([]byte(in), &out)
return out, err
}
func hasPrefixAndSuffix(prefix byte, in []byte, suffix byte) bool {
if len(in) >= 2 && in[0] == prefix && in[len(in)-1] == suffix {
return true
}
return false
}
// trimQuote is like unquoteString but simply strips surrounding quotes.
// This is incorrect, but is behavior done by the legacy implementation.
func trimQuote(in []byte) []byte {
if len(in) >= 2 && in[0] == '"' && in[len(in)-1] == '"' {
in = in[1 : len(in)-1]
}
return in
}

View file

@ -1,559 +0,0 @@
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package jsonpb
import (
"encoding/json"
"errors"
"fmt"
"io"
"math"
"reflect"
"sort"
"strconv"
"strings"
"time"
"github.com/golang/protobuf/proto"
"google.golang.org/protobuf/encoding/protojson"
protoV2 "google.golang.org/protobuf/proto"
"google.golang.org/protobuf/reflect/protoreflect"
"google.golang.org/protobuf/reflect/protoregistry"
)
const wrapJSONMarshalV2 = false
// Marshaler is a configurable object for marshaling protocol buffer messages
// to the specified JSON representation.
type Marshaler struct {
// OrigName specifies whether to use the original protobuf name for fields.
OrigName bool
// EnumsAsInts specifies whether to render enum values as integers,
// as opposed to string values.
EnumsAsInts bool
// EmitDefaults specifies whether to render fields with zero values.
EmitDefaults bool
// Indent controls whether the output is compact or not.
// If empty, the output is compact JSON. Otherwise, every JSON object
// entry and JSON array value will be on its own line.
// Each line will be preceded by repeated copies of Indent, where the
// number of copies is the current indentation depth.
Indent string
// AnyResolver is used to resolve the google.protobuf.Any well-known type.
// If unset, the global registry is used by default.
AnyResolver AnyResolver
}
// JSONPBMarshaler is implemented by protobuf messages that customize the
// way they are marshaled to JSON. Messages that implement this should also
// implement JSONPBUnmarshaler so that the custom format can be parsed.
//
// The JSON marshaling must follow the proto to JSON specification:
// https://developers.google.com/protocol-buffers/docs/proto3#json
//
// Deprecated: Custom types should implement protobuf reflection instead.
type JSONPBMarshaler interface {
MarshalJSONPB(*Marshaler) ([]byte, error)
}
// Marshal serializes a protobuf message as JSON into w.
func (jm *Marshaler) Marshal(w io.Writer, m proto.Message) error {
b, err := jm.marshal(m)
if len(b) > 0 {
if _, err := w.Write(b); err != nil {
return err
}
}
return err
}
// MarshalToString serializes a protobuf message as JSON in string form.
func (jm *Marshaler) MarshalToString(m proto.Message) (string, error) {
b, err := jm.marshal(m)
if err != nil {
return "", err
}
return string(b), nil
}
func (jm *Marshaler) marshal(m proto.Message) ([]byte, error) {
v := reflect.ValueOf(m)
if m == nil || (v.Kind() == reflect.Ptr && v.IsNil()) {
return nil, errors.New("Marshal called with nil")
}
// Check for custom marshalers first since they may not properly
// implement protobuf reflection that the logic below relies on.
if jsm, ok := m.(JSONPBMarshaler); ok {
return jsm.MarshalJSONPB(jm)
}
if wrapJSONMarshalV2 {
opts := protojson.MarshalOptions{
UseProtoNames: jm.OrigName,
UseEnumNumbers: jm.EnumsAsInts,
EmitUnpopulated: jm.EmitDefaults,
Indent: jm.Indent,
}
if jm.AnyResolver != nil {
opts.Resolver = anyResolver{jm.AnyResolver}
}
return opts.Marshal(proto.MessageReflect(m).Interface())
} else {
// Check for unpopulated required fields first.
m2 := proto.MessageReflect(m)
if err := protoV2.CheckInitialized(m2.Interface()); err != nil {
return nil, err
}
w := jsonWriter{Marshaler: jm}
err := w.marshalMessage(m2, "", "")
return w.buf, err
}
}
type jsonWriter struct {
*Marshaler
buf []byte
}
func (w *jsonWriter) write(s string) {
w.buf = append(w.buf, s...)
}
func (w *jsonWriter) marshalMessage(m protoreflect.Message, indent, typeURL string) error {
if jsm, ok := proto.MessageV1(m.Interface()).(JSONPBMarshaler); ok {
b, err := jsm.MarshalJSONPB(w.Marshaler)
if err != nil {
return err
}
if typeURL != "" {
// we are marshaling this object to an Any type
var js map[string]*json.RawMessage
if err = json.Unmarshal(b, &js); err != nil {
return fmt.Errorf("type %T produced invalid JSON: %v", m.Interface(), err)
}
turl, err := json.Marshal(typeURL)
if err != nil {
return fmt.Errorf("failed to marshal type URL %q to JSON: %v", typeURL, err)
}
js["@type"] = (*json.RawMessage)(&turl)
if b, err = json.Marshal(js); err != nil {
return err
}
}
w.write(string(b))
return nil
}
md := m.Descriptor()
fds := md.Fields()
// Handle well-known types.
const secondInNanos = int64(time.Second / time.Nanosecond)
switch wellKnownType(md.FullName()) {
case "Any":
return w.marshalAny(m, indent)
case "BoolValue", "BytesValue", "StringValue",
"Int32Value", "UInt32Value", "FloatValue",
"Int64Value", "UInt64Value", "DoubleValue":
fd := fds.ByNumber(1)
return w.marshalValue(fd, m.Get(fd), indent)
case "Duration":
const maxSecondsInDuration = 315576000000
// "Generated output always contains 0, 3, 6, or 9 fractional digits,
// depending on required precision."
s := m.Get(fds.ByNumber(1)).Int()
ns := m.Get(fds.ByNumber(2)).Int()
if s < -maxSecondsInDuration || s > maxSecondsInDuration {
return fmt.Errorf("seconds out of range %v", s)
}
if ns <= -secondInNanos || ns >= secondInNanos {
return fmt.Errorf("ns out of range (%v, %v)", -secondInNanos, secondInNanos)
}
if (s > 0 && ns < 0) || (s < 0 && ns > 0) {
return errors.New("signs of seconds and nanos do not match")
}
var sign string
if s < 0 || ns < 0 {
sign, s, ns = "-", -1*s, -1*ns
}
x := fmt.Sprintf("%s%d.%09d", sign, s, ns)
x = strings.TrimSuffix(x, "000")
x = strings.TrimSuffix(x, "000")
x = strings.TrimSuffix(x, ".000")
w.write(fmt.Sprintf(`"%vs"`, x))
return nil
case "Timestamp":
// "RFC 3339, where generated output will always be Z-normalized
// and uses 0, 3, 6 or 9 fractional digits."
s := m.Get(fds.ByNumber(1)).Int()
ns := m.Get(fds.ByNumber(2)).Int()
if ns < 0 || ns >= secondInNanos {
return fmt.Errorf("ns out of range [0, %v)", secondInNanos)
}
t := time.Unix(s, ns).UTC()
// time.RFC3339Nano isn't exactly right (we need to get 3/6/9 fractional digits).
x := t.Format("2006-01-02T15:04:05.000000000")
x = strings.TrimSuffix(x, "000")
x = strings.TrimSuffix(x, "000")
x = strings.TrimSuffix(x, ".000")
w.write(fmt.Sprintf(`"%vZ"`, x))
return nil
case "Value":
// JSON value; which is a null, number, string, bool, object, or array.
od := md.Oneofs().Get(0)
fd := m.WhichOneof(od)
if fd == nil {
return errors.New("nil Value")
}
return w.marshalValue(fd, m.Get(fd), indent)
case "Struct", "ListValue":
// JSON object or array.
fd := fds.ByNumber(1)
return w.marshalValue(fd, m.Get(fd), indent)
}
w.write("{")
if w.Indent != "" {
w.write("\n")
}
firstField := true
if typeURL != "" {
if err := w.marshalTypeURL(indent, typeURL); err != nil {
return err
}
firstField = false
}
for i := 0; i < fds.Len(); {
fd := fds.Get(i)
if od := fd.ContainingOneof(); od != nil {
fd = m.WhichOneof(od)
i += od.Fields().Len()
if fd == nil {
continue
}
} else {
i++
}
v := m.Get(fd)
if !m.Has(fd) {
if !w.EmitDefaults || fd.ContainingOneof() != nil {
continue
}
if fd.Cardinality() != protoreflect.Repeated && (fd.Message() != nil || fd.Syntax() == protoreflect.Proto2) {
v = protoreflect.Value{} // use "null" for singular messages or proto2 scalars
}
}
if !firstField {
w.writeComma()
}
if err := w.marshalField(fd, v, indent); err != nil {
return err
}
firstField = false
}
// Handle proto2 extensions.
if md.ExtensionRanges().Len() > 0 {
// Collect a sorted list of all extension descriptor and values.
type ext struct {
desc protoreflect.FieldDescriptor
val protoreflect.Value
}
var exts []ext
m.Range(func(fd protoreflect.FieldDescriptor, v protoreflect.Value) bool {
if fd.IsExtension() {
exts = append(exts, ext{fd, v})
}
return true
})
sort.Slice(exts, func(i, j int) bool {
return exts[i].desc.Number() < exts[j].desc.Number()
})
for _, ext := range exts {
if !firstField {
w.writeComma()
}
if err := w.marshalField(ext.desc, ext.val, indent); err != nil {
return err
}
firstField = false
}
}
if w.Indent != "" {
w.write("\n")
w.write(indent)
}
w.write("}")
return nil
}
func (w *jsonWriter) writeComma() {
if w.Indent != "" {
w.write(",\n")
} else {
w.write(",")
}
}
func (w *jsonWriter) marshalAny(m protoreflect.Message, indent string) error {
// "If the Any contains a value that has a special JSON mapping,
// it will be converted as follows: {"@type": xxx, "value": yyy}.
// Otherwise, the value will be converted into a JSON object,
// and the "@type" field will be inserted to indicate the actual data type."
md := m.Descriptor()
typeURL := m.Get(md.Fields().ByNumber(1)).String()
rawVal := m.Get(md.Fields().ByNumber(2)).Bytes()
var m2 protoreflect.Message
if w.AnyResolver != nil {
mi, err := w.AnyResolver.Resolve(typeURL)
if err != nil {
return err
}
m2 = proto.MessageReflect(mi)
} else {
mt, err := protoregistry.GlobalTypes.FindMessageByURL(typeURL)
if err != nil {
return err
}
m2 = mt.New()
}
if err := protoV2.Unmarshal(rawVal, m2.Interface()); err != nil {
return err
}
if wellKnownType(m2.Descriptor().FullName()) == "" {
return w.marshalMessage(m2, indent, typeURL)
}
w.write("{")
if w.Indent != "" {
w.write("\n")
}
if err := w.marshalTypeURL(indent, typeURL); err != nil {
return err
}
w.writeComma()
if w.Indent != "" {
w.write(indent)
w.write(w.Indent)
w.write(`"value": `)
} else {
w.write(`"value":`)
}
if err := w.marshalMessage(m2, indent+w.Indent, ""); err != nil {
return err
}
if w.Indent != "" {
w.write("\n")
w.write(indent)
}
w.write("}")
return nil
}
func (w *jsonWriter) marshalTypeURL(indent, typeURL string) error {
if w.Indent != "" {
w.write(indent)
w.write(w.Indent)
}
w.write(`"@type":`)
if w.Indent != "" {
w.write(" ")
}
b, err := json.Marshal(typeURL)
if err != nil {
return err
}
w.write(string(b))
return nil
}
// marshalField writes field description and value to the Writer.
func (w *jsonWriter) marshalField(fd protoreflect.FieldDescriptor, v protoreflect.Value, indent string) error {
if w.Indent != "" {
w.write(indent)
w.write(w.Indent)
}
w.write(`"`)
switch {
case fd.IsExtension():
// For message set, use the fname of the message as the extension name.
name := string(fd.FullName())
if isMessageSet(fd.ContainingMessage()) {
name = strings.TrimSuffix(name, ".message_set_extension")
}
w.write("[" + name + "]")
case w.OrigName:
name := string(fd.Name())
if fd.Kind() == protoreflect.GroupKind {
name = string(fd.Message().Name())
}
w.write(name)
default:
w.write(string(fd.JSONName()))
}
w.write(`":`)
if w.Indent != "" {
w.write(" ")
}
return w.marshalValue(fd, v, indent)
}
func (w *jsonWriter) marshalValue(fd protoreflect.FieldDescriptor, v protoreflect.Value, indent string) error {
switch {
case fd.IsList():
w.write("[")
comma := ""
lv := v.List()
for i := 0; i < lv.Len(); i++ {
w.write(comma)
if w.Indent != "" {
w.write("\n")
w.write(indent)
w.write(w.Indent)
w.write(w.Indent)
}
if err := w.marshalSingularValue(fd, lv.Get(i), indent+w.Indent); err != nil {
return err
}
comma = ","
}
if w.Indent != "" {
w.write("\n")
w.write(indent)
w.write(w.Indent)
}
w.write("]")
return nil
case fd.IsMap():
kfd := fd.MapKey()
vfd := fd.MapValue()
mv := v.Map()
// Collect a sorted list of all map keys and values.
type entry struct{ key, val protoreflect.Value }
var entries []entry
mv.Range(func(k protoreflect.MapKey, v protoreflect.Value) bool {
entries = append(entries, entry{k.Value(), v})
return true
})
sort.Slice(entries, func(i, j int) bool {
switch kfd.Kind() {
case protoreflect.BoolKind:
return !entries[i].key.Bool() && entries[j].key.Bool()
case protoreflect.Int32Kind, protoreflect.Sint32Kind, protoreflect.Sfixed32Kind, protoreflect.Int64Kind, protoreflect.Sint64Kind, protoreflect.Sfixed64Kind:
return entries[i].key.Int() < entries[j].key.Int()
case protoreflect.Uint32Kind, protoreflect.Fixed32Kind, protoreflect.Uint64Kind, protoreflect.Fixed64Kind:
return entries[i].key.Uint() < entries[j].key.Uint()
case protoreflect.StringKind:
return entries[i].key.String() < entries[j].key.String()
default:
panic("invalid kind")
}
})
w.write(`{`)
comma := ""
for _, entry := range entries {
w.write(comma)
if w.Indent != "" {
w.write("\n")
w.write(indent)
w.write(w.Indent)
w.write(w.Indent)
}
s := fmt.Sprint(entry.key.Interface())
b, err := json.Marshal(s)
if err != nil {
return err
}
w.write(string(b))
w.write(`:`)
if w.Indent != "" {
w.write(` `)
}
if err := w.marshalSingularValue(vfd, entry.val, indent+w.Indent); err != nil {
return err
}
comma = ","
}
if w.Indent != "" {
w.write("\n")
w.write(indent)
w.write(w.Indent)
}
w.write(`}`)
return nil
default:
return w.marshalSingularValue(fd, v, indent)
}
}
func (w *jsonWriter) marshalSingularValue(fd protoreflect.FieldDescriptor, v protoreflect.Value, indent string) error {
switch {
case !v.IsValid():
w.write("null")
return nil
case fd.Message() != nil:
return w.marshalMessage(v.Message(), indent+w.Indent, "")
case fd.Enum() != nil:
if fd.Enum().FullName() == "google.protobuf.NullValue" {
w.write("null")
return nil
}
vd := fd.Enum().Values().ByNumber(v.Enum())
if vd == nil || w.EnumsAsInts {
w.write(strconv.Itoa(int(v.Enum())))
} else {
w.write(`"` + string(vd.Name()) + `"`)
}
return nil
default:
switch v.Interface().(type) {
case float32, float64:
switch {
case math.IsInf(v.Float(), +1):
w.write(`"Infinity"`)
return nil
case math.IsInf(v.Float(), -1):
w.write(`"-Infinity"`)
return nil
case math.IsNaN(v.Float()):
w.write(`"NaN"`)
return nil
}
case int64, uint64:
w.write(fmt.Sprintf(`"%d"`, v.Interface()))
return nil
}
b, err := json.Marshal(v.Interface())
if err != nil {
return err
}
w.write(string(b))
return nil
}
}

View file

@ -1,69 +0,0 @@
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package jsonpb provides functionality to marshal and unmarshal between a
// protocol buffer message and JSON. It follows the specification at
// https://developers.google.com/protocol-buffers/docs/proto3#json.
//
// Do not rely on the default behavior of the standard encoding/json package
// when called on generated message types as it does not operate correctly.
//
// Deprecated: Use the "google.golang.org/protobuf/encoding/protojson"
// package instead.
package jsonpb
import (
"github.com/golang/protobuf/proto"
"google.golang.org/protobuf/reflect/protoreflect"
"google.golang.org/protobuf/reflect/protoregistry"
"google.golang.org/protobuf/runtime/protoimpl"
)
// AnyResolver takes a type URL, present in an Any message,
// and resolves it into an instance of the associated message.
type AnyResolver interface {
Resolve(typeURL string) (proto.Message, error)
}
type anyResolver struct{ AnyResolver }
func (r anyResolver) FindMessageByName(message protoreflect.FullName) (protoreflect.MessageType, error) {
return r.FindMessageByURL(string(message))
}
func (r anyResolver) FindMessageByURL(url string) (protoreflect.MessageType, error) {
m, err := r.Resolve(url)
if err != nil {
return nil, err
}
return protoimpl.X.MessageTypeOf(m), nil
}
func (r anyResolver) FindExtensionByName(field protoreflect.FullName) (protoreflect.ExtensionType, error) {
return protoregistry.GlobalTypes.FindExtensionByName(field)
}
func (r anyResolver) FindExtensionByNumber(message protoreflect.FullName, field protoreflect.FieldNumber) (protoreflect.ExtensionType, error) {
return protoregistry.GlobalTypes.FindExtensionByNumber(message, field)
}
func wellKnownType(s protoreflect.FullName) string {
if s.Parent() == "google.protobuf" {
switch s.Name() {
case "Empty", "Any",
"BoolValue", "BytesValue", "StringValue",
"Int32Value", "UInt32Value", "FloatValue",
"Int64Value", "UInt64Value", "DoubleValue",
"Duration", "Timestamp",
"NullValue", "Struct", "Value", "ListValue":
return string(s.Name())
}
}
return ""
}
func isMessageSet(md protoreflect.MessageDescriptor) bool {
ms, ok := md.(interface{ IsMessageSet() bool })
return ok && ms.IsMessageSet()
}

View file

@ -1,179 +0,0 @@
// Copyright 2016 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package ptypes
import (
"fmt"
"strings"
"github.com/golang/protobuf/proto"
"google.golang.org/protobuf/reflect/protoreflect"
"google.golang.org/protobuf/reflect/protoregistry"
anypb "github.com/golang/protobuf/ptypes/any"
)
const urlPrefix = "type.googleapis.com/"
// AnyMessageName returns the message name contained in an anypb.Any message.
// Most type assertions should use the Is function instead.
//
// Deprecated: Call the any.MessageName method instead.
func AnyMessageName(any *anypb.Any) (string, error) {
name, err := anyMessageName(any)
return string(name), err
}
func anyMessageName(any *anypb.Any) (protoreflect.FullName, error) {
if any == nil {
return "", fmt.Errorf("message is nil")
}
name := protoreflect.FullName(any.TypeUrl)
if i := strings.LastIndex(any.TypeUrl, "/"); i >= 0 {
name = name[i+len("/"):]
}
if !name.IsValid() {
return "", fmt.Errorf("message type url %q is invalid", any.TypeUrl)
}
return name, nil
}
// MarshalAny marshals the given message m into an anypb.Any message.
//
// Deprecated: Call the anypb.New function instead.
func MarshalAny(m proto.Message) (*anypb.Any, error) {
switch dm := m.(type) {
case DynamicAny:
m = dm.Message
case *DynamicAny:
if dm == nil {
return nil, proto.ErrNil
}
m = dm.Message
}
b, err := proto.Marshal(m)
if err != nil {
return nil, err
}
return &anypb.Any{TypeUrl: urlPrefix + proto.MessageName(m), Value: b}, nil
}
// Empty returns a new message of the type specified in an anypb.Any message.
// It returns protoregistry.NotFound if the corresponding message type could not
// be resolved in the global registry.
//
// Deprecated: Use protoregistry.GlobalTypes.FindMessageByName instead
// to resolve the message name and create a new instance of it.
func Empty(any *anypb.Any) (proto.Message, error) {
name, err := anyMessageName(any)
if err != nil {
return nil, err
}
mt, err := protoregistry.GlobalTypes.FindMessageByName(name)
if err != nil {
return nil, err
}
return proto.MessageV1(mt.New().Interface()), nil
}
// UnmarshalAny unmarshals the encoded value contained in the anypb.Any message
// into the provided message m. It returns an error if the target message
// does not match the type in the Any message or if an unmarshal error occurs.
//
// The target message m may be a *DynamicAny message. If the underlying message
// type could not be resolved, then this returns protoregistry.NotFound.
//
// Deprecated: Call the any.UnmarshalTo method instead.
func UnmarshalAny(any *anypb.Any, m proto.Message) error {
if dm, ok := m.(*DynamicAny); ok {
if dm.Message == nil {
var err error
dm.Message, err = Empty(any)
if err != nil {
return err
}
}
m = dm.Message
}
anyName, err := AnyMessageName(any)
if err != nil {
return err
}
msgName := proto.MessageName(m)
if anyName != msgName {
return fmt.Errorf("mismatched message type: got %q want %q", anyName, msgName)
}
return proto.Unmarshal(any.Value, m)
}
// Is reports whether the Any message contains a message of the specified type.
//
// Deprecated: Call the any.MessageIs method instead.
func Is(any *anypb.Any, m proto.Message) bool {
if any == nil || m == nil {
return false
}
name := proto.MessageName(m)
if !strings.HasSuffix(any.TypeUrl, name) {
return false
}
return len(any.TypeUrl) == len(name) || any.TypeUrl[len(any.TypeUrl)-len(name)-1] == '/'
}
// DynamicAny is a value that can be passed to UnmarshalAny to automatically
// allocate a proto.Message for the type specified in an anypb.Any message.
// The allocated message is stored in the embedded proto.Message.
//
// Example:
// var x ptypes.DynamicAny
// if err := ptypes.UnmarshalAny(a, &x); err != nil { ... }
// fmt.Printf("unmarshaled message: %v", x.Message)
//
// Deprecated: Use the any.UnmarshalNew method instead to unmarshal
// the any message contents into a new instance of the underlying message.
type DynamicAny struct{ proto.Message }
func (m DynamicAny) String() string {
if m.Message == nil {
return "<nil>"
}
return m.Message.String()
}
func (m DynamicAny) Reset() {
if m.Message == nil {
return
}
m.Message.Reset()
}
func (m DynamicAny) ProtoMessage() {
return
}
func (m DynamicAny) ProtoReflect() protoreflect.Message {
if m.Message == nil {
return nil
}
return dynamicAny{proto.MessageReflect(m.Message)}
}
type dynamicAny struct{ protoreflect.Message }
func (m dynamicAny) Type() protoreflect.MessageType {
return dynamicAnyType{m.Message.Type()}
}
func (m dynamicAny) New() protoreflect.Message {
return dynamicAnyType{m.Message.Type()}.New()
}
func (m dynamicAny) Interface() protoreflect.ProtoMessage {
return DynamicAny{proto.MessageV1(m.Message.Interface())}
}
type dynamicAnyType struct{ protoreflect.MessageType }
func (t dynamicAnyType) New() protoreflect.Message {
return dynamicAny{t.MessageType.New()}
}
func (t dynamicAnyType) Zero() protoreflect.Message {
return dynamicAny{t.MessageType.Zero()}
}

View file

@ -1,62 +0,0 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// source: github.com/golang/protobuf/ptypes/any/any.proto
package any
import (
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
anypb "google.golang.org/protobuf/types/known/anypb"
reflect "reflect"
)
// Symbols defined in public import of google/protobuf/any.proto.
type Any = anypb.Any
var File_github_com_golang_protobuf_ptypes_any_any_proto protoreflect.FileDescriptor
var file_github_com_golang_protobuf_ptypes_any_any_proto_rawDesc = []byte{
0x0a, 0x2f, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x67, 0x6f, 0x6c,
0x61, 0x6e, 0x67, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x70, 0x74, 0x79,
0x70, 0x65, 0x73, 0x2f, 0x61, 0x6e, 0x79, 0x2f, 0x61, 0x6e, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74,
0x6f, 0x1a, 0x19, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62,
0x75, 0x66, 0x2f, 0x61, 0x6e, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x42, 0x2b, 0x5a, 0x29,
0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x67, 0x6f, 0x6c, 0x61, 0x6e,
0x67, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x70, 0x74, 0x79, 0x70, 0x65,
0x73, 0x2f, 0x61, 0x6e, 0x79, 0x3b, 0x61, 0x6e, 0x79, 0x50, 0x00, 0x62, 0x06, 0x70, 0x72, 0x6f,
0x74, 0x6f, 0x33,
}
var file_github_com_golang_protobuf_ptypes_any_any_proto_goTypes = []interface{}{}
var file_github_com_golang_protobuf_ptypes_any_any_proto_depIdxs = []int32{
0, // [0:0] is the sub-list for method output_type
0, // [0:0] is the sub-list for method input_type
0, // [0:0] is the sub-list for extension type_name
0, // [0:0] is the sub-list for extension extendee
0, // [0:0] is the sub-list for field type_name
}
func init() { file_github_com_golang_protobuf_ptypes_any_any_proto_init() }
func file_github_com_golang_protobuf_ptypes_any_any_proto_init() {
if File_github_com_golang_protobuf_ptypes_any_any_proto != nil {
return
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: file_github_com_golang_protobuf_ptypes_any_any_proto_rawDesc,
NumEnums: 0,
NumMessages: 0,
NumExtensions: 0,
NumServices: 0,
},
GoTypes: file_github_com_golang_protobuf_ptypes_any_any_proto_goTypes,
DependencyIndexes: file_github_com_golang_protobuf_ptypes_any_any_proto_depIdxs,
}.Build()
File_github_com_golang_protobuf_ptypes_any_any_proto = out.File
file_github_com_golang_protobuf_ptypes_any_any_proto_rawDesc = nil
file_github_com_golang_protobuf_ptypes_any_any_proto_goTypes = nil
file_github_com_golang_protobuf_ptypes_any_any_proto_depIdxs = nil
}

View file

@ -1,10 +0,0 @@
// Copyright 2016 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package ptypes provides functionality for interacting with well-known types.
//
// Deprecated: Well-known types have specialized functionality directly
// injected into the generated packages for each message type.
// See the deprecation notice for each function for the suggested alternative.
package ptypes

View file

@ -1,76 +0,0 @@
// Copyright 2016 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package ptypes
import (
"errors"
"fmt"
"time"
durationpb "github.com/golang/protobuf/ptypes/duration"
)
// Range of google.protobuf.Duration as specified in duration.proto.
// This is about 10,000 years in seconds.
const (
maxSeconds = int64(10000 * 365.25 * 24 * 60 * 60)
minSeconds = -maxSeconds
)
// Duration converts a durationpb.Duration to a time.Duration.
// Duration returns an error if dur is invalid or overflows a time.Duration.
//
// Deprecated: Call the dur.AsDuration and dur.CheckValid methods instead.
func Duration(dur *durationpb.Duration) (time.Duration, error) {
if err := validateDuration(dur); err != nil {
return 0, err
}
d := time.Duration(dur.Seconds) * time.Second
if int64(d/time.Second) != dur.Seconds {
return 0, fmt.Errorf("duration: %v is out of range for time.Duration", dur)
}
if dur.Nanos != 0 {
d += time.Duration(dur.Nanos) * time.Nanosecond
if (d < 0) != (dur.Nanos < 0) {
return 0, fmt.Errorf("duration: %v is out of range for time.Duration", dur)
}
}
return d, nil
}
// DurationProto converts a time.Duration to a durationpb.Duration.
//
// Deprecated: Call the durationpb.New function instead.
func DurationProto(d time.Duration) *durationpb.Duration {
nanos := d.Nanoseconds()
secs := nanos / 1e9
nanos -= secs * 1e9
return &durationpb.Duration{
Seconds: int64(secs),
Nanos: int32(nanos),
}
}
// validateDuration determines whether the durationpb.Duration is valid
// according to the definition in google/protobuf/duration.proto.
// A valid durpb.Duration may still be too large to fit into a time.Duration
// Note that the range of durationpb.Duration is about 10,000 years,
// while the range of time.Duration is about 290 years.
func validateDuration(dur *durationpb.Duration) error {
if dur == nil {
return errors.New("duration: nil Duration")
}
if dur.Seconds < minSeconds || dur.Seconds > maxSeconds {
return fmt.Errorf("duration: %v: seconds out of range", dur)
}
if dur.Nanos <= -1e9 || dur.Nanos >= 1e9 {
return fmt.Errorf("duration: %v: nanos out of range", dur)
}
// Seconds and Nanos must have the same sign, unless d.Nanos is zero.
if (dur.Seconds < 0 && dur.Nanos > 0) || (dur.Seconds > 0 && dur.Nanos < 0) {
return fmt.Errorf("duration: %v: seconds and nanos have different signs", dur)
}
return nil
}

View file

@ -1,63 +0,0 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// source: github.com/golang/protobuf/ptypes/duration/duration.proto
package duration
import (
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
durationpb "google.golang.org/protobuf/types/known/durationpb"
reflect "reflect"
)
// Symbols defined in public import of google/protobuf/duration.proto.
type Duration = durationpb.Duration
var File_github_com_golang_protobuf_ptypes_duration_duration_proto protoreflect.FileDescriptor
var file_github_com_golang_protobuf_ptypes_duration_duration_proto_rawDesc = []byte{
0x0a, 0x39, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x67, 0x6f, 0x6c,
0x61, 0x6e, 0x67, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x70, 0x74, 0x79,
0x70, 0x65, 0x73, 0x2f, 0x64, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x2f, 0x64, 0x75, 0x72,
0x61, 0x74, 0x69, 0x6f, 0x6e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x1e, 0x67, 0x6f, 0x6f,
0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x64, 0x75, 0x72,
0x61, 0x74, 0x69, 0x6f, 0x6e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x42, 0x35, 0x5a, 0x33, 0x67,
0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x67, 0x6f, 0x6c, 0x61, 0x6e, 0x67,
0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x70, 0x74, 0x79, 0x70, 0x65, 0x73,
0x2f, 0x64, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x3b, 0x64, 0x75, 0x72, 0x61, 0x74, 0x69,
0x6f, 0x6e, 0x50, 0x00, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
}
var file_github_com_golang_protobuf_ptypes_duration_duration_proto_goTypes = []interface{}{}
var file_github_com_golang_protobuf_ptypes_duration_duration_proto_depIdxs = []int32{
0, // [0:0] is the sub-list for method output_type
0, // [0:0] is the sub-list for method input_type
0, // [0:0] is the sub-list for extension type_name
0, // [0:0] is the sub-list for extension extendee
0, // [0:0] is the sub-list for field type_name
}
func init() { file_github_com_golang_protobuf_ptypes_duration_duration_proto_init() }
func file_github_com_golang_protobuf_ptypes_duration_duration_proto_init() {
if File_github_com_golang_protobuf_ptypes_duration_duration_proto != nil {
return
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: file_github_com_golang_protobuf_ptypes_duration_duration_proto_rawDesc,
NumEnums: 0,
NumMessages: 0,
NumExtensions: 0,
NumServices: 0,
},
GoTypes: file_github_com_golang_protobuf_ptypes_duration_duration_proto_goTypes,
DependencyIndexes: file_github_com_golang_protobuf_ptypes_duration_duration_proto_depIdxs,
}.Build()
File_github_com_golang_protobuf_ptypes_duration_duration_proto = out.File
file_github_com_golang_protobuf_ptypes_duration_duration_proto_rawDesc = nil
file_github_com_golang_protobuf_ptypes_duration_duration_proto_goTypes = nil
file_github_com_golang_protobuf_ptypes_duration_duration_proto_depIdxs = nil
}

View file

@ -1,112 +0,0 @@
// Copyright 2016 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package ptypes
import (
"errors"
"fmt"
"time"
timestamppb "github.com/golang/protobuf/ptypes/timestamp"
)
// Range of google.protobuf.Duration as specified in timestamp.proto.
const (
// Seconds field of the earliest valid Timestamp.
// This is time.Date(1, 1, 1, 0, 0, 0, 0, time.UTC).Unix().
minValidSeconds = -62135596800
// Seconds field just after the latest valid Timestamp.
// This is time.Date(10000, 1, 1, 0, 0, 0, 0, time.UTC).Unix().
maxValidSeconds = 253402300800
)
// Timestamp converts a timestamppb.Timestamp to a time.Time.
// It returns an error if the argument is invalid.
//
// Unlike most Go functions, if Timestamp returns an error, the first return
// value is not the zero time.Time. Instead, it is the value obtained from the
// time.Unix function when passed the contents of the Timestamp, in the UTC
// locale. This may or may not be a meaningful time; many invalid Timestamps
// do map to valid time.Times.
//
// A nil Timestamp returns an error. The first return value in that case is
// undefined.
//
// Deprecated: Call the ts.AsTime and ts.CheckValid methods instead.
func Timestamp(ts *timestamppb.Timestamp) (time.Time, error) {
// Don't return the zero value on error, because corresponds to a valid
// timestamp. Instead return whatever time.Unix gives us.
var t time.Time
if ts == nil {
t = time.Unix(0, 0).UTC() // treat nil like the empty Timestamp
} else {
t = time.Unix(ts.Seconds, int64(ts.Nanos)).UTC()
}
return t, validateTimestamp(ts)
}
// TimestampNow returns a google.protobuf.Timestamp for the current time.
//
// Deprecated: Call the timestamppb.Now function instead.
func TimestampNow() *timestamppb.Timestamp {
ts, err := TimestampProto(time.Now())
if err != nil {
panic("ptypes: time.Now() out of Timestamp range")
}
return ts
}
// TimestampProto converts the time.Time to a google.protobuf.Timestamp proto.
// It returns an error if the resulting Timestamp is invalid.
//
// Deprecated: Call the timestamppb.New function instead.
func TimestampProto(t time.Time) (*timestamppb.Timestamp, error) {
ts := &timestamppb.Timestamp{
Seconds: t.Unix(),
Nanos: int32(t.Nanosecond()),
}
if err := validateTimestamp(ts); err != nil {
return nil, err
}
return ts, nil
}
// TimestampString returns the RFC 3339 string for valid Timestamps.
// For invalid Timestamps, it returns an error message in parentheses.
//
// Deprecated: Call the ts.AsTime method instead,
// followed by a call to the Format method on the time.Time value.
func TimestampString(ts *timestamppb.Timestamp) string {
t, err := Timestamp(ts)
if err != nil {
return fmt.Sprintf("(%v)", err)
}
return t.Format(time.RFC3339Nano)
}
// validateTimestamp determines whether a Timestamp is valid.
// A valid timestamp represents a time in the range [0001-01-01, 10000-01-01)
// and has a Nanos field in the range [0, 1e9).
//
// If the Timestamp is valid, validateTimestamp returns nil.
// Otherwise, it returns an error that describes the problem.
//
// Every valid Timestamp can be represented by a time.Time,
// but the converse is not true.
func validateTimestamp(ts *timestamppb.Timestamp) error {
if ts == nil {
return errors.New("timestamp: nil Timestamp")
}
if ts.Seconds < minValidSeconds {
return fmt.Errorf("timestamp: %v before 0001-01-01", ts)
}
if ts.Seconds >= maxValidSeconds {
return fmt.Errorf("timestamp: %v after 10000-01-01", ts)
}
if ts.Nanos < 0 || ts.Nanos >= 1e9 {
return fmt.Errorf("timestamp: %v: nanos not in range [0, 1e9)", ts)
}
return nil
}

View file

@ -1,64 +0,0 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// source: github.com/golang/protobuf/ptypes/timestamp/timestamp.proto
package timestamp
import (
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
timestamppb "google.golang.org/protobuf/types/known/timestamppb"
reflect "reflect"
)
// Symbols defined in public import of google/protobuf/timestamp.proto.
type Timestamp = timestamppb.Timestamp
var File_github_com_golang_protobuf_ptypes_timestamp_timestamp_proto protoreflect.FileDescriptor
var file_github_com_golang_protobuf_ptypes_timestamp_timestamp_proto_rawDesc = []byte{
0x0a, 0x3b, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x67, 0x6f, 0x6c,
0x61, 0x6e, 0x67, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x70, 0x74, 0x79,
0x70, 0x65, 0x73, 0x2f, 0x74, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x2f, 0x74, 0x69,
0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x1f, 0x67,
0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x74,
0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x42, 0x37,
0x5a, 0x35, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x67, 0x6f, 0x6c,
0x61, 0x6e, 0x67, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x70, 0x74, 0x79,
0x70, 0x65, 0x73, 0x2f, 0x74, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x3b, 0x74, 0x69,
0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x50, 0x00, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f,
0x33,
}
var file_github_com_golang_protobuf_ptypes_timestamp_timestamp_proto_goTypes = []interface{}{}
var file_github_com_golang_protobuf_ptypes_timestamp_timestamp_proto_depIdxs = []int32{
0, // [0:0] is the sub-list for method output_type
0, // [0:0] is the sub-list for method input_type
0, // [0:0] is the sub-list for extension type_name
0, // [0:0] is the sub-list for extension extendee
0, // [0:0] is the sub-list for field type_name
}
func init() { file_github_com_golang_protobuf_ptypes_timestamp_timestamp_proto_init() }
func file_github_com_golang_protobuf_ptypes_timestamp_timestamp_proto_init() {
if File_github_com_golang_protobuf_ptypes_timestamp_timestamp_proto != nil {
return
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: file_github_com_golang_protobuf_ptypes_timestamp_timestamp_proto_rawDesc,
NumEnums: 0,
NumMessages: 0,
NumExtensions: 0,
NumServices: 0,
},
GoTypes: file_github_com_golang_protobuf_ptypes_timestamp_timestamp_proto_goTypes,
DependencyIndexes: file_github_com_golang_protobuf_ptypes_timestamp_timestamp_proto_depIdxs,
}.Build()
File_github_com_golang_protobuf_ptypes_timestamp_timestamp_proto = out.File
file_github_com_golang_protobuf_ptypes_timestamp_timestamp_proto_rawDesc = nil
file_github_com_golang_protobuf_ptypes_timestamp_timestamp_proto_goTypes = nil
file_github_com_golang_protobuf_ptypes_timestamp_timestamp_proto_depIdxs = nil
}

View file

@ -1,3 +1,3 @@
{
"v2": "2.12.1"
"v2": "2.12.2"
}

View file

@ -1,5 +1,12 @@
# Changelog
## [2.12.2](https://github.com/googleapis/gax-go/compare/v2.12.1...v2.12.2) (2024-02-23)
### Bug Fixes
* **v2/callctx:** fix SetHeader race by cloning header map ([#326](https://github.com/googleapis/gax-go/issues/326)) ([534311f](https://github.com/googleapis/gax-go/commit/534311f0f163d101f30657736c0e6f860e9c39dc))
## [2.12.1](https://github.com/googleapis/gax-go/compare/v2.12.0...v2.12.1) (2024-02-13)

View file

@ -74,9 +74,27 @@ func SetHeaders(ctx context.Context, keyvals ...string) context.Context {
h, ok := ctx.Value(headerKey).(map[string][]string)
if !ok {
h = make(map[string][]string)
} else {
h = cloneHeaders(h)
}
for i := 0; i < len(keyvals); i = i + 2 {
h[keyvals[i]] = append(h[keyvals[i]], keyvals[i+1])
}
return context.WithValue(ctx, headerKey, h)
}
// cloneHeaders makes a new key-value map while reusing the value slices.
// As such, new values should be appended to the value slice, and modifying
// indexed values is not thread safe.
//
// TODO: Replace this with maps.Clone when Go 1.21 is the minimum version.
func cloneHeaders(h map[string][]string) map[string][]string {
c := make(map[string][]string, len(h))
for k, v := range h {
vc := make([]string, len(v))
copy(vc, v)
c[k] = vc
}
return c
}

View file

@ -30,4 +30,4 @@
package internal
// Version is the current tagged release of the library.
const Version = "2.12.1"
const Version = "2.12.2"

View file

@ -1,6 +1,6 @@
package blueprint
type InstallerCustomization struct {
Unattended bool `json:"unattended,omitempty" toml:"unattended,omitempty"`
WheelSudoNopasswd bool `json:"wheel-sudo-nopasswd,omitempty" toml:"wheel-sudo-nopasswd,omitempty"`
Unattended bool `json:"unattended,omitempty" toml:"unattended,omitempty"`
SudoNopasswd []string `json:"sudo-nopasswd,omitempty" toml:"sudo-nopasswd,omitempty"`
}

View file

@ -353,7 +353,7 @@ func imageInstallerImage(workload workload.Workload,
img := image.NewAnacondaTarInstaller()
if instCust := customizations.GetInstaller(); instCust != nil {
img.WheelNoPasswd = instCust.WheelSudoNopasswd
img.NoPasswd = instCust.SudoNopasswd
img.UnattendedKickstart = instCust.Unattended
}
@ -541,7 +541,7 @@ func iotInstallerImage(workload workload.Workload,
}
if instCust := customizations.GetInstaller(); instCust != nil {
img.WheelNoPasswd = instCust.WheelSudoNopasswd
img.NoPasswd = instCust.SudoNopasswd
img.UnattendedKickstart = instCust.Unattended
}

View file

@ -182,6 +182,12 @@ func iotCommitPackageSet(t *imageType) rpmmd.PackageSet {
"podman-plugins", // deprecated in podman 5
},
})
} else {
ps = ps.Append(rpmmd.PackageSet{
Include: []string{
"bootupd", // added in F40+
},
})
}
return ps
@ -546,7 +552,7 @@ func liveInstallerPackageSet(t *imageType) rpmmd.PackageSet {
},
}
if common.VersionGreaterThanOrEqual(t.arch.distro.osVersion, "41") {
if common.VersionGreaterThanOrEqual(t.arch.distro.osVersion, VERSION_RAWHIDE) {
ps = ps.Append(rpmmd.PackageSet{
Include: []string{
"anaconda-webui",
@ -560,7 +566,7 @@ func liveInstallerPackageSet(t *imageType) rpmmd.PackageSet {
func imageInstallerPackageSet(t *imageType) rpmmd.PackageSet {
ps := anacondaPackageSet(t)
if common.VersionGreaterThanOrEqual(t.arch.distro.osVersion, "41") {
if common.VersionGreaterThanOrEqual(t.arch.distro.osVersion, VERSION_RAWHIDE) {
ps = ps.Append(rpmmd.PackageSet{
Include: []string{
"anaconda-webui",

View file

@ -0,0 +1,3 @@
package fedora
const VERSION_RAWHIDE = "41"

View file

@ -333,7 +333,7 @@ func imageInstallerImage(workload workload.Workload,
img.AdditionalAnacondaModules = []string{"org.fedoraproject.Anaconda.Modules.Users"}
if instCust := customizations.GetInstaller(); instCust != nil {
img.WheelNoPasswd = instCust.WheelSudoNopasswd
img.NoPasswd = instCust.SudoNopasswd
img.UnattendedKickstart = instCust.Unattended
}
@ -449,7 +449,7 @@ func edgeInstallerImage(workload workload.Workload,
img.Timezone, _ = customizations.GetTimezoneSettings()
if instCust := customizations.GetInstaller(); instCust != nil {
img.WheelNoPasswd = instCust.WheelSudoNopasswd
img.NoPasswd = instCust.SudoNopasswd
img.UnattendedKickstart = instCust.Unattended
}

View file

@ -296,10 +296,9 @@ func ec2BuildPackageSet(t *imageType) rpmmd.PackageSet {
}
func ec2CommonPackageSet(t *imageType) rpmmd.PackageSet {
return rpmmd.PackageSet{
ps := rpmmd.PackageSet{
Include: []string{
"@core",
"authselect-compat",
"chrony",
"cloud-init",
"cloud-utils-growpart",
@ -350,6 +349,12 @@ func ec2CommonPackageSet(t *imageType) rpmmd.PackageSet {
"qemu-guest-agent",
},
}.Append(distroSpecificPackageSet(t))
if t.arch.distro.releaseVersion == "9" {
ps.Include = append(ps.Include, "authselect-compat")
}
return ps
}
// common rhel ec2 RHUI image package set

View file

@ -30,25 +30,6 @@ var (
basePartitionTables: defaultBasePartitionTables,
}
// Azure BYOS image type
azureByosImgType = imageType{
name: "vhd",
filename: "disk.vhd",
mimeType: "application/x-vhd",
packageSets: map[string]packageSetFunc{
osPkgsKey: azurePackageSet,
},
defaultImageConfig: defaultAzureByosImageConfig.InheritFrom(defaultAzureImageConfig),
kernelOptions: defaultAzureKernelOptions,
bootable: true,
defaultSize: 4 * common.GibiByte,
image: diskImage,
buildPipelines: []string{"build"},
payloadPipelines: []string{"os", "image", "vpc"},
exports: []string{"vpc"},
basePartitionTables: defaultBasePartitionTables,
}
// Azure RHUI image type
azureRhuiImgType = imageType{
name: "azure-rhui",
@ -70,6 +51,27 @@ var (
}
)
// Azure BYOS image type
func azureByosImgType(rd distribution) imageType {
return imageType{
name: "vhd",
filename: "disk.vhd",
mimeType: "application/x-vhd",
packageSets: map[string]packageSetFunc{
osPkgsKey: azurePackageSet,
},
defaultImageConfig: defaultAzureByosImageConfig(rd).InheritFrom(defaultAzureImageConfig),
kernelOptions: defaultAzureKernelOptions,
bootable: true,
defaultSize: 4 * common.GibiByte,
image: diskImage,
buildPipelines: []string{"build"},
payloadPipelines: []string{"os", "image", "vpc"},
exports: []string{"vpc"},
basePartitionTables: defaultBasePartitionTables,
}
}
func azureSapRhuiImgType(rd distribution) imageType {
return imageType{
name: "azure-sap-rhui",
@ -574,10 +576,18 @@ var defaultAzureImageConfig = &distro.ImageConfig{
// Diff of the default Image Config compare to the `defaultAzureImageConfig`
// The configuration for non-RHUI images does not touch the RHSM configuration at all.
// https://issues.redhat.com/browse/COMPOSER-2157
var defaultAzureByosImageConfig = &distro.ImageConfig{
GPGKeyFiles: []string{
"/etc/pki/rpm-gpg/RPM-GPG-KEY-redhat-release",
},
func defaultAzureByosImageConfig(rd distribution) *distro.ImageConfig {
ic := &distro.ImageConfig{}
// NOTE RHEL 10 content is currently unsigned - remove this when GPG keys get added to the repos
if rd.Releasever() == "9" {
ic = &distro.ImageConfig{
GPGKeyFiles: []string{
"/etc/pki/rpm-gpg/RPM-GPG-KEY-redhat-release",
},
}
}
return ic
}
// Diff of the default Image Config compare to the `defaultAzureImageConfig`

View file

@ -3,6 +3,7 @@ package rhel9
import (
"fmt"
"github.com/osbuild/images/internal/common"
"github.com/osbuild/images/pkg/arch"
"github.com/osbuild/images/pkg/rpmmd"
)
@ -48,7 +49,6 @@ func bareMetalPackageSet(t *imageType) rpmmd.PackageSet {
ps := rpmmd.PackageSet{
Include: []string{
"@core",
"authselect-compat",
"chrony",
"cockpit-system",
"cockpit-ws",
@ -90,6 +90,10 @@ func bareMetalPackageSet(t *imageType) rpmmd.PackageSet {
},
}.Append(distroBuildPackageSet(t))
if common.VersionLessThan(t.arch.distro.osVersion, "10.0") {
ps.Include = append(ps.Include, "authselect-compat")
}
// Ensure to not pull in subscription-manager on non-RHEL distro
if t.arch.distro.isRHEL() {
ps = ps.Append(rpmmd.PackageSet{

View file

@ -125,10 +125,10 @@ func (d *distribution) getDefaultImageConfig() *distro.ImageConfig {
return d.defaultImageConfig
}
func newDistro(name string, minor int) *distribution {
func newDistro(name string, major, minor int) *distribution {
var rd distribution
switch name {
case "rhel":
switch fmt.Sprintf("%s-%d", name, major) {
case "rhel-9":
rd = distribution{
name: fmt.Sprintf("rhel-9.%d", minor),
product: "Red Hat Enterprise Linux",
@ -141,7 +141,20 @@ func newDistro(name string, minor int) *distribution {
runner: &runner.RHEL{Major: uint64(9), Minor: uint64(minor)},
defaultImageConfig: defaultDistroImageConfig,
}
case "centos":
case "rhel-10":
rd = distribution{
name: fmt.Sprintf("rhel-10.%d", minor),
product: "Red Hat Enterprise Linux",
osVersion: fmt.Sprintf("10.%d", minor),
releaseVersion: "10",
modulePlatformID: "platform:el10",
vendor: "redhat",
ostreeRefTmpl: "rhel/10/%s/edge",
isolabelTmpl: fmt.Sprintf("RHEL-10-%d-0-BaseOS-%%s", minor),
runner: &runner.RHEL{Major: uint64(10), Minor: uint64(minor)},
defaultImageConfig: defaultDistroImageConfig,
}
case "centos-9":
rd = distribution{
name: "centos-9",
product: "CentOS Stream",
@ -154,8 +167,21 @@ func newDistro(name string, minor int) *distribution {
runner: &runner.CentOS{Version: uint64(9)},
defaultImageConfig: defaultDistroImageConfig,
}
case "centos-10":
rd = distribution{
name: "centos-10",
product: "CentOS Stream",
osVersion: "10-stream",
releaseVersion: "10",
modulePlatformID: "platform:el10",
vendor: "centos",
ostreeRefTmpl: "centos/10/%s/edge",
isolabelTmpl: "CentOS-Stream-10-BaseOS-%s",
runner: &runner.CentOS{Version: uint64(10)},
defaultImageConfig: defaultDistroImageConfig,
}
default:
panic(fmt.Sprintf("unknown distro name: %s", name))
panic(fmt.Sprintf("unknown distro name: %s and major: %d", name, major))
}
// Architecture definitions
@ -207,21 +233,6 @@ func newDistro(name string, minor int) *distribution {
openstackImgType,
)
azureX64Platform := &platform.X86{
BIOS: true,
UEFIVendor: rd.vendor,
BasePlatform: platform.BasePlatform{
ImageFormat: platform.FORMAT_VHD,
},
}
azureAarch64Platform := &platform.Aarch64{
UEFIVendor: rd.vendor,
BasePlatform: platform.BasePlatform{
ImageFormat: platform.FORMAT_VHD,
},
}
x86_64.addImageTypes(
&platform.X86{
BIOS: true,
@ -244,80 +255,6 @@ func newDistro(name string, minor int) *distribution {
ovaImgType,
)
ec2X86Platform := &platform.X86{
BIOS: true,
UEFIVendor: rd.vendor,
BasePlatform: platform.BasePlatform{
ImageFormat: platform.FORMAT_RAW,
},
}
x86_64.addImageTypes(
ec2X86Platform,
mkAMIImgTypeX86_64(),
)
gceX86Platform := &platform.X86{
UEFIVendor: rd.vendor,
BasePlatform: platform.BasePlatform{
ImageFormat: platform.FORMAT_GCE,
},
}
x86_64.addImageTypes(
gceX86Platform,
mkGCEImageType(),
)
x86_64.addImageTypes(
&platform.X86{
BasePlatform: platform.BasePlatform{
FirmwarePackages: []string{
"microcode_ctl", // ??
"iwl1000-firmware",
"iwl100-firmware",
"iwl105-firmware",
"iwl135-firmware",
"iwl2000-firmware",
"iwl2030-firmware",
"iwl3160-firmware",
"iwl5000-firmware",
"iwl5150-firmware",
"iwl6050-firmware",
},
},
BIOS: true,
UEFIVendor: rd.vendor,
},
edgeOCIImgType,
edgeCommitImgType,
edgeInstallerImgType,
edgeRawImgType,
imageInstaller,
edgeAMIImgType,
)
x86_64.addImageTypes(
&platform.X86{
BasePlatform: platform.BasePlatform{
ImageFormat: platform.FORMAT_VMDK,
},
BIOS: true,
UEFIVendor: rd.vendor,
},
edgeVsphereImgType,
)
x86_64.addImageTypes(
&platform.X86{
BasePlatform: platform.BasePlatform{
ImageFormat: platform.FORMAT_RAW,
},
BIOS: false,
UEFIVendor: rd.vendor,
},
edgeSimplifiedInstallerImgType,
minimalrawImgType,
)
x86_64.addImageTypes(
&platform.X86{},
tarImgType,
@ -340,40 +277,6 @@ func newDistro(name string, minor int) *distribution {
wslImgType,
)
aarch64.addImageTypes(
&platform.Aarch64{
BasePlatform: platform.BasePlatform{},
UEFIVendor: rd.vendor,
},
edgeCommitImgType,
edgeOCIImgType,
edgeInstallerImgType,
edgeSimplifiedInstallerImgType,
imageInstaller,
edgeAMIImgType,
)
aarch64.addImageTypes(
&platform.Aarch64{
BasePlatform: platform.BasePlatform{
ImageFormat: platform.FORMAT_VMDK,
},
UEFIVendor: rd.vendor,
},
edgeVsphereImgType,
)
aarch64.addImageTypes(
&platform.Aarch64{
BasePlatform: platform.BasePlatform{
ImageFormat: platform.FORMAT_RAW,
},
UEFIVendor: rd.vendor,
},
edgeRawImgType,
minimalrawImgType,
)
aarch64.addImageTypes(
&platform.Aarch64{
UEFIVendor: rd.vendor,
@ -384,15 +287,6 @@ func newDistro(name string, minor int) *distribution {
},
qcow2ImgType,
)
aarch64.addImageTypes(
&platform.Aarch64{
UEFIVendor: rd.vendor,
BasePlatform: platform.BasePlatform{
ImageFormat: platform.FORMAT_RAW,
},
},
mkAMIImgTypeAarch64(),
)
ppc64le.addImageTypes(
&platform.PPC64LE{
@ -424,42 +318,187 @@ func newDistro(name string, minor int) *distribution {
tarImgType,
)
if rd.isRHEL() {
// add azure to RHEL distro only
x86_64.addImageTypes(azureX64Platform, azureRhuiImgType, azureByosImgType)
aarch64.addImageTypes(azureAarch64Platform, azureRhuiImgType, azureByosImgType)
ec2X86Platform := &platform.X86{
BIOS: true,
UEFIVendor: rd.vendor,
BasePlatform: platform.BasePlatform{
ImageFormat: platform.FORMAT_RAW,
},
}
x86_64.addImageTypes(
ec2X86Platform,
mkAMIImgTypeX86_64(),
)
x86_64.addImageTypes(azureX64Platform, azureSapRhuiImgType(rd))
// keep the RHEL EC2 x86_64 images before 9.3 BIOS-only for backward compatibility
if common.VersionLessThan(rd.osVersion, "9.3") {
ec2X86Platform = &platform.X86{
BIOS: true,
BasePlatform: platform.BasePlatform{
ImageFormat: platform.FORMAT_RAW,
},
}
}
// add ec2 image types to RHEL distro only
x86_64.addImageTypes(ec2X86Platform, mkEc2ImgTypeX86_64(rd.osVersion, rd.isRHEL()), mkEc2HaImgTypeX86_64(rd.osVersion, rd.isRHEL()), mkEC2SapImgTypeX86_64(rd.osVersion, rd.isRHEL()))
aarch64.addImageTypes(
&platform.Aarch64{
UEFIVendor: rd.vendor,
BasePlatform: platform.BasePlatform{
ImageFormat: platform.FORMAT_RAW,
},
aarch64.addImageTypes(
&platform.Aarch64{
UEFIVendor: rd.vendor,
BasePlatform: platform.BasePlatform{
ImageFormat: platform.FORMAT_RAW,
},
mkEC2ImgTypeAarch64(rd.osVersion, rd.isRHEL()),
)
},
mkAMIImgTypeAarch64(),
)
// add GCE RHUI image to RHEL only
x86_64.addImageTypes(gceX86Platform, mkGCERHUIImageType())
azureX64Platform := &platform.X86{
BIOS: true,
UEFIVendor: rd.vendor,
BasePlatform: platform.BasePlatform{
ImageFormat: platform.FORMAT_VHD,
},
}
azureAarch64Platform := &platform.Aarch64{
UEFIVendor: rd.vendor,
BasePlatform: platform.BasePlatform{
ImageFormat: platform.FORMAT_VHD,
},
}
if rd.isRHEL() { // RHEL-only (non-CentOS) image types
x86_64.addImageTypes(azureX64Platform, azureByosImgType(rd))
aarch64.addImageTypes(azureAarch64Platform, azureByosImgType(rd))
} else {
x86_64.addImageTypes(azureX64Platform, azureImgType)
aarch64.addImageTypes(azureAarch64Platform, azureImgType)
}
// NOTE: This condition is a temporary separation of EL9 and EL10 while we
// add support for all image types on EL10. Currently only a small subset
// is supported on EL10 because of package availability. This big
// conditional separation should be removed when most image types become
// available in EL10.
if major == 9 {
gceX86Platform := &platform.X86{
UEFIVendor: rd.vendor,
BasePlatform: platform.BasePlatform{
ImageFormat: platform.FORMAT_GCE,
},
}
x86_64.addImageTypes(
gceX86Platform,
mkGCEImageType(),
)
x86_64.addImageTypes(
&platform.X86{
BasePlatform: platform.BasePlatform{
FirmwarePackages: []string{
"microcode_ctl", // ??
"iwl1000-firmware",
"iwl100-firmware",
"iwl105-firmware",
"iwl135-firmware",
"iwl2000-firmware",
"iwl2030-firmware",
"iwl3160-firmware",
"iwl5000-firmware",
"iwl5150-firmware",
"iwl6050-firmware",
},
},
BIOS: true,
UEFIVendor: rd.vendor,
},
edgeOCIImgType,
edgeCommitImgType,
edgeInstallerImgType,
edgeRawImgType,
imageInstaller,
edgeAMIImgType,
)
x86_64.addImageTypes(
&platform.X86{
BasePlatform: platform.BasePlatform{
ImageFormat: platform.FORMAT_VMDK,
},
BIOS: true,
UEFIVendor: rd.vendor,
},
edgeVsphereImgType,
)
x86_64.addImageTypes(
&platform.X86{
BasePlatform: platform.BasePlatform{
ImageFormat: platform.FORMAT_RAW,
},
BIOS: false,
UEFIVendor: rd.vendor,
},
edgeSimplifiedInstallerImgType,
minimalrawImgType,
)
aarch64.addImageTypes(
&platform.Aarch64{
BasePlatform: platform.BasePlatform{},
UEFIVendor: rd.vendor,
},
edgeCommitImgType,
edgeOCIImgType,
edgeInstallerImgType,
edgeSimplifiedInstallerImgType,
imageInstaller,
edgeAMIImgType,
)
aarch64.addImageTypes(
&platform.Aarch64{
BasePlatform: platform.BasePlatform{
ImageFormat: platform.FORMAT_VMDK,
},
UEFIVendor: rd.vendor,
},
edgeVsphereImgType,
)
aarch64.addImageTypes(
&platform.Aarch64{
BasePlatform: platform.BasePlatform{
ImageFormat: platform.FORMAT_RAW,
},
UEFIVendor: rd.vendor,
},
edgeRawImgType,
minimalrawImgType,
)
if rd.isRHEL() { // RHEL-only (non-CentOS) image types
x86_64.addImageTypes(azureX64Platform, azureRhuiImgType, azureByosImgType(rd))
aarch64.addImageTypes(azureAarch64Platform, azureRhuiImgType, azureByosImgType(rd))
x86_64.addImageTypes(azureX64Platform, azureSapRhuiImgType(rd))
// keep the RHEL EC2 x86_64 images before 9.3 BIOS-only for backward compatibility
if common.VersionLessThan(rd.osVersion, "9.3") {
ec2X86Platform = &platform.X86{
BIOS: true,
BasePlatform: platform.BasePlatform{
ImageFormat: platform.FORMAT_RAW,
},
}
}
// add ec2 image types to RHEL distro only
x86_64.addImageTypes(ec2X86Platform, mkEc2ImgTypeX86_64(rd.osVersion, rd.isRHEL()), mkEc2HaImgTypeX86_64(rd.osVersion, rd.isRHEL()), mkEC2SapImgTypeX86_64(rd.osVersion, rd.isRHEL()))
aarch64.addImageTypes(
&platform.Aarch64{
UEFIVendor: rd.vendor,
BasePlatform: platform.BasePlatform{
ImageFormat: platform.FORMAT_RAW,
},
},
mkEC2ImgTypeAarch64(rd.osVersion, rd.isRHEL()),
)
// add GCE RHUI image to RHEL only
x86_64.addImageTypes(gceX86Platform, mkGCERHUIImageType())
}
}
rd.addArches(x86_64, aarch64, ppc64le, s390x)
return &rd
}
@ -510,5 +549,41 @@ func DistroFactory(idStr string) distro.Distro {
return nil
}
return newDistro(id.Name, id.MinorVersion)
return newDistro(id.Name, 9, id.MinorVersion)
}
func ParseIDEl10(idStr string) (*distro.ID, error) {
id, err := distro.ParseID(idStr)
if err != nil {
return nil, err
}
if id.Name != "rhel" && id.Name != "centos" {
return nil, fmt.Errorf("invalid distro name: %s", id.Name)
}
if id.MajorVersion != 10 {
return nil, fmt.Errorf("invalid distro major version: %d", id.MajorVersion)
}
// CentOS does not use minor version
if id.Name == "centos" && id.MinorVersion != -1 {
return nil, fmt.Errorf("centos does not use minor version, but got: %d", id.MinorVersion)
}
// RHEL uses minor version
if id.Name == "rhel" && id.MinorVersion == -1 {
return nil, fmt.Errorf("rhel requires minor version, but got: %d", id.MinorVersion)
}
return id, nil
}
func DistroFactoryEl10(idStr string) distro.Distro {
id, err := ParseIDEl10(idStr)
if err != nil {
return nil
}
return newDistro(id.Name, 10, id.MinorVersion)
}

View file

@ -397,7 +397,7 @@ func edgeInstallerImage(workload workload.Workload,
img.Timezone, _ = customizations.GetTimezoneSettings()
if instCust := customizations.GetInstaller(); instCust != nil {
img.WheelNoPasswd = instCust.WheelSudoNopasswd
img.NoPasswd = instCust.SudoNopasswd
img.UnattendedKickstart = instCust.Unattended
}
@ -607,7 +607,7 @@ func imageInstallerImage(workload workload.Workload,
img.AdditionalAnacondaModules = []string{"org.fedoraproject.Anaconda.Modules.Users"}
if instCust := customizations.GetInstaller(); instCust != nil {
img.WheelNoPasswd = instCust.WheelSudoNopasswd
img.NoPasswd = instCust.SudoNopasswd
img.UnattendedKickstart = instCust.Unattended
}

View file

@ -267,7 +267,14 @@ func (t *imageType) Manifest(bp *blueprint.Blueprint,
return nil, nil, err
}
mf := manifest.New()
mf.Distro = manifest.DISTRO_EL9
switch t.arch.distro.releaseVersion {
case "9":
mf.Distro = manifest.DISTRO_EL9
case "10":
mf.Distro = manifest.DISTRO_EL10
default:
return nil, nil, fmt.Errorf("unsupported distro release version %s", t.arch.distro.releaseVersion)
}
_, err = img.InstantiateManifest(&mf, repos, t.arch.distro.runner, rng)
if err != nil {
return nil, nil, err

View file

@ -34,7 +34,6 @@ func qcow2CommonPackageSet(t *imageType) rpmmd.PackageSet {
ps := rpmmd.PackageSet{
Include: []string{
"@core",
"authselect-compat",
"chrony",
"cloud-init",
"cloud-utils-growpart",
@ -94,6 +93,10 @@ func qcow2CommonPackageSet(t *imageType) rpmmd.PackageSet {
},
}.Append(distroSpecificPackageSet(t))
if t.arch.distro.releaseVersion == "9" {
ps.Include = append(ps.Include, "authselect-compat")
}
// Ensure to not pull in subscription-manager on non-RHEL distro
if t.arch.distro.isRHEL() {
ps = ps.Append(rpmmd.PackageSet{

View file

@ -112,6 +112,7 @@ func NewDefault() *Factory {
rhel7.DistroFactory,
rhel8.DistroFactory,
rhel9.DistroFactory,
rhel9.DistroFactoryEl10,
)
}

View file

@ -66,5 +66,6 @@ func NewDefaultParser() *Parser {
rhel7.ParseID,
rhel8.ParseID,
rhel9.ParseID,
rhel9.ParseIDEl10,
)
}

View file

@ -27,8 +27,9 @@ type AnacondaOSTreeInstaller struct {
Keyboard *string
Timezone *string
// Create a sudoers drop-in file for wheel group with NOPASSWD option
WheelNoPasswd bool
// Create a sudoers drop-in file for each user or group to enable the
// NOPASSWD option
NoPasswd []string
// Add kickstart options to make the installation fully unattended
UnattendedKickstart bool
@ -128,7 +129,7 @@ func (img *AnacondaOSTreeInstaller) InstantiateManifest(m *manifest.Manifest,
isoTreePipeline.Remote = img.Remote
isoTreePipeline.Users = img.Users
isoTreePipeline.Groups = img.Groups
isoTreePipeline.WheelNoPasswd = img.WheelNoPasswd
isoTreePipeline.NoPasswd = img.NoPasswd
isoTreePipeline.UnattendedKickstart = img.UnattendedKickstart
isoTreePipeline.SquashfsCompression = img.SquashfsCompression
isoTreePipeline.Language = img.Language

View file

@ -56,8 +56,9 @@ type AnacondaTarInstaller struct {
// defaults.
ISORootKickstart bool
// Create a sudoers drop-in file for wheel group with NOPASSWD option
WheelNoPasswd bool
// Create a sudoers drop-in file for each user or group to enable the
// NOPASSWD option
NoPasswd []string
// Add kickstart options to make the installation fully unattended.
// Enabling this option also automatically enables the ISORootKickstart
@ -193,7 +194,7 @@ func (img *AnacondaTarInstaller) InstantiateManifest(m *manifest.Manifest,
isoTreePipeline.KSPath = kspath
}
isoTreePipeline.WheelNoPasswd = img.WheelNoPasswd
isoTreePipeline.NoPasswd = img.NoPasswd
isoTreePipeline.UnattendedKickstart = img.UnattendedKickstart
isoTreePipeline.SquashfsCompression = img.SquashfsCompression

View file

@ -4,10 +4,9 @@ import (
"fmt"
"math/rand"
"github.com/osbuild/images/pkg/artifact"
"github.com/osbuild/images/pkg/container"
"github.com/osbuild/images/pkg/manifest"
"github.com/osbuild/images/pkg/platform"
"github.com/osbuild/images/pkg/osbuild"
"github.com/osbuild/images/pkg/runner"
)
@ -32,41 +31,41 @@ func NewBootcDiskImage(container container.SourceSpec) *BootcDiskImage {
func (img *BootcDiskImage) InstantiateManifestFromContainers(m *manifest.Manifest,
containers []container.SourceSpec,
runner runner.Runner,
rng *rand.Rand) (*artifact.Artifact, error) {
rng *rand.Rand) error {
buildPipeline := manifest.NewBuildFromContainer(m, runner, containers, &manifest.BuildOptions{ContainerBuildable: true})
buildPipeline.Checkpoint()
// don't support compressing non-raw images
imgFormat := img.Platform.GetImageFormat()
if imgFormat == platform.FORMAT_UNSET {
// treat unset as raw for this check
imgFormat = platform.FORMAT_RAW
}
if imgFormat != platform.FORMAT_RAW && img.Compression != "" {
panic(fmt.Sprintf("no compression is allowed with %q format for %q", imgFormat, img.name))
}
// In the bootc flow, we reuse the host container context for tools;
// this is signified by passing nil to the below pipelines.
var hostPipeline manifest.Build
opts := &baseRawOstreeImageOpts{useBootupd: true}
baseImage := baseRawOstreeImage(img.OSTreeDiskImage, buildPipeline, opts)
switch imgFormat {
case platform.FORMAT_QCOW2:
// qcow2 runs without a build pipeline directly from "bib"
qcow2Pipeline := manifest.NewQCOW2(nil, baseImage)
qcow2Pipeline.Compat = img.Platform.GetQCOW2Compat()
qcow2Pipeline.SetFilename(img.Filename)
return qcow2Pipeline.Export(), nil
}
switch img.Compression {
case "xz":
compressedImage := manifest.NewXZ(buildPipeline, baseImage)
compressedImage.SetFilename(img.Filename)
return compressedImage.Export(), nil
case "":
baseImage.SetFilename(img.Filename)
return baseImage.Export(), nil
default:
panic(fmt.Sprintf("unsupported compression type %q on %q", img.Compression, img.name))
fileBasename := img.Filename
// In BIB, we export multiple images from the same pipeline so we use the
// filename as the basename for each export and set the extensions based on
// each file format.
baseImage := baseRawOstreeImage(img.OSTreeDiskImage, buildPipeline, opts)
baseImage.SetFilename(fmt.Sprintf("%s.raw", fileBasename))
qcow2Pipeline := manifest.NewQCOW2(hostPipeline, baseImage)
qcow2Pipeline.Compat = img.Platform.GetQCOW2Compat()
qcow2Pipeline.SetFilename(fmt.Sprintf("%s.qcow2", fileBasename))
vmdkPipeline := manifest.NewVMDK(hostPipeline, baseImage)
vmdkPipeline.SetFilename(fmt.Sprintf("%s.vmdk", fileBasename))
ovfPipeline := manifest.NewOVF(hostPipeline, vmdkPipeline)
tarPipeline := manifest.NewTar(hostPipeline, ovfPipeline, "archive")
tarPipeline.Format = osbuild.TarArchiveFormatUstar
tarPipeline.SetFilename(fmt.Sprintf("%s.tar", fileBasename))
// The .ovf descriptor needs to be the first file in the archive
tarPipeline.Paths = []string{
fmt.Sprintf("%s.ovf", fileBasename),
fmt.Sprintf("%s.mf", fileBasename),
fmt.Sprintf("%s.vmdk", fileBasename),
}
return nil
}

View file

@ -3,6 +3,8 @@ package manifest
import (
"fmt"
"path"
"sort"
"strings"
"github.com/osbuild/images/internal/common"
"github.com/osbuild/images/pkg/container"
@ -32,8 +34,9 @@ type AnacondaInstallerISOTree struct {
Keyboard *string
Timezone *string
// Create a sudoers drop-in file for wheel group with NOPASSWD option
WheelNoPasswd bool
// Create a sudoers drop-in file for each user or group to enable the
// NOPASSWD option
NoPasswd []string
// Add kickstart options to make the installation fully unattended
UnattendedKickstart bool
@ -532,16 +535,10 @@ func (p *AnacondaInstallerISOTree) makeKickstartStages(kickstartOptions *osbuild
stages = append(stages, osbuild.NewKickstartStage(kickstartOptions))
if p.WheelNoPasswd {
hardcodedKickstartBits := makeKickstartSudoersPost(p.NoPasswd)
if hardcodedKickstartBits != "" {
// Because osbuild core only supports a subset of options,
// we append to the base here with hardcoded wheel group with NOPASSWD option
hardcodedKickstartBits := `
%post
echo -e "%wheel\tALL=(ALL)\tNOPASSWD: ALL" > "/etc/sudoers.d/wheel"
chmod 0440 /etc/sudoers.d/wheel
restorecon -rvF /etc/sudoers.d
%end
`
kickstartFile, err := kickstartOptions.IncludeRaw(hardcodedKickstartBits)
if err != nil {
panic(err)
@ -560,3 +557,31 @@ func makeISORootPath(p string) string {
fullpath := path.Join("/run/install/repo", p)
return fmt.Sprintf("file://%s", fullpath)
}
func makeKickstartSudoersPost(names []string) string {
if len(names) == 0 {
return ""
}
echoLineFmt := `echo -e "%[1]s\tALL=(ALL)\tNOPASSWD: ALL" > "/etc/sudoers.d/%[1]s"
chmod 0440 /etc/sudoers.d/%[1]s`
filenames := make(map[string]bool)
sort.Strings(names)
entries := make([]string, 0, len(names))
for _, name := range names {
if filenames[name] {
continue
}
entries = append(entries, fmt.Sprintf(echoLineFmt, name))
filenames[name] = true
}
kickstartSudoersPost := `
%%post
%s
restorecon -rvF /etc/sudoers.d
%%end
`
return fmt.Sprintf(kickstartSudoersPost, strings.Join(entries, "\n"))
}

View file

@ -34,6 +34,7 @@ type Distro uint64
const (
DISTRO_NULL = iota
DISTRO_EL10
DISTRO_EL9
DISTRO_EL8
DISTRO_EL7

View file

@ -298,6 +298,7 @@ func (p *OS) getBuildPackages(distro Distro) []string {
switch distro {
case DISTRO_EL8:
packages = append(packages, "python3-pytoml")
case DISTRO_EL10:
default:
packages = append(packages, "python3-toml")
}

View file

@ -14,12 +14,17 @@ type OVF struct {
}
// NewOVF creates a new OVF pipeline. imgPipeline is the pipeline producing the vmdk image.
func NewOVF(buidPipeline Build, imgPipeline *VMDK) *OVF {
func NewOVF(buildPipeline Build, imgPipeline *VMDK) *OVF {
p := &OVF{
Base: NewBase("ovf", buidPipeline),
Base: NewBase("ovf", buildPipeline),
imgPipeline: imgPipeline,
}
buidPipeline.addDependent(p)
// See similar logic in qcow2 to run on the host
if buildPipeline != nil {
buildPipeline.addDependent(p)
} else {
imgPipeline.Manifest().addPipeline(p)
}
return p
}

View file

@ -1,6 +1,8 @@
package manifest
import (
"fmt"
"github.com/osbuild/images/pkg/arch"
"github.com/osbuild/images/pkg/artifact"
"github.com/osbuild/images/pkg/osbuild"
@ -59,6 +61,38 @@ func (p *RawImage) serialize() osbuild.Pipeline {
copyInputs := osbuild.NewPipelineTreeInputs(inputName, p.treePipeline.Name())
pipeline.AddStage(osbuild.NewCopyStage(copyOptions, copyInputs, copyDevices, copyMounts))
bootFiles := p.treePipeline.platform.GetBootFiles()
if len(bootFiles) > 0 {
// we ignore the bootcopyoptions as they contain a full tree copy instead we make our own, we *do* still want all the other
// information such as mountpoints and devices
_, bootCopyDevices, bootCopyMounts := osbuild.GenCopyFSTreeOptions(inputName, p.treePipeline.Name(), p.Filename(), pt)
bootCopyOptions := &osbuild.CopyStageOptions{}
bootCopyInputs := osbuild.NewPipelineTreeInputs(inputName, p.treePipeline.Name())
// Find the FS root mount name to use as the destination root
// for the target when copying the boot files.
var fsRootMntName string
for _, mnt := range bootCopyMounts {
if mnt.Target == "/" {
fsRootMntName = mnt.Name
break
}
}
if fsRootMntName == "" {
panic("no mount found for the filesystem root")
}
for _, paths := range bootFiles {
bootCopyOptions.Paths = append(bootCopyOptions.Paths, osbuild.CopyStagePath{
From: fmt.Sprintf("input://root-tree%s", paths[0]),
To: fmt.Sprintf("mount://%s%s", fsRootMntName, paths[1]),
})
}
pipeline.AddStage(osbuild.NewCopyStage(bootCopyOptions, bootCopyInputs, bootCopyDevices, bootCopyMounts))
}
for _, stage := range osbuild.GenImageFinishStages(pt, p.Filename()) {
pipeline.AddStage(stage)
}

View file

@ -37,7 +37,12 @@ func NewTar(buildPipeline Build, inputPipeline Pipeline, pipelinename string) *T
inputPipeline: inputPipeline,
filename: "image.tar",
}
buildPipeline.addDependent(p)
// See similar logic in qcow2 to run on the host
if buildPipeline != nil {
buildPipeline.addDependent(p)
} else {
inputPipeline.Manifest().addPipeline(p)
}
return p
}

View file

@ -31,7 +31,12 @@ func NewVMDK(buildPipeline Build, imgPipeline FilePipeline) *VMDK {
imgPipeline: imgPipeline,
filename: "image.vmdk",
}
buildPipeline.addDependent(p)
// See similar logic in qcow2 to run on the host
if buildPipeline != nil {
buildPipeline.addDependent(p)
} else {
imgPipeline.Manifest().addPipeline(p)
}
return p
}

View file

@ -1,6 +1,8 @@
package platform
import (
"fmt"
"github.com/osbuild/images/pkg/arch"
)
@ -19,6 +21,8 @@ const ( // image format enum
func (f ImageFormat) String() string {
switch f {
case FORMAT_UNSET:
return "unset"
case FORMAT_RAW:
return "raw"
case FORMAT_ISO:
@ -34,7 +38,7 @@ func (f ImageFormat) String() string {
case FORMAT_OVA:
return "ova"
default:
panic("invalid image format")
panic(fmt.Errorf("unknown image format %d", f))
}
}

View file

@ -16,7 +16,7 @@ package otelgrpc // import "go.opentelemetry.io/contrib/instrumentation/google.g
// Version is the current release version of the gRPC instrumentation.
func Version() string {
return "0.48.0"
return "0.49.0"
// This string is updated by the pre_release.sh script during release
}

View file

@ -31,14 +31,6 @@ const (
// Server HTTP metrics.
const (
// Deprecated: This field is unused.
RequestCount = "http.server.request_count" // Incoming request count total
// Deprecated: Use of this field has been migrated to serverRequestSize. It will be removed in a future version.
RequestContentLength = "http.server.request_content_length" // Incoming request bytes total
// Deprecated: Use of this field has been migrated to serverResponseSize. It will be removed in a future version.
ResponseContentLength = "http.server.response_content_length" // Incoming response bytes total
// Deprecated: Use of this field has been migrated to serverDuration. It will be removed in a future version.
ServerLatency = "http.server.duration" // Incoming end to end duration, milliseconds
serverRequestSize = "http.server.request.size" // Incoming request bytes total
serverResponseSize = "http.server.response.size" // Incoming response bytes total
serverDuration = "http.server.duration" // Incoming end to end duration, milliseconds

View file

@ -224,7 +224,7 @@ func (h *middleware) serveHTTP(w http.ResponseWriter, r *http.Request, next http
next.ServeHTTP(w, r.WithContext(ctx))
setAfterServeAttributes(span, bw.read, rww.written, rww.statusCode, bw.err, rww.err)
setAfterServeAttributes(span, bw.read.Load(), rww.written, rww.statusCode, bw.err, rww.err)
// Add metrics
attributes := append(labeler.Get(), semconvutil.HTTPServerRequestMetrics(h.server, r)...)
@ -232,7 +232,7 @@ func (h *middleware) serveHTTP(w http.ResponseWriter, r *http.Request, next http
attributes = append(attributes, semconv.HTTPStatusCode(rww.statusCode))
}
o := metric.WithAttributes(attributes...)
h.requestBytesCounter.Add(ctx, bw.read, o)
h.requestBytesCounter.Add(ctx, bw.read.Load(), o)
h.responseBytesCounter.Add(ctx, rww.written, o)
// Use floating point division here for higher precision (instead of Millisecond method).

View file

@ -43,10 +43,10 @@ func HTTPClientResponse(resp *http.Response) []attribute.KeyValue {
}
// HTTPClientRequest returns trace attributes for an HTTP request made by a client.
// The following attributes are always returned: "http.url", "http.flavor",
// "http.method", "net.peer.name". The following attributes are returned if the
// related values are defined in req: "net.peer.port", "http.user_agent",
// "http.request_content_length", "enduser.id".
// The following attributes are always returned: "http.url", "http.method",
// "net.peer.name". The following attributes are returned if the related values
// are defined in req: "net.peer.port", "user_agent.original",
// "http.request_content_length".
func HTTPClientRequest(req *http.Request) []attribute.KeyValue {
return hc.ClientRequest(req)
}
@ -83,10 +83,9 @@ func HTTPClientStatus(code int) (codes.Code, string) {
// The req Host will be used to determine the server instead.
//
// The following attributes are always returned: "http.method", "http.scheme",
// "http.flavor", "http.target", "net.host.name". The following attributes are
// returned if they related values are defined in req: "net.host.port",
// "net.sock.peer.addr", "net.sock.peer.port", "http.user_agent", "enduser.id",
// "http.client_ip".
// "http.target", "net.host.name". The following attributes are returned if
// they related values are defined in req: "net.host.port", "net.sock.peer.addr",
// "net.sock.peer.port", "user_agent.original", "http.client_ip".
func HTTPServerRequest(server string, req *http.Request) []attribute.KeyValue {
return hc.ServerRequest(server, req)
}
@ -109,8 +108,8 @@ func HTTPServerRequest(server string, req *http.Request) []attribute.KeyValue {
// The req Host will be used to determine the server instead.
//
// The following attributes are always returned: "http.method", "http.scheme",
// "http.flavor", "net.host.name". The following attributes are
// returned if they related values are defined in req: "net.host.port".
// "net.host.name". The following attributes are returned if they related
// values are defined in req: "net.host.port".
func HTTPServerRequestMetrics(server string, req *http.Request) []attribute.KeyValue {
return hc.ServerRequestMetrics(server, req)
}
@ -192,7 +191,7 @@ func (c *httpConv) ClientResponse(resp *http.Response) []attribute.KeyValue {
// ClientRequest returns attributes for an HTTP request made by a client. The
// following attributes are always returned: "http.url", "http.method",
// "net.peer.name". The following attributes are returned if the related values
// are defined in req: "net.peer.port", "http.user_agent",
// are defined in req: "net.peer.port", "user_agent.original",
// "http.request_content_length", "user_agent.original".
func (c *httpConv) ClientRequest(req *http.Request) []attribute.KeyValue {
/* The following semantic conventions are returned if present:
@ -449,8 +448,8 @@ func (c *httpConv) ServerRequest(server string, req *http.Request) []attribute.K
// The req Host will be used to determine the server instead.
//
// The following attributes are always returned: "http.method", "http.scheme",
// "http.flavor", "net.host.name". The following attributes are
// returned if they related values are defined in req: "net.host.port".
// "net.host.name". The following attributes are returned if they related
// values are defined in req: "net.host.port".
func (c *httpConv) ServerRequestMetrics(server string, req *http.Request) []attribute.KeyValue {
/* The following semantic conventions are returned if present:
http.scheme string

View file

@ -182,7 +182,7 @@ func (t *Transport) RoundTrip(r *http.Request) (*http.Response, error) {
metricAttrs = append(metricAttrs, semconv.HTTPStatusCode(res.StatusCode))
}
o := metric.WithAttributes(metricAttrs...)
t.requestBytesCounter.Add(ctx, bw.read, o)
t.requestBytesCounter.Add(ctx, bw.read.Load(), o)
// For handling response bytes we leverage a callback when the client reads the http response
readRecordFunc := func(n int64) {
t.responseBytesCounter.Add(ctx, n, o)

View file

@ -16,7 +16,7 @@ package otelhttp // import "go.opentelemetry.io/contrib/instrumentation/net/http
// Version is the current release version of the otelhttp instrumentation.
func Version() string {
return "0.48.0"
return "0.49.0"
// This string is updated by the pre_release.sh script during release
}

View file

@ -18,6 +18,7 @@ import (
"context"
"io"
"net/http"
"sync/atomic"
"go.opentelemetry.io/otel/propagation"
)
@ -30,14 +31,14 @@ type bodyWrapper struct {
io.ReadCloser
record func(n int64) // must not be nil
read int64
read atomic.Int64
err error
}
func (w *bodyWrapper) Read(b []byte) (int, error) {
n, err := w.ReadCloser.Read(b)
n1 := int64(n)
w.read += n1
w.read.Add(n1)
w.err = err
w.record(n1)
return n, err

View file

@ -3,3 +3,5 @@ fo
te
collison
consequentially
ans
nam

Some files were not shown because too many files have changed in this diff Show more