18
18
import logging
19
19
from typing import Optional , TYPE_CHECKING
20
20
21
- import aiohttp
22
21
from cryptography import x509
22
+ from google .api_core .client_options import ClientOptions
23
+ from google .api_core .gapic_v1 .client_info import ClientInfo
23
24
from google .auth .credentials import TokenState
24
25
from google .auth .transport import requests
26
+ import google .cloud .alloydb_v1beta as v1beta
27
+ from google .protobuf import duration_pb2
25
28
26
29
from google .cloud .alloydb .connector .connection_info import ConnectionInfo
27
30
from google .cloud .alloydb .connector .version import __version__ as version
@@ -55,7 +58,7 @@ def __init__(
55
58
alloydb_api_endpoint : str ,
56
59
quota_project : Optional [str ],
57
60
credentials : Credentials ,
58
- client : Optional [aiohttp . ClientSession ] = None ,
61
+ client : Optional [v1beta . AlloyDBAdminAsyncClient ] = None ,
59
62
driver : Optional [str ] = None ,
60
63
user_agent : Optional [str ] = None ,
61
64
) -> None :
@@ -72,23 +75,28 @@ def __init__(
72
75
A credentials object created from the google-auth Python library.
73
76
Must have the AlloyDB Admin scopes. For more info check out
74
77
https://google-auth.readthedocs.io/en/latest/.
75
- client (aiohttp.ClientSession ): Async client used to make requests to
76
- AlloyDB APIs.
78
+ client (v1beta.AlloyDBAdminAsyncClient ): Async client used to make
79
+ requests to AlloyDB APIs.
77
80
Optional, defaults to None and creates new client.
78
81
driver (str): Database driver to be used by the client.
79
82
"""
80
83
user_agent = _format_user_agent (driver , user_agent )
81
- headers = {
82
- "x-goog-api-client" : user_agent ,
83
- "User-Agent" : user_agent ,
84
- "Content-Type" : "application/json" ,
85
- }
86
- if quota_project :
87
- headers ["x-goog-user-project" ] = quota_project
88
84
89
- self ._client = client if client else aiohttp .ClientSession (headers = headers )
85
+ self ._client = (
86
+ client
87
+ if client
88
+ else v1beta .AlloyDBAdminAsyncClient (
89
+ credentials = credentials ,
90
+ client_options = ClientOptions (
91
+ api_endpoint = alloydb_api_endpoint ,
92
+ quota_project_id = quota_project ,
93
+ ),
94
+ client_info = ClientInfo (
95
+ user_agent = user_agent ,
96
+ ),
97
+ )
98
+ )
90
99
self ._credentials = credentials
91
- self ._alloydb_api_endpoint = alloydb_api_endpoint
92
100
# asyncpg does not currently support using metadata exchange
93
101
# only use metadata exchange for pg8000 driver
94
102
self ._use_metadata = True if driver == "pg8000" else False
@@ -118,35 +126,21 @@ async def _get_metadata(
118
126
Returns:
119
127
dict: IP addresses of the AlloyDB instance.
120
128
"""
121
- headers = {
122
- "Authorization" : f"Bearer { self . _credentials . token } " ,
123
- }
129
+ parent = (
130
+ f"projects/ { project } /locations/ { region } /clusters/ { cluster } /instances/ { name } "
131
+ )
124
132
125
- url = f"{ self ._alloydb_api_endpoint } /{ API_VERSION } /projects/{ project } /locations/{ region } /clusters/{ cluster } /instances/{ name } /connectionInfo"
126
-
127
- resp = await self ._client .get (url , headers = headers )
128
- # try to get response json for better error message
129
- try :
130
- resp_dict = await resp .json ()
131
- if resp .status >= 400 :
132
- # if detailed error message is in json response, use as error message
133
- message = resp_dict .get ("error" , {}).get ("message" )
134
- if message :
135
- resp .reason = message
136
- # skip, raise_for_status will catch all errors in finally block
137
- except Exception :
138
- pass
139
- finally :
140
- resp .raise_for_status ()
133
+ req = v1beta .GetConnectionInfoRequest (parent = parent )
134
+ resp = await self ._client .get_connection_info (request = req )
141
135
142
136
# Remove trailing period from PSC DNS name.
143
- psc_dns = resp_dict . get ( "pscDnsName" )
137
+ psc_dns = resp . psc_dns_name
144
138
if psc_dns :
145
139
psc_dns = psc_dns .rstrip ("." )
146
140
147
141
return {
148
- "PRIVATE" : resp_dict . get ( "ipAddress" ) ,
149
- "PUBLIC" : resp_dict . get ( "publicIpAddress" ) ,
142
+ "PRIVATE" : resp . ip_address ,
143
+ "PUBLIC" : resp . public_ip_address ,
150
144
"PSC" : psc_dns ,
151
145
}
152
146
@@ -175,34 +169,17 @@ async def _get_client_certificate(
175
169
tuple[str, list[str]]: tuple containing the CA certificate
176
170
and certificate chain for the AlloyDB instance.
177
171
"""
178
- headers = {
179
- "Authorization" : f"Bearer { self ._credentials .token } " ,
180
- }
181
-
182
- url = f"{ self ._alloydb_api_endpoint } /{ API_VERSION } /projects/{ project } /locations/{ region } /clusters/{ cluster } :generateClientCertificate"
183
-
184
- data = {
185
- "publicKey" : pub_key ,
186
- "certDuration" : "3600s" ,
187
- "useMetadataExchange" : self ._use_metadata ,
188
- }
189
-
190
- resp = await self ._client .post (url , headers = headers , json = data )
191
- # try to get response json for better error message
192
- try :
193
- resp_dict = await resp .json ()
194
- if resp .status >= 400 :
195
- # if detailed error message is in json response, use as error message
196
- message = resp_dict .get ("error" , {}).get ("message" )
197
- if message :
198
- resp .reason = message
199
- # skip, raise_for_status will catch all errors in finally block
200
- except Exception :
201
- pass
202
- finally :
203
- resp .raise_for_status ()
204
-
205
- return (resp_dict ["caCert" ], resp_dict ["pemCertificateChain" ])
172
+ parent = f"projects/{ project } /locations/{ region } /clusters/{ cluster } "
173
+ dur = duration_pb2 .Duration ()
174
+ dur .seconds = 3600
175
+ req = v1beta .GenerateClientCertificateRequest (
176
+ parent = parent ,
177
+ cert_duration = dur ,
178
+ public_key = pub_key ,
179
+ use_metadata_exchange = self ._use_metadata ,
180
+ )
181
+ resp = await self ._client .generate_client_certificate (request = req )
182
+ return (resp .ca_cert , resp .pem_certificate_chain )
206
183
207
184
async def get_connection_info (
208
185
self ,
@@ -267,9 +244,3 @@ async def get_connection_info(
267
244
ip_addrs ,
268
245
expiration ,
269
246
)
270
-
271
- async def close (self ) -> None :
272
- """Close AlloyDBClient gracefully."""
273
- logger .debug ("Waiting for connector's http client to close" )
274
- await self ._client .close ()
275
- logger .debug ("Closed connector's http client" )
0 commit comments