1# -*- coding: utf-8 -*-
2# Copyright 2020 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#
16import abc
17from typing import Awaitable, Callable, Dict, Optional, Sequence, Union
18import packaging.version
19import pkg_resources
20
21import google.auth  # type: ignore
22import google.api_core  # type: ignore
23from google.api_core import exceptions as core_exceptions  # type: ignore
24from google.api_core import gapic_v1  # type: ignore
25from google.api_core import retry as retries  # type: ignore
26from google.api_core import operations_v1  # type: ignore
27from google.auth import credentials as ga_credentials  # type: ignore
28from google.oauth2 import service_account  # type: ignore
29
30from google.cloud.bigtable_admin_v2.types import bigtable_table_admin
31from google.cloud.bigtable_admin_v2.types import table
32from google.cloud.bigtable_admin_v2.types import table as gba_table
33from google.iam.v1 import iam_policy_pb2  # type: ignore
34from google.iam.v1 import policy_pb2  # type: ignore
35from google.longrunning import operations_pb2  # type: ignore
36from google.protobuf import empty_pb2  # type: ignore
37
38try:
39    DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
40        gapic_version=pkg_resources.get_distribution(
41            "google-cloud-bigtable-admin",
42        ).version,
43    )
44except pkg_resources.DistributionNotFound:
45    DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo()
46
47try:
48    # google.auth.__version__ was added in 1.26.0
49    _GOOGLE_AUTH_VERSION = google.auth.__version__
50except AttributeError:
51    try:  # try pkg_resources if it is available
52        _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version
53    except pkg_resources.DistributionNotFound:  # pragma: NO COVER
54        _GOOGLE_AUTH_VERSION = None
55
56
57class BigtableTableAdminTransport(abc.ABC):
58    """Abstract transport class for BigtableTableAdmin."""
59
60    AUTH_SCOPES = (
61        "https://www.googleapis.com/auth/bigtable.admin",
62        "https://www.googleapis.com/auth/bigtable.admin.table",
63        "https://www.googleapis.com/auth/cloud-bigtable.admin",
64        "https://www.googleapis.com/auth/cloud-bigtable.admin.table",
65        "https://www.googleapis.com/auth/cloud-platform",
66        "https://www.googleapis.com/auth/cloud-platform.read-only",
67    )
68
69    DEFAULT_HOST: str = "bigtableadmin.googleapis.com"
70
71    def __init__(
72        self,
73        *,
74        host: str = DEFAULT_HOST,
75        credentials: ga_credentials.Credentials = None,
76        credentials_file: Optional[str] = None,
77        scopes: Optional[Sequence[str]] = None,
78        quota_project_id: Optional[str] = None,
79        client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
80        always_use_jwt_access: Optional[bool] = False,
81        **kwargs,
82    ) -> None:
83        """Instantiate the transport.
84
85        Args:
86            host (Optional[str]):
87                 The hostname to connect to.
88            credentials (Optional[google.auth.credentials.Credentials]): The
89                authorization credentials to attach to requests. These
90                credentials identify the application to the service; if none
91                are specified, the client will attempt to ascertain the
92                credentials from the environment.
93            credentials_file (Optional[str]): A file with credentials that can
94                be loaded with :func:`google.auth.load_credentials_from_file`.
95                This argument is mutually exclusive with credentials.
96            scopes (Optional[Sequence[str]]): A list of scopes.
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        # Save the hostname. Default to port 443 (HTTPS) if none is specified.
108        if ":" not in host:
109            host += ":443"
110        self._host = host
111
112        scopes_kwargs = self._get_scopes_kwargs(self._host, scopes)
113
114        # Save the scopes.
115        self._scopes = scopes
116
117        # If no credentials are provided, then determine the appropriate
118        # defaults.
119        if credentials and credentials_file:
120            raise core_exceptions.DuplicateCredentialArgs(
121                "'credentials_file' and 'credentials' are mutually exclusive"
122            )
123
124        if credentials_file is not None:
125            credentials, _ = google.auth.load_credentials_from_file(
126                credentials_file, **scopes_kwargs, quota_project_id=quota_project_id
127            )
128
129        elif credentials is None:
130            credentials, _ = google.auth.default(
131                **scopes_kwargs, quota_project_id=quota_project_id
132            )
133
134        # If the credentials are service account credentials, then always try to use self signed JWT.
135        if (
136            always_use_jwt_access
137            and isinstance(credentials, service_account.Credentials)
138            and hasattr(service_account.Credentials, "with_always_use_jwt_access")
139        ):
140            credentials = credentials.with_always_use_jwt_access(True)
141
142        # Save the credentials.
143        self._credentials = credentials
144
145    # TODO(busunkim): This method is in the base transport
146    # to avoid duplicating code across the transport classes. These functions
147    # should be deleted once the minimum required versions of google-auth is increased.
148
149    # TODO: Remove this function once google-auth >= 1.25.0 is required
150    @classmethod
151    def _get_scopes_kwargs(
152        cls, host: str, scopes: Optional[Sequence[str]]
153    ) -> Dict[str, Optional[Sequence[str]]]:
154        """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version"""
155
156        scopes_kwargs = {}
157
158        if _GOOGLE_AUTH_VERSION and (
159            packaging.version.parse(_GOOGLE_AUTH_VERSION)
160            >= packaging.version.parse("1.25.0")
161        ):
162            scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES}
163        else:
164            scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES}
165
166        return scopes_kwargs
167
168    def _prep_wrapped_messages(self, client_info):
169        # Precompute the wrapped methods.
170        self._wrapped_methods = {
171            self.create_table: gapic_v1.method.wrap_method(
172                self.create_table, default_timeout=300.0, client_info=client_info,
173            ),
174            self.create_table_from_snapshot: gapic_v1.method.wrap_method(
175                self.create_table_from_snapshot,
176                default_timeout=None,
177                client_info=client_info,
178            ),
179            self.list_tables: gapic_v1.method.wrap_method(
180                self.list_tables,
181                default_retry=retries.Retry(
182                    initial=1.0,
183                    maximum=60.0,
184                    multiplier=2,
185                    predicate=retries.if_exception_type(
186                        core_exceptions.DeadlineExceeded,
187                        core_exceptions.ServiceUnavailable,
188                    ),
189                    deadline=60.0,
190                ),
191                default_timeout=60.0,
192                client_info=client_info,
193            ),
194            self.get_table: gapic_v1.method.wrap_method(
195                self.get_table,
196                default_retry=retries.Retry(
197                    initial=1.0,
198                    maximum=60.0,
199                    multiplier=2,
200                    predicate=retries.if_exception_type(
201                        core_exceptions.DeadlineExceeded,
202                        core_exceptions.ServiceUnavailable,
203                    ),
204                    deadline=60.0,
205                ),
206                default_timeout=60.0,
207                client_info=client_info,
208            ),
209            self.delete_table: gapic_v1.method.wrap_method(
210                self.delete_table, default_timeout=60.0, client_info=client_info,
211            ),
212            self.modify_column_families: gapic_v1.method.wrap_method(
213                self.modify_column_families,
214                default_timeout=300.0,
215                client_info=client_info,
216            ),
217            self.drop_row_range: gapic_v1.method.wrap_method(
218                self.drop_row_range, default_timeout=3600.0, client_info=client_info,
219            ),
220            self.generate_consistency_token: gapic_v1.method.wrap_method(
221                self.generate_consistency_token,
222                default_retry=retries.Retry(
223                    initial=1.0,
224                    maximum=60.0,
225                    multiplier=2,
226                    predicate=retries.if_exception_type(
227                        core_exceptions.DeadlineExceeded,
228                        core_exceptions.ServiceUnavailable,
229                    ),
230                    deadline=60.0,
231                ),
232                default_timeout=60.0,
233                client_info=client_info,
234            ),
235            self.check_consistency: gapic_v1.method.wrap_method(
236                self.check_consistency,
237                default_retry=retries.Retry(
238                    initial=1.0,
239                    maximum=60.0,
240                    multiplier=2,
241                    predicate=retries.if_exception_type(
242                        core_exceptions.DeadlineExceeded,
243                        core_exceptions.ServiceUnavailable,
244                    ),
245                    deadline=60.0,
246                ),
247                default_timeout=60.0,
248                client_info=client_info,
249            ),
250            self.snapshot_table: gapic_v1.method.wrap_method(
251                self.snapshot_table, default_timeout=None, client_info=client_info,
252            ),
253            self.get_snapshot: gapic_v1.method.wrap_method(
254                self.get_snapshot,
255                default_retry=retries.Retry(
256                    initial=1.0,
257                    maximum=60.0,
258                    multiplier=2,
259                    predicate=retries.if_exception_type(
260                        core_exceptions.DeadlineExceeded,
261                        core_exceptions.ServiceUnavailable,
262                    ),
263                    deadline=60.0,
264                ),
265                default_timeout=60.0,
266                client_info=client_info,
267            ),
268            self.list_snapshots: gapic_v1.method.wrap_method(
269                self.list_snapshots,
270                default_retry=retries.Retry(
271                    initial=1.0,
272                    maximum=60.0,
273                    multiplier=2,
274                    predicate=retries.if_exception_type(
275                        core_exceptions.DeadlineExceeded,
276                        core_exceptions.ServiceUnavailable,
277                    ),
278                    deadline=60.0,
279                ),
280                default_timeout=60.0,
281                client_info=client_info,
282            ),
283            self.delete_snapshot: gapic_v1.method.wrap_method(
284                self.delete_snapshot, default_timeout=60.0, client_info=client_info,
285            ),
286            self.create_backup: gapic_v1.method.wrap_method(
287                self.create_backup, default_timeout=60.0, client_info=client_info,
288            ),
289            self.get_backup: gapic_v1.method.wrap_method(
290                self.get_backup,
291                default_retry=retries.Retry(
292                    initial=1.0,
293                    maximum=60.0,
294                    multiplier=2,
295                    predicate=retries.if_exception_type(
296                        core_exceptions.DeadlineExceeded,
297                        core_exceptions.ServiceUnavailable,
298                    ),
299                    deadline=60.0,
300                ),
301                default_timeout=60.0,
302                client_info=client_info,
303            ),
304            self.update_backup: gapic_v1.method.wrap_method(
305                self.update_backup, default_timeout=60.0, client_info=client_info,
306            ),
307            self.delete_backup: gapic_v1.method.wrap_method(
308                self.delete_backup, default_timeout=60.0, client_info=client_info,
309            ),
310            self.list_backups: gapic_v1.method.wrap_method(
311                self.list_backups,
312                default_retry=retries.Retry(
313                    initial=1.0,
314                    maximum=60.0,
315                    multiplier=2,
316                    predicate=retries.if_exception_type(
317                        core_exceptions.DeadlineExceeded,
318                        core_exceptions.ServiceUnavailable,
319                    ),
320                    deadline=60.0,
321                ),
322                default_timeout=60.0,
323                client_info=client_info,
324            ),
325            self.restore_table: gapic_v1.method.wrap_method(
326                self.restore_table, default_timeout=60.0, client_info=client_info,
327            ),
328            self.get_iam_policy: gapic_v1.method.wrap_method(
329                self.get_iam_policy,
330                default_retry=retries.Retry(
331                    initial=1.0,
332                    maximum=60.0,
333                    multiplier=2,
334                    predicate=retries.if_exception_type(
335                        core_exceptions.DeadlineExceeded,
336                        core_exceptions.ServiceUnavailable,
337                    ),
338                    deadline=60.0,
339                ),
340                default_timeout=60.0,
341                client_info=client_info,
342            ),
343            self.set_iam_policy: gapic_v1.method.wrap_method(
344                self.set_iam_policy, default_timeout=60.0, client_info=client_info,
345            ),
346            self.test_iam_permissions: gapic_v1.method.wrap_method(
347                self.test_iam_permissions,
348                default_retry=retries.Retry(
349                    initial=1.0,
350                    maximum=60.0,
351                    multiplier=2,
352                    predicate=retries.if_exception_type(
353                        core_exceptions.DeadlineExceeded,
354                        core_exceptions.ServiceUnavailable,
355                    ),
356                    deadline=60.0,
357                ),
358                default_timeout=60.0,
359                client_info=client_info,
360            ),
361        }
362
363    @property
364    def operations_client(self) -> operations_v1.OperationsClient:
365        """Return the client designed to process long-running operations."""
366        raise NotImplementedError()
367
368    @property
369    def create_table(
370        self,
371    ) -> Callable[
372        [bigtable_table_admin.CreateTableRequest],
373        Union[gba_table.Table, Awaitable[gba_table.Table]],
374    ]:
375        raise NotImplementedError()
376
377    @property
378    def create_table_from_snapshot(
379        self,
380    ) -> Callable[
381        [bigtable_table_admin.CreateTableFromSnapshotRequest],
382        Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]],
383    ]:
384        raise NotImplementedError()
385
386    @property
387    def list_tables(
388        self,
389    ) -> Callable[
390        [bigtable_table_admin.ListTablesRequest],
391        Union[
392            bigtable_table_admin.ListTablesResponse,
393            Awaitable[bigtable_table_admin.ListTablesResponse],
394        ],
395    ]:
396        raise NotImplementedError()
397
398    @property
399    def get_table(
400        self,
401    ) -> Callable[
402        [bigtable_table_admin.GetTableRequest],
403        Union[table.Table, Awaitable[table.Table]],
404    ]:
405        raise NotImplementedError()
406
407    @property
408    def delete_table(
409        self,
410    ) -> Callable[
411        [bigtable_table_admin.DeleteTableRequest],
412        Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]],
413    ]:
414        raise NotImplementedError()
415
416    @property
417    def modify_column_families(
418        self,
419    ) -> Callable[
420        [bigtable_table_admin.ModifyColumnFamiliesRequest],
421        Union[table.Table, Awaitable[table.Table]],
422    ]:
423        raise NotImplementedError()
424
425    @property
426    def drop_row_range(
427        self,
428    ) -> Callable[
429        [bigtable_table_admin.DropRowRangeRequest],
430        Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]],
431    ]:
432        raise NotImplementedError()
433
434    @property
435    def generate_consistency_token(
436        self,
437    ) -> Callable[
438        [bigtable_table_admin.GenerateConsistencyTokenRequest],
439        Union[
440            bigtable_table_admin.GenerateConsistencyTokenResponse,
441            Awaitable[bigtable_table_admin.GenerateConsistencyTokenResponse],
442        ],
443    ]:
444        raise NotImplementedError()
445
446    @property
447    def check_consistency(
448        self,
449    ) -> Callable[
450        [bigtable_table_admin.CheckConsistencyRequest],
451        Union[
452            bigtable_table_admin.CheckConsistencyResponse,
453            Awaitable[bigtable_table_admin.CheckConsistencyResponse],
454        ],
455    ]:
456        raise NotImplementedError()
457
458    @property
459    def snapshot_table(
460        self,
461    ) -> Callable[
462        [bigtable_table_admin.SnapshotTableRequest],
463        Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]],
464    ]:
465        raise NotImplementedError()
466
467    @property
468    def get_snapshot(
469        self,
470    ) -> Callable[
471        [bigtable_table_admin.GetSnapshotRequest],
472        Union[table.Snapshot, Awaitable[table.Snapshot]],
473    ]:
474        raise NotImplementedError()
475
476    @property
477    def list_snapshots(
478        self,
479    ) -> Callable[
480        [bigtable_table_admin.ListSnapshotsRequest],
481        Union[
482            bigtable_table_admin.ListSnapshotsResponse,
483            Awaitable[bigtable_table_admin.ListSnapshotsResponse],
484        ],
485    ]:
486        raise NotImplementedError()
487
488    @property
489    def delete_snapshot(
490        self,
491    ) -> Callable[
492        [bigtable_table_admin.DeleteSnapshotRequest],
493        Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]],
494    ]:
495        raise NotImplementedError()
496
497    @property
498    def create_backup(
499        self,
500    ) -> Callable[
501        [bigtable_table_admin.CreateBackupRequest],
502        Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]],
503    ]:
504        raise NotImplementedError()
505
506    @property
507    def get_backup(
508        self,
509    ) -> Callable[
510        [bigtable_table_admin.GetBackupRequest],
511        Union[table.Backup, Awaitable[table.Backup]],
512    ]:
513        raise NotImplementedError()
514
515    @property
516    def update_backup(
517        self,
518    ) -> Callable[
519        [bigtable_table_admin.UpdateBackupRequest],
520        Union[table.Backup, Awaitable[table.Backup]],
521    ]:
522        raise NotImplementedError()
523
524    @property
525    def delete_backup(
526        self,
527    ) -> Callable[
528        [bigtable_table_admin.DeleteBackupRequest],
529        Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]],
530    ]:
531        raise NotImplementedError()
532
533    @property
534    def list_backups(
535        self,
536    ) -> Callable[
537        [bigtable_table_admin.ListBackupsRequest],
538        Union[
539            bigtable_table_admin.ListBackupsResponse,
540            Awaitable[bigtable_table_admin.ListBackupsResponse],
541        ],
542    ]:
543        raise NotImplementedError()
544
545    @property
546    def restore_table(
547        self,
548    ) -> Callable[
549        [bigtable_table_admin.RestoreTableRequest],
550        Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]],
551    ]:
552        raise NotImplementedError()
553
554    @property
555    def get_iam_policy(
556        self,
557    ) -> Callable[
558        [iam_policy_pb2.GetIamPolicyRequest],
559        Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]],
560    ]:
561        raise NotImplementedError()
562
563    @property
564    def set_iam_policy(
565        self,
566    ) -> Callable[
567        [iam_policy_pb2.SetIamPolicyRequest],
568        Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]],
569    ]:
570        raise NotImplementedError()
571
572    @property
573    def test_iam_permissions(
574        self,
575    ) -> Callable[
576        [iam_policy_pb2.TestIamPermissionsRequest],
577        Union[
578            iam_policy_pb2.TestIamPermissionsResponse,
579            Awaitable[iam_policy_pb2.TestIamPermissionsResponse],
580        ],
581    ]:
582        raise NotImplementedError()
583
584
585__all__ = ("BigtableTableAdminTransport",)
586