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