1# -*- coding: utf-8 -*-
2# Copyright 2022 Google LLC
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8# http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15#
16from typing import Callable, Dict, Optional, Sequence, Tuple, Union
17import warnings
18
19from google.api_core import gapic_v1, grpc_helpers
20import google.auth # type: ignore
21from google.auth import credentials as ga_credentials # type: ignore
22from google.auth.transport.grpc import SslCredentials # type: ignore
23from google.iam.v1 import iam_policy_pb2 # type: ignore
24from google.iam.v1 import policy_pb2 # type: ignore
25from google.longrunning import operations_pb2
26import grpc # type: ignore
27
28from google.cloud.resourcemanager_v3.types import organizations
29
30from .base import DEFAULT_CLIENT_INFO, OrganizationsTransport
31
32
33class OrganizationsGrpcTransport(OrganizationsTransport):
34 """gRPC backend transport for Organizations.
35
36 Allows users to manage their organization resources.
37
38 This class defines the same methods as the primary client, so the
39 primary client can load the underlying transport implementation
40 and call it.
41
42 It sends protocol buffers over the wire using gRPC (which is built on
43 top of HTTP/2); the ``grpcio`` package must be installed.
44 """
45
46 _stubs: Dict[str, Callable]
47
48 def __init__(
49 self,
50 *,
51 host: str = "cloudresourcemanager.googleapis.com",
52 credentials: Optional[ga_credentials.Credentials] = None,
53 credentials_file: Optional[str] = None,
54 scopes: Optional[Sequence[str]] = None,
55 channel: Optional[grpc.Channel] = None,
56 api_mtls_endpoint: Optional[str] = None,
57 client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None,
58 ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None,
59 client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None,
60 quota_project_id: Optional[str] = None,
61 client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
62 always_use_jwt_access: Optional[bool] = False,
63 api_audience: Optional[str] = None,
64 ) -> None:
65 """Instantiate the transport.
66
67 Args:
68 host (Optional[str]):
69 The hostname to connect to.
70 credentials (Optional[google.auth.credentials.Credentials]): The
71 authorization credentials to attach to requests. These
72 credentials identify the application to the service; if none
73 are specified, the client will attempt to ascertain the
74 credentials from the environment.
75 This argument is ignored if ``channel`` is provided.
76 credentials_file (Optional[str]): A file with credentials that can
77 be loaded with :func:`google.auth.load_credentials_from_file`.
78 This argument is ignored if ``channel`` is provided.
79 scopes (Optional(Sequence[str])): A list of scopes. This argument is
80 ignored if ``channel`` is provided.
81 channel (Optional[grpc.Channel]): A ``Channel`` instance through
82 which to make calls.
83 api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint.
84 If provided, it overrides the ``host`` argument and tries to create
85 a mutual TLS channel with client SSL credentials from
86 ``client_cert_source`` or application default SSL credentials.
87 client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]):
88 Deprecated. A callback to provide client SSL certificate bytes and
89 private key bytes, both in PEM format. It is ignored if
90 ``api_mtls_endpoint`` is None.
91 ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials
92 for the grpc channel. It is ignored if ``channel`` is provided.
93 client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]):
94 A callback to provide client certificate bytes and private key bytes,
95 both in PEM format. It is used to configure a mutual TLS channel. It is
96 ignored if ``channel`` or ``ssl_channel_credentials`` is provided.
97 quota_project_id (Optional[str]): An optional project to use for billing
98 and quota.
99 client_info (google.api_core.gapic_v1.client_info.ClientInfo):
100 The client info used to send a user-agent string along with
101 API requests. If ``None``, then default info will be used.
102 Generally, you only need to set this if you're developing
103 your own client library.
104 always_use_jwt_access (Optional[bool]): Whether self signed JWT should
105 be used for service account credentials.
106
107 Raises:
108 google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport
109 creation failed for any reason.
110 google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
111 and ``credentials_file`` are passed.
112 """
113 self._grpc_channel = None
114 self._ssl_channel_credentials = ssl_channel_credentials
115 self._stubs: Dict[str, Callable] = {}
116
117 if api_mtls_endpoint:
118 warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning)
119 if client_cert_source:
120 warnings.warn("client_cert_source is deprecated", DeprecationWarning)
121
122 if channel:
123 # Ignore credentials if a channel was passed.
124 credentials = False
125 # If a channel was explicitly provided, set it.
126 self._grpc_channel = channel
127 self._ssl_channel_credentials = None
128
129 else:
130 if api_mtls_endpoint:
131 host = api_mtls_endpoint
132
133 # Create SSL credentials with client_cert_source or application
134 # default SSL credentials.
135 if client_cert_source:
136 cert, key = client_cert_source()
137 self._ssl_channel_credentials = grpc.ssl_channel_credentials(
138 certificate_chain=cert, private_key=key
139 )
140 else:
141 self._ssl_channel_credentials = SslCredentials().ssl_credentials
142
143 else:
144 if client_cert_source_for_mtls and not ssl_channel_credentials:
145 cert, key = client_cert_source_for_mtls()
146 self._ssl_channel_credentials = grpc.ssl_channel_credentials(
147 certificate_chain=cert, private_key=key
148 )
149
150 # The base transport sets the host, credentials and scopes
151 super().__init__(
152 host=host,
153 credentials=credentials,
154 credentials_file=credentials_file,
155 scopes=scopes,
156 quota_project_id=quota_project_id,
157 client_info=client_info,
158 always_use_jwt_access=always_use_jwt_access,
159 api_audience=api_audience,
160 )
161
162 if not self._grpc_channel:
163 self._grpc_channel = type(self).create_channel(
164 self._host,
165 # use the credentials which are saved
166 credentials=self._credentials,
167 # Set ``credentials_file`` to ``None`` here as
168 # the credentials that we saved earlier should be used.
169 credentials_file=None,
170 scopes=self._scopes,
171 ssl_credentials=self._ssl_channel_credentials,
172 quota_project_id=quota_project_id,
173 options=[
174 ("grpc.max_send_message_length", -1),
175 ("grpc.max_receive_message_length", -1),
176 ],
177 )
178
179 # Wrap messages. This must be done after self._grpc_channel exists
180 self._prep_wrapped_messages(client_info)
181
182 @classmethod
183 def create_channel(
184 cls,
185 host: str = "cloudresourcemanager.googleapis.com",
186 credentials: Optional[ga_credentials.Credentials] = None,
187 credentials_file: Optional[str] = None,
188 scopes: Optional[Sequence[str]] = None,
189 quota_project_id: Optional[str] = None,
190 **kwargs,
191 ) -> grpc.Channel:
192 """Create and return a gRPC channel object.
193 Args:
194 host (Optional[str]): The host for the channel to use.
195 credentials (Optional[~.Credentials]): The
196 authorization credentials to attach to requests. These
197 credentials identify this application to the service. If
198 none are specified, the client will attempt to ascertain
199 the credentials from the environment.
200 credentials_file (Optional[str]): A file with credentials that can
201 be loaded with :func:`google.auth.load_credentials_from_file`.
202 This argument is mutually exclusive with credentials.
203 scopes (Optional[Sequence[str]]): A optional list of scopes needed for this
204 service. These are only used when credentials are not specified and
205 are passed to :func:`google.auth.default`.
206 quota_project_id (Optional[str]): An optional project to use for billing
207 and quota.
208 kwargs (Optional[dict]): Keyword arguments, which are passed to the
209 channel creation.
210 Returns:
211 grpc.Channel: A gRPC channel object.
212
213 Raises:
214 google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
215 and ``credentials_file`` are passed.
216 """
217
218 return grpc_helpers.create_channel(
219 host,
220 credentials=credentials,
221 credentials_file=credentials_file,
222 quota_project_id=quota_project_id,
223 default_scopes=cls.AUTH_SCOPES,
224 scopes=scopes,
225 default_host=cls.DEFAULT_HOST,
226 **kwargs,
227 )
228
229 @property
230 def grpc_channel(self) -> grpc.Channel:
231 """Return the channel designed to connect to this service."""
232 return self._grpc_channel
233
234 @property
235 def get_organization(
236 self,
237 ) -> Callable[[organizations.GetOrganizationRequest], organizations.Organization]:
238 r"""Return a callable for the get organization method over gRPC.
239
240 Fetches an organization resource identified by the
241 specified resource name.
242
243 Returns:
244 Callable[[~.GetOrganizationRequest],
245 ~.Organization]:
246 A function that, when called, will call the underlying RPC
247 on the server.
248 """
249 # Generate a "stub function" on-the-fly which will actually make
250 # the request.
251 # gRPC handles serialization and deserialization, so we just need
252 # to pass in the functions for each.
253 if "get_organization" not in self._stubs:
254 self._stubs["get_organization"] = self.grpc_channel.unary_unary(
255 "/google.cloud.resourcemanager.v3.Organizations/GetOrganization",
256 request_serializer=organizations.GetOrganizationRequest.serialize,
257 response_deserializer=organizations.Organization.deserialize,
258 )
259 return self._stubs["get_organization"]
260
261 @property
262 def search_organizations(
263 self,
264 ) -> Callable[
265 [organizations.SearchOrganizationsRequest],
266 organizations.SearchOrganizationsResponse,
267 ]:
268 r"""Return a callable for the search organizations method over gRPC.
269
270 Searches organization resources that are visible to the user and
271 satisfy the specified filter. This method returns organizations
272 in an unspecified order. New organizations do not necessarily
273 appear at the end of the results, and may take a small amount of
274 time to appear.
275
276 Search will only return organizations on which the user has the
277 permission ``resourcemanager.organizations.get``
278
279 Returns:
280 Callable[[~.SearchOrganizationsRequest],
281 ~.SearchOrganizationsResponse]:
282 A function that, when called, will call the underlying RPC
283 on the server.
284 """
285 # Generate a "stub function" on-the-fly which will actually make
286 # the request.
287 # gRPC handles serialization and deserialization, so we just need
288 # to pass in the functions for each.
289 if "search_organizations" not in self._stubs:
290 self._stubs["search_organizations"] = self.grpc_channel.unary_unary(
291 "/google.cloud.resourcemanager.v3.Organizations/SearchOrganizations",
292 request_serializer=organizations.SearchOrganizationsRequest.serialize,
293 response_deserializer=organizations.SearchOrganizationsResponse.deserialize,
294 )
295 return self._stubs["search_organizations"]
296
297 @property
298 def get_iam_policy(
299 self,
300 ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]:
301 r"""Return a callable for the get iam policy method over gRPC.
302
303 Gets the access control policy for an organization resource. The
304 policy may be empty if no such policy or resource exists. The
305 ``resource`` field should be the organization's resource name,
306 for example: "organizations/123".
307
308 Authorization requires the IAM permission
309 ``resourcemanager.organizations.getIamPolicy`` on the specified
310 organization.
311
312 Returns:
313 Callable[[~.GetIamPolicyRequest],
314 ~.Policy]:
315 A function that, when called, will call the underlying RPC
316 on the server.
317 """
318 # Generate a "stub function" on-the-fly which will actually make
319 # the request.
320 # gRPC handles serialization and deserialization, so we just need
321 # to pass in the functions for each.
322 if "get_iam_policy" not in self._stubs:
323 self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary(
324 "/google.cloud.resourcemanager.v3.Organizations/GetIamPolicy",
325 request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString,
326 response_deserializer=policy_pb2.Policy.FromString,
327 )
328 return self._stubs["get_iam_policy"]
329
330 @property
331 def set_iam_policy(
332 self,
333 ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]:
334 r"""Return a callable for the set iam policy method over gRPC.
335
336 Sets the access control policy on an organization resource.
337 Replaces any existing policy. The ``resource`` field should be
338 the organization's resource name, for example:
339 "organizations/123".
340
341 Authorization requires the IAM permission
342 ``resourcemanager.organizations.setIamPolicy`` on the specified
343 organization.
344
345 Returns:
346 Callable[[~.SetIamPolicyRequest],
347 ~.Policy]:
348 A function that, when called, will call the underlying RPC
349 on the server.
350 """
351 # Generate a "stub function" on-the-fly which will actually make
352 # the request.
353 # gRPC handles serialization and deserialization, so we just need
354 # to pass in the functions for each.
355 if "set_iam_policy" not in self._stubs:
356 self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary(
357 "/google.cloud.resourcemanager.v3.Organizations/SetIamPolicy",
358 request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString,
359 response_deserializer=policy_pb2.Policy.FromString,
360 )
361 return self._stubs["set_iam_policy"]
362
363 @property
364 def test_iam_permissions(
365 self,
366 ) -> Callable[
367 [iam_policy_pb2.TestIamPermissionsRequest],
368 iam_policy_pb2.TestIamPermissionsResponse,
369 ]:
370 r"""Return a callable for the test iam permissions method over gRPC.
371
372 Returns the permissions that a caller has on the specified
373 organization. The ``resource`` field should be the
374 organization's resource name, for example: "organizations/123".
375
376 There are no permissions required for making this API call.
377
378 Returns:
379 Callable[[~.TestIamPermissionsRequest],
380 ~.TestIamPermissionsResponse]:
381 A function that, when called, will call the underlying RPC
382 on the server.
383 """
384 # Generate a "stub function" on-the-fly which will actually make
385 # the request.
386 # gRPC handles serialization and deserialization, so we just need
387 # to pass in the functions for each.
388 if "test_iam_permissions" not in self._stubs:
389 self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary(
390 "/google.cloud.resourcemanager.v3.Organizations/TestIamPermissions",
391 request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString,
392 response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString,
393 )
394 return self._stubs["test_iam_permissions"]
395
396 def close(self):
397 self.grpc_channel.close()
398
399 @property
400 def get_operation(
401 self,
402 ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]:
403 r"""Return a callable for the get_operation method over gRPC."""
404 # Generate a "stub function" on-the-fly which will actually make
405 # the request.
406 # gRPC handles serialization and deserialization, so we just need
407 # to pass in the functions for each.
408 if "get_operation" not in self._stubs:
409 self._stubs["get_operation"] = self.grpc_channel.unary_unary(
410 "/google.longrunning.Operations/GetOperation",
411 request_serializer=operations_pb2.GetOperationRequest.SerializeToString,
412 response_deserializer=operations_pb2.Operation.FromString,
413 )
414 return self._stubs["get_operation"]
415
416 @property
417 def kind(self) -> str:
418 return "grpc"
419
420
421__all__ = ("OrganizationsGrpcTransport",)