betodealmeida commented on code in PR #32231: URL: https://github.com/apache/superset/pull/32231#discussion_r1959966347
########## superset/commands/database/sync_permissions.py: ########## @@ -0,0 +1,313 @@ +# 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 Iterable + +from superset import app, security_manager +from superset.commands.base import BaseCommand +from superset.commands.database.exceptions import ( + DatabaseConnectionFailedError, + DatabaseConnectionSyncPermissionsError, + DatabaseNotFoundError, + UserNotFoundInSessionError, +) +from superset.commands.database.utils import ping +from superset.daos.database import DatabaseDAO +from superset.daos.dataset import DatasetDAO +from superset.databases.ssh_tunnel.models import SSHTunnel +from superset.db_engine_specs.base import GenericDBException +from superset.exceptions import OAuth2RedirectError +from superset.models.core import Database +from superset.tasks.permissions import sync_database_permissions +from superset.utils.decorators import on_error, transaction + +logger = logging.getLogger(__name__) + + +class SyncPermissionsCommand(BaseCommand): + """ + Command to sync database permissions. + """ + + def __init__( + self, + model_id: int, + username: str | None = None, + old_db_connection_name: str | None = None, + db_connection: Database | None = None, + ssh_tunnel: SSHTunnel | None = None, + ): + """ + Constructor method. + """ + self.username = username + self.db_connection_id = model_id + self._old_db_connection_name: str | None = old_db_connection_name + self._db_connection: Database | None = db_connection + self.db_connection_ssh_tunnel: SSHTunnel | None = ssh_tunnel + + self.async_mode: bool = app.config["SYNC_DB_PERMISSIONS_IN_ASYNC_MODE"] + + @property + def db_connection(self) -> Database: + if not self._db_connection: + raise DatabaseNotFoundError() + return self._db_connection + + @property + def old_db_connection_name(self) -> str: + return ( + self._old_db_connection_name + if self._old_db_connection_name is not None + else self.db_connection.database_name + ) + + def validate(self) -> None: + self._db_connection = ( + self._db_connection + if self._db_connection + else DatabaseDAO.find_by_id(self.db_connection_id) + ) + if not self._db_connection: + raise DatabaseNotFoundError() + + if not self.db_connection_ssh_tunnel: + self.db_connection_ssh_tunnel = DatabaseDAO.get_ssh_tunnel( + self.db_connection_id + ) + + # For async mode we'll need to pass the user to the Celery task in case of + # OAuth connections. + if self.async_mode: + if ( + not self.username + or not security_manager.get_user_by_username(self.username) + # The perm is already validated at the API layer, but checking here + # as well since Celery would also call this Command. + or not security_manager.can_access("can_write", "Database") + ): + raise UserNotFoundInSessionError() + + with self.db_connection.get_sqla_engine() as engine: + try: + alive = ping(engine) + except Exception as err: + raise DatabaseConnectionFailedError() from err + + if not alive: + raise DatabaseConnectionFailedError() + + def _run(self) -> None: + """ + Triggers the perm sync in sync or async mode. + """ + self.validate() + if self.async_mode: + self.trigger_task() + else: + self.sync_permissions() + + @transaction( + on_error=partial(on_error, reraise=DatabaseConnectionSyncPermissionsError) + ) + def run(self) -> None: + """ + Run the SyncPermissionsCommand for a DB connection. + """ + self._run() + + def run_nested_transaction(self) -> None: + """ + Run the SyncPermissionsCommand in a nested transaction. + + The process is the same, but it's part of the caller's transaction block. This + ensures that a perm sync triggered as part of the DatabaseUpdateCommand happens + as a single transaction, for example. An error to sync perms would bubble up to + the caller's command and return an error response. + """ + self._run() + + def trigger_task(self) -> None: + """ + Delegates the permission sync to a Celery task. + """ + sync_database_permissions.delay( + self.db_connection_id, + self.username, + self.old_db_connection_name, + ) Review Comment: I'm a bit confused by this. This calls the `sync_database_permissions` task, and the task then calls `SyncPermissionsCommand`. I'm assuming this doesn't get stuck in an infinite loop, but I can't understand why it doesn't happen — does Celery detect it's already running a task? Is the `SYNC_DB_PERMISSIONS_IN_ASYNC_MODE` flag not present for the Celery worker? Even if it works, it would be better to be more explicit, maybe passing an argument to `SyncPermissionsCommand` to force it in sync mode (when it's being called by the celery task). Also, you can make the task synchronous by calling `sync_database_permissions.get()`, this would eliminate even more duplicate logic: ```python def _run(self) -> None: """ Triggers the perm sync in sync or async mode. """ self.validate() args = [self.db_connection_id, self.username, self.old_db_connection_name] if self.async_mode: sync_database_permissions.delay(*args) else: sync_database_permissions.get(*args) ``` ########## superset/commands/database/sync_permissions.py: ########## @@ -0,0 +1,313 @@ +# 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 Iterable + +from superset import app, security_manager +from superset.commands.base import BaseCommand +from superset.commands.database.exceptions import ( + DatabaseConnectionFailedError, + DatabaseConnectionSyncPermissionsError, + DatabaseNotFoundError, + UserNotFoundInSessionError, +) +from superset.commands.database.utils import ping +from superset.daos.database import DatabaseDAO +from superset.daos.dataset import DatasetDAO +from superset.databases.ssh_tunnel.models import SSHTunnel +from superset.db_engine_specs.base import GenericDBException +from superset.exceptions import OAuth2RedirectError +from superset.models.core import Database +from superset.tasks.permissions import sync_database_permissions +from superset.utils.decorators import on_error, transaction + +logger = logging.getLogger(__name__) + + +class SyncPermissionsCommand(BaseCommand): + """ + Command to sync database permissions. + """ + + def __init__( + self, + model_id: int, + username: str | None = None, + old_db_connection_name: str | None = None, + db_connection: Database | None = None, + ssh_tunnel: SSHTunnel | None = None, + ): + """ + Constructor method. + """ + self.username = username + self.db_connection_id = model_id + self._old_db_connection_name: str | None = old_db_connection_name + self._db_connection: Database | None = db_connection + self.db_connection_ssh_tunnel: SSHTunnel | None = ssh_tunnel + + self.async_mode: bool = app.config["SYNC_DB_PERMISSIONS_IN_ASYNC_MODE"] + + @property + def db_connection(self) -> Database: + if not self._db_connection: + raise DatabaseNotFoundError() + return self._db_connection + + @property + def old_db_connection_name(self) -> str: + return ( + self._old_db_connection_name + if self._old_db_connection_name is not None + else self.db_connection.database_name + ) + + def validate(self) -> None: + self._db_connection = ( + self._db_connection + if self._db_connection + else DatabaseDAO.find_by_id(self.db_connection_id) + ) + if not self._db_connection: + raise DatabaseNotFoundError() + + if not self.db_connection_ssh_tunnel: + self.db_connection_ssh_tunnel = DatabaseDAO.get_ssh_tunnel( + self.db_connection_id + ) + + # For async mode we'll need to pass the user to the Celery task in case of + # OAuth connections. + if self.async_mode: + if ( + not self.username + or not security_manager.get_user_by_username(self.username) + # The perm is already validated at the API layer, but checking here + # as well since Celery would also call this Command. + or not security_manager.can_access("can_write", "Database") + ): + raise UserNotFoundInSessionError() + + with self.db_connection.get_sqla_engine() as engine: + try: + alive = ping(engine) + except Exception as err: + raise DatabaseConnectionFailedError() from err + + if not alive: + raise DatabaseConnectionFailedError() + + def _run(self) -> None: + """ + Triggers the perm sync in sync or async mode. + """ + self.validate() + if self.async_mode: + self.trigger_task() + else: + self.sync_permissions() + + @transaction( + on_error=partial(on_error, reraise=DatabaseConnectionSyncPermissionsError) + ) + def run(self) -> None: + """ + Run the SyncPermissionsCommand for a DB connection. + """ + self._run() + + def run_nested_transaction(self) -> None: + """ + Run the SyncPermissionsCommand in a nested transaction. Review Comment: Technically this doesn't run inside a nested transaction — a transaction within a transaction — does it? It's actually the opposite, you call `run_nested_transaction` instead of `run` because you don't want a nested transaction; the transaction from `run` inside the transaction from `UpdateDatabaseCommand.run`. If I understood it correctly it would be better to call this `run_without_transaction`. ########## superset/commands/database/sync_permissions.py: ########## @@ -0,0 +1,313 @@ +# 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 Iterable + +from superset import app, security_manager +from superset.commands.base import BaseCommand +from superset.commands.database.exceptions import ( + DatabaseConnectionFailedError, + DatabaseConnectionSyncPermissionsError, + DatabaseNotFoundError, + UserNotFoundInSessionError, +) +from superset.commands.database.utils import ping +from superset.daos.database import DatabaseDAO +from superset.daos.dataset import DatasetDAO +from superset.databases.ssh_tunnel.models import SSHTunnel +from superset.db_engine_specs.base import GenericDBException +from superset.exceptions import OAuth2RedirectError +from superset.models.core import Database +from superset.tasks.permissions import sync_database_permissions +from superset.utils.decorators import on_error, transaction + +logger = logging.getLogger(__name__) + + +class SyncPermissionsCommand(BaseCommand): + """ + Command to sync database permissions. + """ + + def __init__( + self, + model_id: int, + username: str | None = None, + old_db_connection_name: str | None = None, + db_connection: Database | None = None, + ssh_tunnel: SSHTunnel | None = None, + ): + """ + Constructor method. + """ + self.username = username + self.db_connection_id = model_id + self._old_db_connection_name: str | None = old_db_connection_name + self._db_connection: Database | None = db_connection + self.db_connection_ssh_tunnel: SSHTunnel | None = ssh_tunnel + + self.async_mode: bool = app.config["SYNC_DB_PERMISSIONS_IN_ASYNC_MODE"] + + @property + def db_connection(self) -> Database: + if not self._db_connection: + raise DatabaseNotFoundError() + return self._db_connection + + @property + def old_db_connection_name(self) -> str: + return ( + self._old_db_connection_name + if self._old_db_connection_name is not None + else self.db_connection.database_name + ) + + def validate(self) -> None: + self._db_connection = ( + self._db_connection + if self._db_connection + else DatabaseDAO.find_by_id(self.db_connection_id) + ) + if not self._db_connection: + raise DatabaseNotFoundError() + + if not self.db_connection_ssh_tunnel: + self.db_connection_ssh_tunnel = DatabaseDAO.get_ssh_tunnel( + self.db_connection_id + ) + + # For async mode we'll need to pass the user to the Celery task in case of + # OAuth connections. + if self.async_mode: + if ( + not self.username + or not security_manager.get_user_by_username(self.username) + # The perm is already validated at the API layer, but checking here + # as well since Celery would also call this Command. + or not security_manager.can_access("can_write", "Database") + ): + raise UserNotFoundInSessionError() + + with self.db_connection.get_sqla_engine() as engine: + try: + alive = ping(engine) + except Exception as err: + raise DatabaseConnectionFailedError() from err + + if not alive: + raise DatabaseConnectionFailedError() + + def _run(self) -> None: + """ + Triggers the perm sync in sync or async mode. + """ + self.validate() + if self.async_mode: + self.trigger_task() + else: + self.sync_permissions() + + @transaction( + on_error=partial(on_error, reraise=DatabaseConnectionSyncPermissionsError) + ) + def run(self) -> None: + """ + Run the SyncPermissionsCommand for a DB connection. + """ + self._run() + + def run_nested_transaction(self) -> None: + """ + Run the SyncPermissionsCommand in a nested transaction. Review Comment: You can also do: ```python class SyncPermissionsCommand(BaseCommand): ... # (Explanation of why we need to have these two different methods goes here) run = transaction( on_error=partial( on_error, reraise=DatabaseConnectionSyncPermissionsError, ) )(_run) run_without_transaction = _run ``` -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: notifications-unsubscr...@superset.apache.org For queries about this service, please contact Infrastructure at: us...@infra.apache.org --------------------------------------------------------------------- To unsubscribe, e-mail: notifications-unsubscr...@superset.apache.org For additional commands, e-mail: notifications-h...@superset.apache.org