Skip to content
Closed
6 changes: 5 additions & 1 deletion .github/workflows/scripts/script.sh
Comment thread
YasenT marked this conversation as resolved.
Resolved
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,11 @@ cmd_user_prefix bash -c "django-admin makemigrations file --check --dry-run"
cmd_user_prefix bash -c "django-admin makemigrations certguard --check --dry-run"

# Run unit tests.
cmd_user_prefix bash -c "PULP_DATABASES__default__USER=postgres pytest -v -r sx --color=yes --suppress-no-test-exit-code -p no:pulpcore --durations=20 --pyargs pulpcore.tests.unit"
# data_1 is a second database on the same local postgres server used by "default" -- Django's
# test runner creates/tears down its own "test_..." database for it, so multi-db unit tests
# run as part of the normal suite without a dedicated satellite service/CI job.
MULTI_DB_ENV="PULP_DATABASES__data_1__ENGINE=django.db.backends.postgresql PULP_DATABASES__data_1__NAME=pulp_data_1 PULP_DATABASES__data_1__USER=postgres PULP_DATABASE_ROUTERS='[\"pulpcore.app.db_router.PulpDomainRouter\"]'"
cmd_user_prefix bash -c "PULP_DATABASES__default__USER=postgres $MULTI_DB_ENV pytest -v -r sx --color=yes --suppress-no-test-exit-code -p no:pulpcore --durations=20 --pyargs pulpcore.tests.unit"
cmd_user_prefix bash -c "PULP_DATABASES__default__USER=postgres pytest -v -r sx --color=yes --suppress-no-test-exit-code -p no:pulpcore --durations=20 --pyargs pulp_file.tests.unit"
cmd_user_prefix bash -c "PULP_DATABASES__default__USER=postgres pytest -v -r sx --color=yes --suppress-no-test-exit-code -p no:pulpcore --durations=20 --pyargs pulp_certguard.tests.unit"
# Run functional tests
Expand Down
1 change: 1 addition & 0 deletions CHANGES/+multi-database-routing.feature
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Added optional multi-database routing, letting a domain's data-plane content live in a separate database (a "satellite") from the control plane, with database-local roles and grants.
1 change: 1 addition & 0 deletions CHANGES/plugin_api/+multi-db-compatible.feature
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Added the `multi_db_compatible` attribute to `PulpPluginAppConfig`. Plugins must set it to `True` to be loaded while `PulpDomainRouter` is configured in `DATABASE_ROUTERS`; otherwise Pulp refuses to start.
24 changes: 23 additions & 1 deletion docs/user/guides/create-domains.md
Original file line number Diff line number Diff line change
Expand Up @@ -136,11 +136,33 @@ pulp user role-assignment add --username <username> --role <role_name> --domain
e.g. You can not add content from one domain to the repository of another domain even if you own both domains.


There are notable objects in Pulp like `Roles`, `Users`, and `Groups`, that are not a part of domains and remain global across the system.
With the default single-database configuration, `Roles`, `Users`, and `Groups` are not part of domains and remain global across the system.
These objects are closely intertwined with the RBAC system and currently do not make sense to be unique on the domain level.
Objects that are not a part of a domain are readable from any domain (with the correct permissions),
but are only operable on within the `default` domain, i.e. `Roles` can be read from any domain, but can only be created from the `default` domain.

## Separate databases

To route new domains to separate databases, configure `DATABASES` and explicitly enable
`pulpcore.app.db_router.PulpDomainRouter` in `DATABASE_ROUTERS`. Migrate `default` first, then
run `pulpcore-manager migrate --database <alias>` for each satellite database. All processes
must use the same database configuration and installed plugins.

Set `database_alias` when creating a Domain through the API. It defaults to `default` and
cannot be changed through the API after creation. Moving existing domains requires a separate
migration procedure.

Users, Groups, and group membership are managed centrally in `default`. When a role grant is
written to a satellite, a placeholder row with the same id is created there for the grant's user
or group; it carries no credentials. Deleting a User or Group removes its placeholders and the
grants on every satellite.

Roles, permissions, and role grants belong to each database. Built-in roles are initialized
during migration; custom roles must be created in each database that needs them. A model-level
(global) grant applies only within the database it was created in, including every domain that
shares that database. Django permissions assigned directly to users or groups, outside of roles,
are not supported for satellite domains.

