diff --git a/src/backend/InvenTree/machine/registry.py b/src/backend/InvenTree/machine/registry.py index e1b3a78dec..967da92747 100644 --- a/src/backend/InvenTree/machine/registry.py +++ b/src/backend/InvenTree/machine/registry.py @@ -113,6 +113,10 @@ class MachineRegistry( # Keep an internal hash of the machine registry state self._hash = None + # The plugin registry 'reload_count' which the machine types and drivers + # were discovered against (None = unknown / stale, reload required) + self._plugin_registry_generation: Optional[int] = None + @property def errors(self) -> list[str | Exception]: """List of registry errors.""" @@ -274,6 +278,8 @@ class MachineRegistry( def reload_machines(self, main: bool = False): """Reload all machines from the database.""" + from plugin import registry as plg_registry + self.drivers = {} self.driver_instances = {} self.machines = {} @@ -282,8 +288,30 @@ class MachineRegistry( self.set_shared_state('errors', []) + # Machine types and drivers are discovered from the plugin registry. + # If the plugin registry is (re)loading in another thread, it may be + # empty or only partially populated - so record which plugin registry + # generation we discovered against, and check it again afterwards. + generation = plg_registry.reload_count + loading = plg_registry.is_loading + self.discover_machine_types() self.discover_drivers() + + if ( + loading + or plg_registry.is_loading + or plg_registry.reload_count != generation + ): + # Discovery may have seen an incomplete set of plugins. + # Mark as stale, so the registry is reloaded on next access. + logger.info( + 'Plugin registry changed during machine discovery - marking machine registry as stale' + ) + self._plugin_registry_generation = None + else: + self._plugin_registry_generation = generation + self.load_machines(main=main) @machine_registry_entrypoint() @@ -422,8 +450,12 @@ class MachineRegistry( data = md5() - # If the plugin registry has changed, the machine registry hash will change - plugin_registry.update_plugin_hash() + # If the plugin registry has changed, the machine registry hash will change. + # Do not publish the plugin hash while the plugin registry is mid-reload, + # as it would reflect a partially loaded set of plugins. + if not plugin_registry.is_loading: + plugin_registry.update_plugin_hash() + current_hash = plugin_registry.registry_hash if current_hash: data.update(current_hash.encode()) @@ -448,6 +480,14 @@ class MachineRegistry( if plugin_registry_hash != plg_registry.registry_hash: do_reload = True + # Also reload if the plugin registry has been reloaded since machine discovery, + # or if the previous discovery may have seen a partially loaded registry + if ( + self._plugin_registry_generation is None + or self._plugin_registry_generation != plg_registry.reload_count + ): + do_reload = True + if not self._hash: self._hash = self._calculate_registry_hash() diff --git a/src/backend/InvenTree/machine/tests.py b/src/backend/InvenTree/machine/tests.py index ed2556e699..ecc1a3f397 100755 --- a/src/backend/InvenTree/machine/tests.py +++ b/src/backend/InvenTree/machine/tests.py @@ -1,6 +1,7 @@ """Machine app tests.""" from typing import cast +from unittest.mock import patch from django.apps import apps from django.test import TestCase @@ -190,6 +191,43 @@ class TestLabelPrinterMachineType(InvenTreeAPITestCase): else: self.assertIsNone(machine) + def test_discovery_during_plugin_reload(self): + """Machine discovery which overlaps a plugin registry reload is treated as stale. + + If the plugin registry is reloaded (e.g. in another thread) while machine + drivers are being discovered, the discovery may have seen an incomplete set of + plugins - so the machine registry must be reloaded again on next access. + """ + PLG_KEY = 'label-printer-test-plugin' + DRIVER_KEY = 'test-label-printer-api' + + plg_registry.set_plugin_state(PLG_KEY, True) + registry.reload_machines() + self.assertIsNotNone(registry.get_driver_instance(DRIVER_KEY)) + + # Simulate a plugin registry reload which starts during driver discovery, + # where the plugin registry is (temporarily) empty + original_discover = registry.discover_drivers + + def discover_during_reload(): + plg_registry.reload_count += 1 + with patch.object(plg_registry, 'with_mixin', return_value=[]): + original_discover() + + with patch.object(registry, 'discover_drivers', discover_during_reload): + registry.reload_machines() + + # Discovery found nothing, and has been marked as stale + self.assertEqual(registry.drivers, {}) + self.assertIsNone(registry._plugin_registry_generation) + + # The next access reloads the machine registry, and finds the driver again + self.assertTrue(registry._check_reload()) + self.assertIsNotNone(registry.get_driver_instance(DRIVER_KEY)) + self.assertEqual( + registry._plugin_registry_generation, plg_registry.reload_count + ) + def create_machine(self, driver_key): """Create a new label printing machine.""" registry.initialize(main=True) diff --git a/src/backend/InvenTree/plugin/_internal/registry.py b/src/backend/InvenTree/plugin/_internal/registry.py index 63d4bfe531..71087312aa 100644 --- a/src/backend/InvenTree/plugin/_internal/registry.py +++ b/src/backend/InvenTree/plugin/_internal/registry.py @@ -148,6 +148,11 @@ class PluginsRegistry: self._loading_thread: Optional[int] = None # Thread currently holding the lock self._reload_pending: bool = False # Reload requested while lock was held + # Incremented each time the registry is (re)loaded. + # Allows dependent registries (e.g. machines) to detect that the set of + # loaded plugins may have changed underneath them. + self.reload_count: int = 0 + # flags self.plugins_loaded = ( False # Marks if the registry fully loaded and all django apps are reloaded @@ -603,6 +608,9 @@ class PluginsRegistry: _internal: Optional[list], ) -> bool: """Perform the plugin registry reload - the caller must hold the loading lock.""" + # Mark the start of a new load cycle *before* any plugins are unloaded + self.reload_count += 1 + # Reset the loading error state if clear_errors: self.errors = {} diff --git a/src/backend/InvenTree/plugin/models.py b/src/backend/InvenTree/plugin/models.py index f97c78d738..ed7f21d361 100644 --- a/src/backend/InvenTree/plugin/models.py +++ b/src/backend/InvenTree/plugin/models.py @@ -7,7 +7,7 @@ from typing import Optional from django.conf import settings from django.contrib import admin from django.contrib.auth.models import User -from django.db import models +from django.db import models, transaction from django.urls import reverse from django.utils.translation import gettext_lazy as _ @@ -161,8 +161,17 @@ class PluginConfig(InvenTreeMetadataMixin, models.Model): return self.active != self.__org_active def save(self, force_insert=False, force_update=False, *args, **kwargs): - """Extend save method to reload plugins if the 'active' status changes.""" + """Extend save method to reload plugins if the 'active' status changes. + + Keyword Arguments: + force_insert: Force the insertion of a new record + force_update: Force the update of an existing record + no_reload: Do not reload the plugin registry, even if the 'active' status changed + reload_on_commit: Defer the plugin registry reload until the current + database transaction is committed (runs immediately if not in a transaction) + """ no_reload = kwargs.pop('no_reload', False) # check if no_reload flag is set + reload_on_commit = kwargs.pop('reload_on_commit', False) mandatory = self.is_mandatory() @@ -176,7 +185,16 @@ class PluginConfig(InvenTreeMetadataMixin, models.Model): if not no_reload and reload_required: self.warn_reload(stacklevel=3) - registry.reload_plugins(full_reload=True, force_reload=True, collect=True) + + def reload(): + registry.reload_plugins( + full_reload=True, force_reload=True, collect=True + ) + + if reload_on_commit: + transaction.on_commit(reload) + else: + reload() self.__org_active = self.active @@ -280,7 +298,13 @@ class PluginConfig(InvenTreeMetadataMixin, models.Model): return self.active = active - self.save() + + # The registry reload publishes the new plugin state to other threads and + # processes (via the registry hash), which then re-read PluginConfig from + # the database. If the reload ran inside an uncommitted transaction (e.g. the + # API update view), they would read the *old* 'active' value and cache an + # inconsistent view of the registry - so wait for the change to be committed. + self.save(reload_on_commit=True) trigger_event(PluginEvents.PLUGIN_ACTIVATED, slug=self.key, active=active) diff --git a/src/backend/InvenTree/plugin/test_plugin.py b/src/backend/InvenTree/plugin/test_plugin.py index b5972ecb0c..96708659e3 100644 --- a/src/backend/InvenTree/plugin/test_plugin.py +++ b/src/backend/InvenTree/plugin/test_plugin.py @@ -1300,6 +1300,37 @@ class RegistryTests(TestQueryMixin, PluginRegistryMixin, TestCase): self.assertFalse(cfg.is_package()) self.assertFalse(cfg.is_sample()) + def test_activate_reloads_on_commit(self): + """Activating a plugin within a transaction defers the registry reload until commit. + + Otherwise the reload publishes the new registry state to other threads / processes + before the new 'active' value is visible to them in the database. + """ + self.ensurePluginsLoaded() + + cfg = registry.get_plugin_config('sample') + self.assertIsNotNone(cfg) + + with patch.object(registry, 'reload_plugins') as reload_plugins: + initial = cfg.active + + # Toggle the plugin state, and then restore it + for state in [not initial, initial]: + with self.captureOnCommitCallbacks(execute=False) as callbacks: + cfg.activate(state) + + # Not reloaded yet - the transaction has not been committed + reload_plugins.assert_not_called() + + # Commit the transaction + for callback in callbacks: + callback() + + reload_plugins.assert_called_once_with( + full_reload=True, force_reload=True, collect=True + ) + reload_plugins.reset_mock() + class InstallerTests(TestCase): """Tests for the plugin installer code."""