...

Source file src/cloud.google.com/go/kms/inventory/apiv1/key_tracking_client.go

Documentation: cloud.google.com/go/kms/inventory/apiv1

     1  // Copyright 2024 Google LLC
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     https://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  // Code generated by protoc-gen-go_gapic. DO NOT EDIT.
    16  
    17  package inventory
    18  
    19  import (
    20  	"context"
    21  	"fmt"
    22  	"io"
    23  	"math"
    24  	"net/http"
    25  	"net/url"
    26  	"time"
    27  
    28  	inventorypb "cloud.google.com/go/kms/inventory/apiv1/inventorypb"
    29  	gax "github.com/googleapis/gax-go/v2"
    30  	"google.golang.org/api/googleapi"
    31  	"google.golang.org/api/iterator"
    32  	"google.golang.org/api/option"
    33  	"google.golang.org/api/option/internaloption"
    34  	gtransport "google.golang.org/api/transport/grpc"
    35  	httptransport "google.golang.org/api/transport/http"
    36  	"google.golang.org/grpc"
    37  	"google.golang.org/protobuf/encoding/protojson"
    38  	"google.golang.org/protobuf/proto"
    39  )
    40  
    41  var newKeyTrackingClientHook clientHook
    42  
    43  // KeyTrackingCallOptions contains the retry settings for each method of KeyTrackingClient.
    44  type KeyTrackingCallOptions struct {
    45  	GetProtectedResourcesSummary []gax.CallOption
    46  	SearchProtectedResources     []gax.CallOption
    47  }
    48  
    49  func defaultKeyTrackingGRPCClientOptions() []option.ClientOption {
    50  	return []option.ClientOption{
    51  		internaloption.WithDefaultEndpoint("kmsinventory.googleapis.com:443"),
    52  		internaloption.WithDefaultEndpointTemplate("kmsinventory.UNIVERSE_DOMAIN:443"),
    53  		internaloption.WithDefaultMTLSEndpoint("kmsinventory.mtls.googleapis.com:443"),
    54  		internaloption.WithDefaultUniverseDomain("googleapis.com"),
    55  		internaloption.WithDefaultAudience("https://kmsinventory.googleapis.com/"),
    56  		internaloption.WithDefaultScopes(DefaultAuthScopes()...),
    57  		internaloption.EnableJwtWithScope(),
    58  		option.WithGRPCDialOption(grpc.WithDefaultCallOptions(
    59  			grpc.MaxCallRecvMsgSize(math.MaxInt32))),
    60  	}
    61  }
    62  
    63  func defaultKeyTrackingCallOptions() *KeyTrackingCallOptions {
    64  	return &KeyTrackingCallOptions{
    65  		GetProtectedResourcesSummary: []gax.CallOption{
    66  			gax.WithTimeout(60000 * time.Millisecond),
    67  		},
    68  		SearchProtectedResources: []gax.CallOption{
    69  			gax.WithTimeout(60000 * time.Millisecond),
    70  		},
    71  	}
    72  }
    73  
    74  func defaultKeyTrackingRESTCallOptions() *KeyTrackingCallOptions {
    75  	return &KeyTrackingCallOptions{
    76  		GetProtectedResourcesSummary: []gax.CallOption{
    77  			gax.WithTimeout(60000 * time.Millisecond),
    78  		},
    79  		SearchProtectedResources: []gax.CallOption{
    80  			gax.WithTimeout(60000 * time.Millisecond),
    81  		},
    82  	}
    83  }
    84  
    85  // internalKeyTrackingClient is an interface that defines the methods available from KMS Inventory API.
    86  type internalKeyTrackingClient interface {
    87  	Close() error
    88  	setGoogleClientInfo(...string)
    89  	Connection() *grpc.ClientConn
    90  	GetProtectedResourcesSummary(context.Context, *inventorypb.GetProtectedResourcesSummaryRequest, ...gax.CallOption) (*inventorypb.ProtectedResourcesSummary, error)
    91  	SearchProtectedResources(context.Context, *inventorypb.SearchProtectedResourcesRequest, ...gax.CallOption) *ProtectedResourceIterator
    92  }
    93  
    94  // KeyTrackingClient is a client for interacting with KMS Inventory API.
    95  // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls.
    96  //
    97  // Returns information about the resources in an org that are protected by a
    98  // given Cloud KMS key via CMEK.
    99  type KeyTrackingClient struct {
   100  	// The internal transport-dependent client.
   101  	internalClient internalKeyTrackingClient
   102  
   103  	// The call options for this service.
   104  	CallOptions *KeyTrackingCallOptions
   105  }
   106  
   107  // Wrapper methods routed to the internal client.
   108  
   109  // Close closes the connection to the API service. The user should invoke this when
   110  // the client is no longer required.
   111  func (c *KeyTrackingClient) Close() error {
   112  	return c.internalClient.Close()
   113  }
   114  
   115  // setGoogleClientInfo sets the name and version of the application in
   116  // the `x-goog-api-client` header passed on each request. Intended for
   117  // use by Google-written clients.
   118  func (c *KeyTrackingClient) setGoogleClientInfo(keyval ...string) {
   119  	c.internalClient.setGoogleClientInfo(keyval...)
   120  }
   121  
   122  // Connection returns a connection to the API service.
   123  //
   124  // Deprecated: Connections are now pooled so this method does not always
   125  // return the same resource.
   126  func (c *KeyTrackingClient) Connection() *grpc.ClientConn {
   127  	return c.internalClient.Connection()
   128  }
   129  
   130  // GetProtectedResourcesSummary returns aggregate information about the resources protected by the given
   131  // Cloud KMS CryptoKey. Only resources within
   132  // the same Cloud organization as the key will be returned. The project that
   133  // holds the key must be part of an organization in order for this call to
   134  // succeed.
   135  func (c *KeyTrackingClient) GetProtectedResourcesSummary(ctx context.Context, req *inventorypb.GetProtectedResourcesSummaryRequest, opts ...gax.CallOption) (*inventorypb.ProtectedResourcesSummary, error) {
   136  	return c.internalClient.GetProtectedResourcesSummary(ctx, req, opts...)
   137  }
   138  
   139  // SearchProtectedResources returns metadata about the resources protected by the given Cloud KMS
   140  // CryptoKey in the given Cloud organization.
   141  func (c *KeyTrackingClient) SearchProtectedResources(ctx context.Context, req *inventorypb.SearchProtectedResourcesRequest, opts ...gax.CallOption) *ProtectedResourceIterator {
   142  	return c.internalClient.SearchProtectedResources(ctx, req, opts...)
   143  }
   144  
   145  // keyTrackingGRPCClient is a client for interacting with KMS Inventory API over gRPC transport.
   146  //
   147  // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls.
   148  type keyTrackingGRPCClient struct {
   149  	// Connection pool of gRPC connections to the service.
   150  	connPool gtransport.ConnPool
   151  
   152  	// Points back to the CallOptions field of the containing KeyTrackingClient
   153  	CallOptions **KeyTrackingCallOptions
   154  
   155  	// The gRPC API client.
   156  	keyTrackingClient inventorypb.KeyTrackingServiceClient
   157  
   158  	// The x-goog-* metadata to be sent with each request.
   159  	xGoogHeaders []string
   160  }
   161  
   162  // NewKeyTrackingClient creates a new key tracking service client based on gRPC.
   163  // The returned client must be Closed when it is done being used to clean up its underlying connections.
   164  //
   165  // Returns information about the resources in an org that are protected by a
   166  // given Cloud KMS key via CMEK.
   167  func NewKeyTrackingClient(ctx context.Context, opts ...option.ClientOption) (*KeyTrackingClient, error) {
   168  	clientOpts := defaultKeyTrackingGRPCClientOptions()
   169  	if newKeyTrackingClientHook != nil {
   170  		hookOpts, err := newKeyTrackingClientHook(ctx, clientHookParams{})
   171  		if err != nil {
   172  			return nil, err
   173  		}
   174  		clientOpts = append(clientOpts, hookOpts...)
   175  	}
   176  
   177  	connPool, err := gtransport.DialPool(ctx, append(clientOpts, opts...)...)
   178  	if err != nil {
   179  		return nil, err
   180  	}
   181  	client := KeyTrackingClient{CallOptions: defaultKeyTrackingCallOptions()}
   182  
   183  	c := &keyTrackingGRPCClient{
   184  		connPool:          connPool,
   185  		keyTrackingClient: inventorypb.NewKeyTrackingServiceClient(connPool),
   186  		CallOptions:       &client.CallOptions,
   187  	}
   188  	c.setGoogleClientInfo()
   189  
   190  	client.internalClient = c
   191  
   192  	return &client, nil
   193  }
   194  
   195  // Connection returns a connection to the API service.
   196  //
   197  // Deprecated: Connections are now pooled so this method does not always
   198  // return the same resource.
   199  func (c *keyTrackingGRPCClient) Connection() *grpc.ClientConn {
   200  	return c.connPool.Conn()
   201  }
   202  
   203  // setGoogleClientInfo sets the name and version of the application in
   204  // the `x-goog-api-client` header passed on each request. Intended for
   205  // use by Google-written clients.
   206  func (c *keyTrackingGRPCClient) setGoogleClientInfo(keyval ...string) {
   207  	kv := append([]string{"gl-go", gax.GoVersion}, keyval...)
   208  	kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "grpc", grpc.Version)
   209  	c.xGoogHeaders = []string{"x-goog-api-client", gax.XGoogHeader(kv...)}
   210  }
   211  
   212  // Close closes the connection to the API service. The user should invoke this when
   213  // the client is no longer required.
   214  func (c *keyTrackingGRPCClient) Close() error {
   215  	return c.connPool.Close()
   216  }
   217  
   218  // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls.
   219  type keyTrackingRESTClient struct {
   220  	// The http endpoint to connect to.
   221  	endpoint string
   222  
   223  	// The http client.
   224  	httpClient *http.Client
   225  
   226  	// The x-goog-* headers to be sent with each request.
   227  	xGoogHeaders []string
   228  
   229  	// Points back to the CallOptions field of the containing KeyTrackingClient
   230  	CallOptions **KeyTrackingCallOptions
   231  }
   232  
   233  // NewKeyTrackingRESTClient creates a new key tracking service rest client.
   234  //
   235  // Returns information about the resources in an org that are protected by a
   236  // given Cloud KMS key via CMEK.
   237  func NewKeyTrackingRESTClient(ctx context.Context, opts ...option.ClientOption) (*KeyTrackingClient, error) {
   238  	clientOpts := append(defaultKeyTrackingRESTClientOptions(), opts...)
   239  	httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...)
   240  	if err != nil {
   241  		return nil, err
   242  	}
   243  
   244  	callOpts := defaultKeyTrackingRESTCallOptions()
   245  	c := &keyTrackingRESTClient{
   246  		endpoint:    endpoint,
   247  		httpClient:  httpClient,
   248  		CallOptions: &callOpts,
   249  	}
   250  	c.setGoogleClientInfo()
   251  
   252  	return &KeyTrackingClient{internalClient: c, CallOptions: callOpts}, nil
   253  }
   254  
   255  func defaultKeyTrackingRESTClientOptions() []option.ClientOption {
   256  	return []option.ClientOption{
   257  		internaloption.WithDefaultEndpoint("https://kmsinventory.googleapis.com"),
   258  		internaloption.WithDefaultEndpointTemplate("https://kmsinventory.UNIVERSE_DOMAIN"),
   259  		internaloption.WithDefaultMTLSEndpoint("https://kmsinventory.mtls.googleapis.com"),
   260  		internaloption.WithDefaultUniverseDomain("googleapis.com"),
   261  		internaloption.WithDefaultAudience("https://kmsinventory.googleapis.com/"),
   262  		internaloption.WithDefaultScopes(DefaultAuthScopes()...),
   263  	}
   264  }
   265  
   266  // setGoogleClientInfo sets the name and version of the application in
   267  // the `x-goog-api-client` header passed on each request. Intended for
   268  // use by Google-written clients.
   269  func (c *keyTrackingRESTClient) setGoogleClientInfo(keyval ...string) {
   270  	kv := append([]string{"gl-go", gax.GoVersion}, keyval...)
   271  	kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN")
   272  	c.xGoogHeaders = []string{"x-goog-api-client", gax.XGoogHeader(kv...)}
   273  }
   274  
   275  // Close closes the connection to the API service. The user should invoke this when
   276  // the client is no longer required.
   277  func (c *keyTrackingRESTClient) Close() error {
   278  	// Replace httpClient with nil to force cleanup.
   279  	c.httpClient = nil
   280  	return nil
   281  }
   282  
   283  // Connection returns a connection to the API service.
   284  //
   285  // Deprecated: This method always returns nil.
   286  func (c *keyTrackingRESTClient) Connection() *grpc.ClientConn {
   287  	return nil
   288  }
   289  func (c *keyTrackingGRPCClient) GetProtectedResourcesSummary(ctx context.Context, req *inventorypb.GetProtectedResourcesSummaryRequest, opts ...gax.CallOption) (*inventorypb.ProtectedResourcesSummary, error) {
   290  	hds := []string{"x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))}
   291  
   292  	hds = append(c.xGoogHeaders, hds...)
   293  	ctx = gax.InsertMetadataIntoOutgoingContext(ctx, hds...)
   294  	opts = append((*c.CallOptions).GetProtectedResourcesSummary[0:len((*c.CallOptions).GetProtectedResourcesSummary):len((*c.CallOptions).GetProtectedResourcesSummary)], opts...)
   295  	var resp *inventorypb.ProtectedResourcesSummary
   296  	err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
   297  		var err error
   298  		resp, err = c.keyTrackingClient.GetProtectedResourcesSummary(ctx, req, settings.GRPC...)
   299  		return err
   300  	}, opts...)
   301  	if err != nil {
   302  		return nil, err
   303  	}
   304  	return resp, nil
   305  }
   306  
   307  func (c *keyTrackingGRPCClient) SearchProtectedResources(ctx context.Context, req *inventorypb.SearchProtectedResourcesRequest, opts ...gax.CallOption) *ProtectedResourceIterator {
   308  	hds := []string{"x-goog-request-params", fmt.Sprintf("%s=%v", "scope", url.QueryEscape(req.GetScope()))}
   309  
   310  	hds = append(c.xGoogHeaders, hds...)
   311  	ctx = gax.InsertMetadataIntoOutgoingContext(ctx, hds...)
   312  	opts = append((*c.CallOptions).SearchProtectedResources[0:len((*c.CallOptions).SearchProtectedResources):len((*c.CallOptions).SearchProtectedResources)], opts...)
   313  	it := &ProtectedResourceIterator{}
   314  	req = proto.Clone(req).(*inventorypb.SearchProtectedResourcesRequest)
   315  	it.InternalFetch = func(pageSize int, pageToken string) ([]*inventorypb.ProtectedResource, string, error) {
   316  		resp := &inventorypb.SearchProtectedResourcesResponse{}
   317  		if pageToken != "" {
   318  			req.PageToken = pageToken
   319  		}
   320  		if pageSize > math.MaxInt32 {
   321  			req.PageSize = math.MaxInt32
   322  		} else if pageSize != 0 {
   323  			req.PageSize = int32(pageSize)
   324  		}
   325  		err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
   326  			var err error
   327  			resp, err = c.keyTrackingClient.SearchProtectedResources(ctx, req, settings.GRPC...)
   328  			return err
   329  		}, opts...)
   330  		if err != nil {
   331  			return nil, "", err
   332  		}
   333  
   334  		it.Response = resp
   335  		return resp.GetProtectedResources(), resp.GetNextPageToken(), nil
   336  	}
   337  	fetch := func(pageSize int, pageToken string) (string, error) {
   338  		items, nextPageToken, err := it.InternalFetch(pageSize, pageToken)
   339  		if err != nil {
   340  			return "", err
   341  		}
   342  		it.items = append(it.items, items...)
   343  		return nextPageToken, nil
   344  	}
   345  
   346  	it.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf)
   347  	it.pageInfo.MaxSize = int(req.GetPageSize())
   348  	it.pageInfo.Token = req.GetPageToken()
   349  
   350  	return it
   351  }
   352  
   353  // GetProtectedResourcesSummary returns aggregate information about the resources protected by the given
   354  // Cloud KMS CryptoKey. Only resources within
   355  // the same Cloud organization as the key will be returned. The project that
   356  // holds the key must be part of an organization in order for this call to
   357  // succeed.
   358  func (c *keyTrackingRESTClient) GetProtectedResourcesSummary(ctx context.Context, req *inventorypb.GetProtectedResourcesSummaryRequest, opts ...gax.CallOption) (*inventorypb.ProtectedResourcesSummary, error) {
   359  	baseUrl, err := url.Parse(c.endpoint)
   360  	if err != nil {
   361  		return nil, err
   362  	}
   363  	baseUrl.Path += fmt.Sprintf("/v1/%v/protectedResourcesSummary", req.GetName())
   364  
   365  	params := url.Values{}
   366  	params.Add("$alt", "json;enum-encoding=int")
   367  
   368  	baseUrl.RawQuery = params.Encode()
   369  
   370  	// Build HTTP headers from client and context metadata.
   371  	hds := []string{"x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))}
   372  
   373  	hds = append(c.xGoogHeaders, hds...)
   374  	hds = append(hds, "Content-Type", "application/json")
   375  	headers := gax.BuildHeaders(ctx, hds...)
   376  	opts = append((*c.CallOptions).GetProtectedResourcesSummary[0:len((*c.CallOptions).GetProtectedResourcesSummary):len((*c.CallOptions).GetProtectedResourcesSummary)], opts...)
   377  	unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true}
   378  	resp := &inventorypb.ProtectedResourcesSummary{}
   379  	e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
   380  		if settings.Path != "" {
   381  			baseUrl.Path = settings.Path
   382  		}
   383  		httpReq, err := http.NewRequest("GET", baseUrl.String(), nil)
   384  		if err != nil {
   385  			return err
   386  		}
   387  		httpReq = httpReq.WithContext(ctx)
   388  		httpReq.Header = headers
   389  
   390  		httpRsp, err := c.httpClient.Do(httpReq)
   391  		if err != nil {
   392  			return err
   393  		}
   394  		defer httpRsp.Body.Close()
   395  
   396  		if err = googleapi.CheckResponse(httpRsp); err != nil {
   397  			return err
   398  		}
   399  
   400  		buf, err := io.ReadAll(httpRsp.Body)
   401  		if err != nil {
   402  			return err
   403  		}
   404  
   405  		if err := unm.Unmarshal(buf, resp); err != nil {
   406  			return err
   407  		}
   408  
   409  		return nil
   410  	}, opts...)
   411  	if e != nil {
   412  		return nil, e
   413  	}
   414  	return resp, nil
   415  }
   416  
   417  // SearchProtectedResources returns metadata about the resources protected by the given Cloud KMS
   418  // CryptoKey in the given Cloud organization.
   419  func (c *keyTrackingRESTClient) SearchProtectedResources(ctx context.Context, req *inventorypb.SearchProtectedResourcesRequest, opts ...gax.CallOption) *ProtectedResourceIterator {
   420  	it := &ProtectedResourceIterator{}
   421  	req = proto.Clone(req).(*inventorypb.SearchProtectedResourcesRequest)
   422  	unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true}
   423  	it.InternalFetch = func(pageSize int, pageToken string) ([]*inventorypb.ProtectedResource, string, error) {
   424  		resp := &inventorypb.SearchProtectedResourcesResponse{}
   425  		if pageToken != "" {
   426  			req.PageToken = pageToken
   427  		}
   428  		if pageSize > math.MaxInt32 {
   429  			req.PageSize = math.MaxInt32
   430  		} else if pageSize != 0 {
   431  			req.PageSize = int32(pageSize)
   432  		}
   433  		baseUrl, err := url.Parse(c.endpoint)
   434  		if err != nil {
   435  			return nil, "", err
   436  		}
   437  		baseUrl.Path += fmt.Sprintf("/v1/%v/protectedResources:search", req.GetScope())
   438  
   439  		params := url.Values{}
   440  		params.Add("$alt", "json;enum-encoding=int")
   441  		params.Add("cryptoKey", fmt.Sprintf("%v", req.GetCryptoKey()))
   442  		if req.GetPageSize() != 0 {
   443  			params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize()))
   444  		}
   445  		if req.GetPageToken() != "" {
   446  			params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken()))
   447  		}
   448  		if items := req.GetResourceTypes(); len(items) > 0 {
   449  			for _, item := range items {
   450  				params.Add("resourceTypes", fmt.Sprintf("%v", item))
   451  			}
   452  		}
   453  
   454  		baseUrl.RawQuery = params.Encode()
   455  
   456  		// Build HTTP headers from client and context metadata.
   457  		hds := append(c.xGoogHeaders, "Content-Type", "application/json")
   458  		headers := gax.BuildHeaders(ctx, hds...)
   459  		e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
   460  			if settings.Path != "" {
   461  				baseUrl.Path = settings.Path
   462  			}
   463  			httpReq, err := http.NewRequest("GET", baseUrl.String(), nil)
   464  			if err != nil {
   465  				return err
   466  			}
   467  			httpReq.Header = headers
   468  
   469  			httpRsp, err := c.httpClient.Do(httpReq)
   470  			if err != nil {
   471  				return err
   472  			}
   473  			defer httpRsp.Body.Close()
   474  
   475  			if err = googleapi.CheckResponse(httpRsp); err != nil {
   476  				return err
   477  			}
   478  
   479  			buf, err := io.ReadAll(httpRsp.Body)
   480  			if err != nil {
   481  				return err
   482  			}
   483  
   484  			if err := unm.Unmarshal(buf, resp); err != nil {
   485  				return err
   486  			}
   487  
   488  			return nil
   489  		}, opts...)
   490  		if e != nil {
   491  			return nil, "", e
   492  		}
   493  		it.Response = resp
   494  		return resp.GetProtectedResources(), resp.GetNextPageToken(), nil
   495  	}
   496  
   497  	fetch := func(pageSize int, pageToken string) (string, error) {
   498  		items, nextPageToken, err := it.InternalFetch(pageSize, pageToken)
   499  		if err != nil {
   500  			return "", err
   501  		}
   502  		it.items = append(it.items, items...)
   503  		return nextPageToken, nil
   504  	}
   505  
   506  	it.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf)
   507  	it.pageInfo.MaxSize = int(req.GetPageSize())
   508  	it.pageInfo.Token = req.GetPageToken()
   509  
   510  	return it
   511  }
   512  

View as plain text