[RBAC Overview]: site:pulpcore/docs/dev/learn/rbac/
[settings]: site:pulpcore/docs/admin/reference/settings/
[Storage]: site:pulpcore/docs/admin/guides/configure-pulp/configure-storages/
1 change: 1 addition & 0 deletions pulp_certguard/app/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,4 @@ class PulpCertGuardPluginAppConfig(PulpPluginAppConfig):
version = "3.124.0.dev"
python_package_name = "pulpcore"
domain_compatible = True
multi_db_compatible = True
1 change: 1 addition & 0 deletions pulp_file/app/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,4 @@ class PulpFilePluginAppConfig(PulpPluginAppConfig):
version = "3.124.0.dev"
python_package_name = "pulpcore"
domain_compatible = True
multi_db_compatible = True
116 changes: 105 additions & 11 deletions pulpcore/app/apps.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import logging
import random
from collections import defaultdict
from contextlib import suppress
Expand All @@ -7,8 +8,8 @@
from django import apps
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.db import ProgrammingError, connection, transaction
from django.db.models.signals import post_migrate, pre_migrate
from django.db import ProgrammingError, connection, connections, transaction
from django.db.models.signals import post_delete, post_migrate, post_save, pre_migrate, pre_save
from django.utils.module_loading import module_has_submodule

from pulpcore.exceptions.plugin import MissingPlugin
Expand Down Expand Up @@ -94,6 +95,14 @@ def __init__(self, app_name, app_module):
"plugin or turn off `DOMAIN_ENABLED` for Pulp to start."
)
raise ImproperlyConfigured(msg.format(self.python_package_name, self.version))
if "pulpcore.app.db_router.PulpDomainRouter" in settings.DATABASE_ROUTERS:
if not getattr(self, "multi_db_compatible", None):
msg = (
"The plugin `{}-{}` is not multi-database compatible. Please uninstall/update "
"the plugin or remove `PulpDomainRouter` from `DATABASE_ROUTERS` for Pulp to "
"start."
)
raise ImproperlyConfigured(msg.format(self.python_package_name, self.version))
# Module containing viewsets eg. <module 'pulp_plugin.app.viewsets'
# from 'pulp_plugin/app/viewsets.py'>. Set by import_viewsets().
# None if the application doesn't have a viewsets module, automatically set
Expand Down Expand Up @@ -244,6 +253,7 @@ class PulpAppConfig(PulpPluginAppConfig):
python_package_name = "pulpcore"

domain_compatible = True
multi_db_compatible = True

def ready(self):
super().ready()
Expand All @@ -253,6 +263,16 @@ def ready(self):
post_migrate.connect(
_ensure_default_domain, sender=self, dispatch_uid="ensure_default_domain"
)

# Connect this before _populate_system_id/_populate_artifact_serving_distribution below:
# post_migrate receivers fire in connection order, and those two create rows whose
# pulp_domain FK defaults to the 'default' alias's Domain row, which doesn't exist yet on
# a freshly-migrated satellite until _ensure_domains_replicated backfills it there.
from pulpcore.app.db_router import is_multi_db_routing_active

if is_multi_db_routing_active():
self._connect_multi_db_signals()

post_migrate.connect(
_populate_system_id, sender=self, dispatch_uid="populate_system_id_identifier"
)
Expand All @@ -262,8 +282,49 @@ def ready(self):
dispatch_uid="populate_artifact_serving_distribution_identifier",
)

def _connect_multi_db_signals(self):
"""Connect replication for Domains and stub Users/Groups."""
post_migrate.connect(
_ensure_domains_replicated,
sender=self,
dispatch_uid="ensure_domains_replicated_identifier",
)
Comment on lines +287 to +291

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For all of these post_migrate and post_save hooks let's group them all into a separate function that is only called if the DBRouter is selected.


# Must stay a local import, not module-level: this module is reachable from
# pulpcore.plugin.__init__ before Django settings/dynaconf have initialized (e.g. via
# pytest's pytest11 entry-point loading), and django.contrib.auth caches a reference to
# whatever settings object exists at its own import time -- a module-level import here
# would permanently wire it to a stale pre-dynaconf settings object.
from django.contrib.auth import get_user_model

from pulpcore.app.domain_sync import on_domain_post_delete, on_domain_post_save
from pulpcore.app.models import Domain, Group
from pulpcore.app.models.role import GroupRole, UserRole
from pulpcore.app.rbac_sync import (
on_group_post_delete,
on_group_role_pre_save,
on_user_post_delete,
on_user_role_pre_save,
)

post_save.connect(
on_domain_post_save, sender=Domain, dispatch_uid="replicate_domain_post_save"
)
post_delete.connect(
on_domain_post_delete, sender=Domain, dispatch_uid="replicate_domain_post_delete"
)

pre_save.connect(on_user_role_pre_save, sender=UserRole, dispatch_uid="user_role_stub")
pre_save.connect(on_group_role_pre_save, sender=GroupRole, dispatch_uid="group_role_stub")
post_delete.connect(
on_user_post_delete, sender=get_user_model(), dispatch_uid="remove_user_stubs"
)
post_delete.connect(on_group_post_delete, sender=Group, dispatch_uid="remove_group_stubs")


def _clean_app_status(sender, apps, verbosity, **kwargs):
if kwargs.get("using", "default") != "default":
return
from django.contrib.postgres.functions import TransactionNow
from django.db.models import F

Expand All @@ -277,6 +338,9 @@ def _clean_app_status(sender, apps, verbosity, **kwargs):


