-
Notifications
You must be signed in to change notification settings - Fork 14.1k
/
update.py
312 lines (274 loc) · 10.5 KB
/
update.py
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
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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
import logging
from functools import partial
from typing import Any
from flask_appbuilder.models.sqla import Model
from superset import is_feature_enabled, security_manager
from superset.commands.base import BaseCommand
from superset.commands.database.exceptions import (
DatabaseConnectionFailedError,
DatabaseExistsValidationError,
DatabaseInvalidError,
DatabaseNotFoundError,
DatabaseUpdateFailedError,
)
from superset.commands.database.ssh_tunnel.create import CreateSSHTunnelCommand
from superset.commands.database.ssh_tunnel.delete import DeleteSSHTunnelCommand
from superset.commands.database.ssh_tunnel.exceptions import (
SSHTunnelingNotEnabledError,
)
from superset.commands.database.ssh_tunnel.update import UpdateSSHTunnelCommand
from superset.daos.database import DatabaseDAO
from superset.daos.dataset import DatasetDAO
from superset.databases.ssh_tunnel.models import SSHTunnel
from superset.models.core import Database
from superset.utils.decorators import on_error, transaction
logger = logging.getLogger(__name__)
class UpdateDatabaseCommand(BaseCommand):
_model: Database | None
def __init__(self, model_id: int, data: dict[str, Any]):
self._properties = data.copy()
self._model_id = model_id
self._model: Database | None = None
@transaction(on_error=partial(on_error, reraise=DatabaseUpdateFailedError))
def run(self) -> Model:
self._model = DatabaseDAO.find_by_id(self._model_id)
if not self._model:
raise DatabaseNotFoundError()
self.validate()
# unmask ``encrypted_extra``
self._properties["encrypted_extra"] = (
self._model.db_engine_spec.unmask_encrypted_extra(
self._model.encrypted_extra,
self._properties.pop("masked_encrypted_extra", "{}"),
)
)
# if the database name changed we need to update any existing permissions,
# since they're name based
original_database_name = self._model.database_name
database = DatabaseDAO.update(self._model, self._properties)
database.set_sqlalchemy_uri(database.sqlalchemy_uri)
ssh_tunnel = self._handle_ssh_tunnel(database)
self._refresh_catalogs(database, original_database_name, ssh_tunnel)
return database
def _handle_ssh_tunnel(self, database: Database) -> SSHTunnel | None:
"""
Delete, create, or update an SSH tunnel.
"""
if "ssh_tunnel" not in self._properties:
return None
if not is_feature_enabled("SSH_TUNNELING"):
raise SSHTunnelingNotEnabledError()
current_ssh_tunnel = DatabaseDAO.get_ssh_tunnel(database.id)
ssh_tunnel_properties = self._properties["ssh_tunnel"]
if ssh_tunnel_properties is None:
if current_ssh_tunnel:
DeleteSSHTunnelCommand(current_ssh_tunnel.id).run()
return None
if current_ssh_tunnel is None:
return CreateSSHTunnelCommand(database, ssh_tunnel_properties).run()
return UpdateSSHTunnelCommand(
current_ssh_tunnel.id,
ssh_tunnel_properties,
).run()
def _get_catalog_names(
self,
database: Database,
ssh_tunnel: SSHTunnel | None,
) -> set[str]:
"""
Helper method to load catalogs.
This method captures a generic exception, since errors could potentially come
from any of the 50+ database drivers we support.
"""
try:
return database.get_all_catalog_names(
force=True,
ssh_tunnel=ssh_tunnel,
)
except Exception as ex:
raise DatabaseConnectionFailedError() from ex
def _get_schema_names(
self,
database: Database,
catalog: str | None,
ssh_tunnel: SSHTunnel | None,
) -> set[str]:
"""
Helper method to load schemas.
This method captures a generic exception, since errors could potentially come
from any of the 50+ database drivers we support.
"""
try:
return database.get_all_schema_names(
force=True,
catalog=catalog,
ssh_tunnel=ssh_tunnel,
)
except Exception as ex:
raise DatabaseConnectionFailedError() from ex
def _refresh_catalogs(
self,
database: Database,
original_database_name: str,
ssh_tunnel: SSHTunnel | None,
) -> None:
"""
Add permissions for any new catalogs and schemas.
"""
catalogs = (
self._get_catalog_names(database, ssh_tunnel)
if database.db_engine_spec.supports_catalog
else [None]
)
for catalog in catalogs:
try:
schemas = self._get_schema_names(database, catalog, ssh_tunnel)
if catalog:
perm = security_manager.get_catalog_perm(
original_database_name,
catalog,
)
existing_pvm = security_manager.find_permission_view_menu(
"catalog_access",
perm,
)
if not existing_pvm:
# new catalog
security_manager.add_permission_view_menu(
"catalog_access",
security_manager.get_catalog_perm(
database.database_name,
catalog,
),
)
for schema in schemas:
security_manager.add_permission_view_menu(
"schema_access",
security_manager.get_schema_perm(
database.database_name,
catalog,
schema,
),
)
continue
except DatabaseConnectionFailedError:
# more than one catalog, move to next
if catalog:
logger.warning("Error processing catalog %s", catalog)
continue
raise
# add possible new schemas in catalog
self._refresh_schemas(
database,
original_database_name,
catalog,
schemas,
)
if original_database_name != database.database_name:
self._rename_database_in_permissions(
database,
original_database_name,
catalog,
schemas,
)
def _refresh_schemas(
self,
database: Database,
original_database_name: str,
catalog: str | None,
schemas: set[str],
) -> None:
"""
Add new schemas that don't have permissions yet.
"""
for schema in schemas:
perm = security_manager.get_schema_perm(
original_database_name,
catalog,
schema,
)
existing_pvm = security_manager.find_permission_view_menu(
"schema_access",
perm,
)
if not existing_pvm:
new_name = security_manager.get_schema_perm(
database.database_name,
catalog,
schema,
)
security_manager.add_permission_view_menu("schema_access", new_name)
def _rename_database_in_permissions(
self,
database: Database,
original_database_name: str,
catalog: str | None,
schemas: set[str],
) -> None:
new_name = security_manager.get_catalog_perm(
database.database_name,
catalog,
)
# rename existing catalog permission
if catalog:
perm = security_manager.get_catalog_perm(
original_database_name,
catalog,
)
existing_pvm = security_manager.find_permission_view_menu(
"catalog_access",
perm,
)
if existing_pvm:
existing_pvm.view_menu.name = new_name
for schema in schemas:
new_name = security_manager.get_schema_perm(
database.database_name,
catalog,
schema,
)
# rename existing schema permission
perm = security_manager.get_schema_perm(
original_database_name,
catalog,
schema,
)
existing_pvm = security_manager.find_permission_view_menu(
"schema_access",
perm,
)
if existing_pvm:
existing_pvm.view_menu.name = new_name
# rename permissions on datasets and charts
for dataset in DatabaseDAO.get_datasets(
database.id,
catalog=catalog,
schema=schema,
):
dataset.schema_perm = new_name
for chart in DatasetDAO.get_related_objects(dataset.id)["charts"]:
chart.schema_perm = new_name
def validate(self) -> None:
if database_name := self._properties.get("database_name"):
if not DatabaseDAO.validate_update_uniqueness(
self._model_id,
database_name,
):
raise DatabaseInvalidError(exceptions=[DatabaseExistsValidationError()])