-
Notifications
You must be signed in to change notification settings - Fork 3.3k
Expand file tree
/
Copy pathadmin_tool.py
More file actions
370 lines (324 loc) · 10.4 KB
/
admin_tool.py
File metadata and controls
370 lines (324 loc) · 10.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
# Copyright 2026 Google LLC
#
"""Spanner Admin Tool."""
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import annotations
from typing import Any
from google.auth.credentials import Credentials
from google.cloud import spanner_admin_instance_v1
from google.cloud.spanner_admin_database_v1 import DatabaseAdminAsyncClient
from google.cloud.spanner_admin_instance_v1 import InstanceAdminAsyncClient
async def list_instances(
project_id: str,
credentials: Credentials,
) -> dict[str, Any]:
"""List Spanner instances within a project.
Args:
project_id: The Google Cloud project id.
credentials: The credentials to use for the request.
Returns:
dict: Dictionary with the status and a list of the Spanner instance IDs.
Examples:
>>> await list_instances("my_project", credentials)
{
"status": "SUCCESS",
"results": [
"instance_1",
"instance_2"
]
}
"""
try:
instance_admin_api = InstanceAdminAsyncClient(credentials=credentials)
instances = []
async for instance in await instance_admin_api.list_instances(
parent=f"projects/{project_id}"
):
instances.append(instance.name.split("/")[-1])
return {"status": "SUCCESS", "results": instances}
except Exception as ex:
return {
"status": "ERROR",
"error_details": repr(ex),
}
async def get_instance(
project_id: str,
*,
instance_id: str,
credentials: Credentials,
) -> dict[str, Any]:
"""Get details of a Spanner instance.
Args:
project_id: The Google Cloud project id.
instance_id: The Spanner instance id.
credentials: The credentials to use for the request.
Returns:
dict: Dictionary with the status and the Spanner instance details.
Examples:
>>> await get_instance(project_id="my_project", instance_id="my_instance",
... credentials=credentials)
{
"status": "SUCCESS",
"results": {
"instance_id": "my_instance",
"display_name": "My Instance",
"config": "projects/my_project/instanceConfigs/regional-us-central1",
"node_count": 1,
"processing_units": 1000,
"labels": {"env": "prod"}
}
}
"""
try:
instance_admin_api = InstanceAdminAsyncClient(credentials=credentials)
instance_path = instance_admin_api.instance_path(project_id, instance_id)
instance = await instance_admin_api.get_instance(name=instance_path)
return {
"status": "SUCCESS",
"results": {
"instance_id": instance_id,
"display_name": instance.display_name,
"config": instance.config,
"node_count": instance.node_count,
"processing_units": instance.processing_units,
"labels": dict(instance.labels),
},
}
except Exception as ex:
return {
"status": "ERROR",
"error_details": repr(ex),
}
async def list_instance_configs(
project_id: str,
credentials: Credentials,
) -> dict[str, Any]:
"""List Spanner instance configs available for a project.
Args:
project_id: The Google Cloud project id.
credentials: The credentials to use for the request.
Returns:
dict: Dictionary with a list of Spanner instance config IDs.
Examples:
>>> await list_instance_configs("my_project", credentials)
{
"status": "SUCCESS",
"results": [
"regional-us-central1",
"nam3"
]
}
"""
try:
instance_admin_api = InstanceAdminAsyncClient(credentials=credentials)
configs = await instance_admin_api.list_instance_configs(
parent=instance_admin_api.common_project_path(project_id)
)
config_ids = [config.name.split("/")[-1] async for config in configs]
return {"status": "SUCCESS", "results": config_ids}
except Exception as ex:
return {
"status": "ERROR",
"error_details": repr(ex),
}
async def get_instance_config(
project_id: str,
*,
config_id: str,
credentials: Credentials,
) -> dict[str, Any]:
"""Get details of a Spanner instance config.
Args:
project_id: The Google Cloud project id.
config_id: The Spanner instance config id.
credentials: The credentials to use for the request.
Returns:
dict: Dictionary with the status and the Spanner instance config details.
Examples:
>>> await get_instance_config(project_id="my_project",
... config_id="regional-us-central1", credentials=credentials)
{
"status": "SUCCESS",
"results": {
"name": "projects/my_project/instanceConfigs/regional-us-central1",
"display_name": "us-central1",
"replicas": [
{'location': 'us-central1', 'type': 'READ_WRITE',
'default_leader_location': True}
],
"labels": {},
}
}
"""
try:
instance_admin_api = InstanceAdminAsyncClient(credentials=credentials)
config_name = instance_admin_api.instance_config_path(project_id, config_id)
config = await instance_admin_api.get_instance_config(name=config_name)
replicas = [
{
"location": r.location,
"type": spanner_admin_instance_v1.types.ReplicaInfo.ReplicaType(
r.type
).name,
"default_leader_location": r.default_leader_location,
}
for r in config.replicas
]
return {
"status": "SUCCESS",
"results": {
"name": config.name,
"display_name": config.display_name,
"replicas": replicas,
"labels": dict(config.labels),
},
}
except Exception as ex:
return {
"status": "ERROR",
"error_details": repr(ex),
}
async def create_instance(
project_id: str,
*,
instance_id: str,
config_id: str,
display_name: str,
credentials: Credentials,
nodes: int = 1,
) -> dict[str, Any]:
"""Create a Spanner instance.
Args:
project_id: The Google Cloud project id.
instance_id: The Spanner instance id to create.
config_id: The instance config id, e.g. regional-us-central1.
display_name: The display name for the instance.
credentials: The credentials to use for the request.
nodes: Number of nodes for the instance. Defaults to 1.
Returns:
dict: Dictionary with the status and result of instance creation.
Examples:
>>> await create_instance(project_id="my_project",
instance_id="my_instance",
... config_id="regional-us-central1", display_name="My Instance",
credentials=credentials)
{
"status": "SUCCESS",
"results": "Instance my_instance created successfully."
}
"""
try:
instance_admin_api = InstanceAdminAsyncClient(credentials=credentials)
instance_config = instance_admin_api.instance_config_path(
project_id, config_id
)
instance = spanner_admin_instance_v1.types.Instance(
display_name=display_name,
config=instance_config,
node_count=nodes,
)
operation = await instance_admin_api.create_instance(
parent=instance_admin_api.common_project_path(project_id),
instance_id=instance_id,
instance=instance,
)
await operation.result(timeout=300) # waits for completion
return {
"status": "SUCCESS",
"results": f"Instance {instance_id} created successfully.",
}
except Exception as ex:
return {
"status": "ERROR",
"error_details": repr(ex),
}
async def list_databases(
project_id: str,
*,
instance_id: str,
credentials: Credentials,
) -> dict[str, Any]:
"""List Spanner databases within an instance.
Args:
project_id: The Google Cloud project id.
instance_id: The Spanner instance id.
credentials: The credentials to use for the request.
Returns:
dict: Dictionary with the status and a list of the Spanner database IDs.
Examples:
>>> await list_databases(project_id="my_project",
... instance_id="my_instance", credentials=credentials)
{
"status": "SUCCESS",
"results": [
"database_1",
"database_2"
]
}
"""
try:
database_admin_api = DatabaseAdminAsyncClient(credentials=credentials)
databases = await database_admin_api.list_databases(
parent=database_admin_api.instance_path(project_id, instance_id)
)
database_ids = [
database.name.split("/")[-1] async for database in databases
]
return {"status": "SUCCESS", "results": database_ids}
except Exception as ex:
return {
"status": "ERROR",
"error_details": repr(ex),
}
async def create_database(
project_id: str,
*,
instance_id: str,
database_id: str,
credentials: Credentials,
) -> dict[str, Any]:
"""Create a Spanner database.
Args:
project_id: The Google Cloud project id.
instance_id: The Spanner instance id.
database_id: The Spanner database id.
credentials: The credentials to use for the request.
Returns:
dict: Dictionary with result of database creation.
Examples:
>>> await create_database(project_id="my_project",
instance_id="my_instance",
... database_id="my_database", credentials=credentials)
{
"status": "SUCCESS",
}
"""
try:
database_admin_api = DatabaseAdminAsyncClient(credentials=credentials)
operation = await database_admin_api.create_database(
parent=database_admin_api.instance_path(project_id, instance_id),
create_statement=f"CREATE DATABASE `{database_id}`",
)
# Wait for the operation to complete (default timeout 5 minutes).
# Result on success is
# google.cloud.spanner_admin_database_v1.types.Database
await operation.result(timeout=300)
return {
"status": "SUCCESS",
}
except Exception as ex:
return {
"status": "ERROR",
"error_details": repr(ex),
}