def _populate_access_policies(sender, apps, verbosity, **kwargs):
if kwargs.get("using", "default") != "default":
return

from pulpcore.app.util import get_view_urlpattern
from pulpcore.app.viewsets import LoginViewSet

Expand Down Expand Up @@ -321,13 +385,17 @@ def _populate_access_policies(sender, apps, verbosity, **kwargs):


def _populate_system_id(sender, apps, verbosity, **kwargs):
if kwargs.get("using", "default") != "default":
return
with suppress(LookupError):
SystemID = apps.get_model("core", "SystemID")
if not SystemID.objects.exists():
SystemID().save()


def _ensure_default_domain(sender, apps, **kwargs):
if kwargs.get("using", "default") != "default":
return
# This is a post migrate hook.
# But on rolling back the database may not match what this function expects.
with suppress(LookupError, ProgrammingError):
Expand All @@ -348,7 +416,28 @@ def _ensure_default_domain(sender, apps, **kwargs):
default.save(skip_hooks=True)


def _ensure_domains_replicated(sender, **kwargs):
using = kwargs.get("using", "default")
if using == "default":
return
if "core_domain" not in connections[using].introspection.table_names():
return
from pulpcore.app.domain_sync import reconcile_domains_to_alias

try:
reconcile_domains_to_alias(using)
except Exception:
logging.getLogger(__name__).error(
"Reconciling Domain rows to alias '%s' failed during migration. Data-plane objects "
"created on this alias by later migrations/post_migrate hooks that FK to Domain may "
"fail until Domain rows are reconciled to this alias.",
using,
exc_info=True,
)


def _populate_roles(sender, apps, verbosity, **kwargs):
alias = kwargs.get("using", "default")
role_prefix = f"{sender.label}."
# collect all plugin defined roles
desired_roles = {}
Expand All @@ -357,10 +446,10 @@ def _populate_roles(sender, apps, verbosity, **kwargs):
locked_roles = getattr(viewset, "LOCKED_ROLES", None)
if locked_roles is not None:
desired_roles.update(locked_roles or {})
adjust_roles(apps, role_prefix, desired_roles, verbosity)
adjust_roles(apps, role_prefix, desired_roles, verbosity, using=alias)


def adjust_roles(apps, role_prefix, desired_roles, verbosity=1):
def adjust_roles(apps, role_prefix, desired_roles, verbosity=1, using="default"):
"""
Adjust all roles with a given prefix.

Expand All @@ -382,10 +471,12 @@ def adjust_roles(apps, role_prefix, desired_roles, verbosity=1):

def _get_permission(perm):
app_label, codename = perm.split(".", maxsplit=2)
return Permission.objects.get(content_type__app_label=app_label, codename=codename)
return Permission.objects.using(using).get(
content_type__app_label=app_label, codename=codename
)

# Remove obsolete roles
Role.objects.filter(name__startswith=role_prefix, locked=True).exclude(
Role.objects.using(using).filter(name__startswith=role_prefix, locked=True).exclude(
name__in=desired_roles.keys()
).delete()
# Create / update desired roles
Expand All @@ -401,13 +492,14 @@ def _get_permission(perm):
_("Locked role definition for {name} is incompatible.").format(name=name)
)
permissions = [_get_permission(perm) for perm in permissions]
role, created = Role.objects.update_or_create(
role, created = Role.objects.using(using).update_or_create(
name=name, defaults={"name": name, "locked": True, "description": description}
)
role.permissions.set(permissions)


def _populate_artifact_serving_distribution(sender, apps, verbosity, **kwargs):
alias = kwargs.get("using", "default")
if (
settings.STORAGES["default"]["BACKEND"] == "pulpcore.app.models.storage.FileSystem"
or not settings.REDIRECT_TO_OBJECT_STORAGE
Expand All @@ -420,15 +512,17 @@ def _populate_artifact_serving_distribution(sender, apps, verbosity, **kwargs):
print(_("ArtifactDistribution model does not exist. Skipping initialization."))
return
try:
ArtifactDistribution.objects.get()
ArtifactDistribution.objects.using(alias).get()
except ArtifactDistribution.DoesNotExist:
name = f"{random.getrandbits(256):x}"
with transaction.atomic():
content_guard, _created = ContentRedirectContentGuard.objects.get_or_create(
with transaction.atomic(using=alias):
content_guard, _created = ContentRedirectContentGuard.objects.using(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This would fail without a default domain in the other DB.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it's already covered.
_ensure_domains_replicated runs right before this hook in ready()
reconcile_domains_to_alias() always includes default in its desired set regardless of which alias it's reconciling
So by the time this runs, defaults row is already there?

alias
).get_or_create(
name=name,
pulp_type="core.content_redirect",
)
_dist, _created = ArtifactDistribution.objects.get_or_create(
_dist, _created = ArtifactDistribution.objects.using(alias).get_or_create(
name=name,
pulp_type="core.artifact",
defaults={"base_path": name, "content_guard": content_guard},
Expand Down
Loading
Loading