diff --git a/.github/scripts/check_exported_data.py b/.github/scripts/check_exported_data.py index 07e72308f9..f807ca4d8c 100644 --- a/.github/scripts/check_exported_data.py +++ b/.github/scripts/check_exported_data.py @@ -10,6 +10,12 @@ In reads the exported data file, to ensure that: - The file contains the expected plugin configuration - The file contains the expected plugin database records +When '--exclude-plugins' is passed, the inverse is checked instead: + +- The plugin app is *not* listed in the metadata installed_apps +- No plugin configuration / settings records (plugin.*) are present +- No plugin app database records are present + It can also optionally check the presence / absence of several categories of data which 'export-records' can include or exclude via --include-x / --exclude-x flags (email logs, API tokens, SSO app/token data, user sessions, @@ -151,8 +157,12 @@ if __name__ == '__main__': found_metadata = False found_installed_apps = False found_plugin_config = False + found_plugin_app = False plugin_data_records = {} + # Count of all records belonging to the 'plugin' app, or to the plugin's own app + plugin_model_counts: dict[str, int] = {} + # Inspect the data and check that it has the expected structure and content. for entry in data: # Check metadata entry for expected values @@ -160,7 +170,7 @@ if __name__ == '__main__': print('Found metadata entry') found_metadata = True - expected_apps = ['InvenTree', 'allauth', 'dbbackup', PLUGIN_KEY] + expected_apps = ['InvenTree', 'allauth', 'dbbackup', 'plugin'] apps = entry.get('installed_apps', []) @@ -170,8 +180,15 @@ if __name__ == '__main__': exit(1) found_installed_apps = True + found_plugin_app = PLUGIN_KEY in apps + continue - elif entry.get('model', None) == 'plugin.pluginconfig': + model = entry.get('model', None) or '' + + if model.startswith(('plugin.', f'{PLUGIN_KEY}.')): + plugin_model_counts[model] = plugin_model_counts.get(model, 0) + 1 + + if entry.get('model', None) == 'plugin.pluginconfig': key = entry['fields']['key'] if key == PLUGIN_SLUG: @@ -189,14 +206,18 @@ if __name__ == '__main__': exit(1) if not found_installed_apps: - print( - f'Error: Plugin "{PLUGIN_KEY}" not found in installed apps list in metadata' - ) + print('Error: No installed apps list found in metadata') exit(1) # Plugin data is included by default (export-records only excludes it when # given --exclude-plugins), so preserve that as the default expectation here if not args.exclude_plugins: + if not found_plugin_app: + print( + f'Error: Plugin app "{PLUGIN_KEY}" not found in installed apps list in metadata' + ) + exit(1) + if not found_plugin_config: print(f'Error: No plugin configuration found for plugin "{PLUGIN_KEY}"') exit(1) @@ -210,10 +231,19 @@ if __name__ == '__main__': f'Error: Expected plugin record with key "{key}" not found in exported data' ) exit(1) - elif found_plugin_config: - print('Error: Plugin data was found, but should have been excluded') - exit(1) else: + if found_plugin_app: + print( + f'Error: Plugin app "{PLUGIN_KEY}" found in installed apps list in metadata, but should have been excluded' + ) + exit(1) + + if plugin_model_counts: + print( + f'Error: Plugin data was found, but should have been excluded: {plugin_model_counts}' + ) + exit(1) + print('Confirmed plugin data was correctly excluded') # Content-excludes checks - only run for '--check-x' flags that were actually passed diff --git a/.github/scripts/check_imported_data.py b/.github/scripts/check_imported_data.py new file mode 100644 index 0000000000..5a87f6471c --- /dev/null +++ b/.github/scripts/check_imported_data.py @@ -0,0 +1,53 @@ +"""Script to check the database state after an 'import-records --exclude-plugins' run. + +This script is intended to be used as part of the CI workflow, +in conjunction with the "workflows/import_export.yaml" workflow +(see the 'exclude-plugins' job). + +It checks that: + +- Core data (e.g. Part records) was imported +- No plugin configuration was imported for the dummy plugin + +Intended to be run from 'src/backend/InvenTree', e.g.: + cd src/backend/InvenTree && python ../../../.github/scripts/check_imported_data.py +""" + +import os +import sys + +sys.path.insert(0, os.getcwd()) +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'InvenTree.settings') + +import django + +django.setup() + +from part.models import Part +from plugin.models import PluginConfig, PluginSetting + +PLUGIN_SLUG = 'dummy-app-plugin' + +if __name__ == '__main__': + part_count = Part.objects.count() + + if part_count == 0: + print('Error: Expected core Part data to be imported, but none was found') + sys.exit(1) + + print(f'Confirmed {part_count} Part record(s) imported') + + if PluginConfig.objects.filter(key=PLUGIN_SLUG).exists(): + print( + f'Error: Plugin configuration for "{PLUGIN_SLUG}" was imported, but should have been excluded' + ) + sys.exit(1) + + if PluginSetting.objects.filter(plugin__key=PLUGIN_SLUG).exists(): + print( + f'Error: Plugin settings for "{PLUGIN_SLUG}" were imported, but should have been excluded' + ) + sys.exit(1) + + print(f'Confirmed no plugin data was imported for "{PLUGIN_SLUG}"') + print('All checks passed successfully!') diff --git a/.github/workflows/import_export.yaml b/.github/workflows/import_export.yaml index 9d6bd645b4..d98f509ef8 100644 --- a/.github/workflows/import_export.yaml +++ b/.github/workflows/import_export.yaml @@ -59,6 +59,7 @@ jobs: - .github/workflows/import_export.yaml - .github/scripts/check_exported_data.py - .github/scripts/seed_content_excludes_data.py + - .github/scripts/check_imported_data.py - 'src/backend/**' - 'tasks.py' import-export: @@ -190,6 +191,120 @@ jobs: --check-email exclude --check-tokens exclude --check-sso exclude \ --check-session exclude --check-permissions exclude + exclude-plugins: + # Ensure that --exclude-plugins works for both export and import, with + # and without --bulk: + # - Export: no plugin.* records, no plugin app (AppMixin) records, and the + # plugin app is not listed in the metadata installed_apps + # - Import: a *full* dataset (including plugin app records) can be imported + # with --exclude-plugins into a target where the plugin is not installed, + # without needing --ignore-nonexistent + runs-on: ubuntu-latest + needs: paths-filter + if: needs.paths-filter.outputs.server == 'true' || contains(github.event.pull_request.labels.*.name, 'full-run') + + env: + FULL_FILE: /home/runner/work/InvenTree/test_inventree_data_full.json + EXCLUDED_FILE: /home/runner/work/InvenTree/test_inventree_data_excluded.json + EXCLUDED_BULK_FILE: /home/runner/work/InvenTree/test_inventree_data_excluded_bulk.json + EXCLUDED_SUMMARY: /home/runner/work/InvenTree/test_inventree_summary_excluded.json + EXCLUDED_BULK_SUMMARY: /home/runner/work/InvenTree/test_inventree_summary_excluded_bulk.json + + services: + postgres: + image: postgres:17 + env: + POSTGRES_USER: inventree + POSTGRES_PASSWORD: password + ports: + - 5432:5432 + + steps: + - name: Checkout code + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + fetch-depth: 0 + persist-credentials: false + - name: Environment Setup + uses: $/.github/actions/setup + with: + apt-dependency: gettext poppler-utils libpq-dev + pip-dependency: psycopg + update: true + static: false + - name: Setup Postgres Database + run: | + invoke migrate + invoke dev.setup-test -i + - name: Create Plugin Data + run: | + pip install --only-binary :all: -U inventree-dummy-app-plugin==0.1.0 + invoke migrate + cd src/backend/InvenTree && python manage.py create_dummy_data + - name: Export Full Dataset (plugin data included) + run: | + invoke export-records -o -f ${{ env.FULL_FILE }} + python .github/scripts/check_exported_data.py ${{ env.FULL_FILE }} + - name: Export With --exclude-plugins + run: | + invoke export-records -o -f ${{ env.EXCLUDED_FILE }} --exclude-plugins --summary ${{ env.EXCLUDED_SUMMARY }} + python .github/scripts/check_exported_data.py ${{ env.EXCLUDED_FILE }} --exclude-plugins + - name: Bulk Export With --exclude-plugins + run: | + invoke export-records -o -f ${{ env.EXCLUDED_BULK_FILE }} --exclude-plugins --bulk --summary ${{ env.EXCLUDED_BULK_SUMMARY }} + python .github/scripts/check_exported_data.py ${{ env.EXCLUDED_BULK_FILE }} --exclude-plugins + - name: Compare Standard and Bulk Exports + run: | + # The bulk export must contain exactly the same records as the standard export + python - <<'EOF' + import json, sys + plain = json.load(open('${{ env.EXCLUDED_SUMMARY }}')) + bulk = json.load(open('${{ env.EXCLUDED_BULK_SUMMARY }}')) + if plain['records'] != bulk['records']: + keys = set(plain['records']) | set(bulk['records']) + for key in sorted(keys): + a, b = plain['records'].get(key, 0), bulk['records'].get(key, 0) + if a != b: + print(f'- {key}: standard={a}, bulk={b}') + print('ERROR: Standard and bulk exports (--exclude-plugins) contain different records') + sys.exit(1) + if plain['metadata']['installed_apps'] != bulk['metadata']['installed_apps']: + print('ERROR: Standard and bulk exports (--exclude-plugins) list different installed apps') + sys.exit(1) + print(f"Confirmed standard and bulk exports match ({plain['total_records']} records)") + EOF + - name: Uninstall Plugin + run: | + pip uninstall -y inventree-dummy-app-plugin + - name: Update Environment Variables for Sqlite + run: | + echo "INVENTREE_DB_ENGINE=sqlite" >> $GITHUB_ENV + echo "INVENTREE_DB_NAME=/home/runner/work/InvenTree/test_inventree_db.sqlite3" >> $GITHUB_ENV + - name: Setup Sqlite Database (plugin not installed) + run: | + invoke migrate + test -f /home/runner/work/InvenTree/test_inventree_db.sqlite3 || (echo "Sqlite database not created" && exit 1) + - name: Import Excluded Dataset + run: | + # Plugin apps are not listed in the metadata, so --strict must pass + invoke import-records -c -f ${{ env.EXCLUDED_FILE }} --strict --exclude-plugins + cd src/backend/InvenTree && python ../../../.github/scripts/check_imported_data.py + - name: Bulk Import Excluded Dataset + run: | + invoke import-records -c -f ${{ env.EXCLUDED_BULK_FILE }} --strict --exclude-plugins --bulk + cd src/backend/InvenTree && python ../../../.github/scripts/check_imported_data.py + - name: Import Full Dataset With --exclude-plugins + run: | + # The full dataset contains plugin app records - these must be skipped + # by --exclude-plugins, *without* needing --ignore-nonexistent. + # Note: --strict is not used, as the source metadata lists the plugin app + invoke import-records -c -f ${{ env.FULL_FILE }} --exclude-plugins + cd src/backend/InvenTree && python ../../../.github/scripts/check_imported_data.py + - name: Bulk Import Full Dataset With --exclude-plugins + run: | + invoke import-records -c -f ${{ env.FULL_FILE }} --exclude-plugins --bulk + cd src/backend/InvenTree && python ../../../.github/scripts/check_imported_data.py + plugin-absent: # Ensure that importing data referencing a plugin's own models degrades # gracefully (skipping just those records) when that plugin isn't diff --git a/src/backend/InvenTree/InvenTree/management/commands/list_apps.py b/src/backend/InvenTree/InvenTree/management/commands/list_apps.py index 56db10e350..b1972e983d 100644 --- a/src/backend/InvenTree/InvenTree/management/commands/list_apps.py +++ b/src/backend/InvenTree/InvenTree/management/commands/list_apps.py @@ -10,6 +10,26 @@ from django.core.management.base import BaseCommand class Command(BaseCommand): """List all installed apps.""" + def add_arguments(self, parser): + """Add command arguments.""" + parser.add_argument( + '--labels', + action='store_true', + help='Output app labels (e.g. "auth") instead of full app names (e.g. "django.contrib.auth")', + ) + + group = parser.add_mutually_exclusive_group() + group.add_argument( + '--plugins-only', + action='store_true', + help='Only list apps which are provided by plugins', + ) + group.add_argument( + '--exclude-plugins', + action='store_true', + help='Do not list apps which are provided by plugins', + ) + def handle(self, *args, **kwargs): """List all installed apps. @@ -18,10 +38,24 @@ class Command(BaseCommand): """ from django.apps import apps + from plugin import registry + + labels = kwargs.get('labels', False) + plugins_only = kwargs.get('plugins_only', False) + exclude_plugins = kwargs.get('exclude_plugins', False) + + # Apps which have been added to INSTALLED_APPS by AppMixin plugins + plugin_apps = set(registry.installed_apps) + app_list = [] for app in apps.get_app_configs(): - app_list.append(app.name) + is_plugin = app.name in plugin_apps + + if (plugins_only and not is_plugin) or (exclude_plugins and is_plugin): + continue + + app_list.append(app.label if labels else app.name) app_list.sort() diff --git a/tasks.py b/tasks.py index 575f4515f3..c312f4676f 100644 --- a/tasks.py +++ b/tasks.py @@ -555,9 +555,27 @@ def manage_interactive(cmd: str, env=None, verbose: bool = False): raise Exit(code=result.returncode) -def installed_apps(c) -> list[str]: - """Returns a list of all installed apps, including plugins.""" - result = manage(c, 'list_apps', pty=False, hide=True) +def installed_apps( + c, labels: bool = False, plugins_only: bool = False, exclude_plugins: bool = False +) -> list[str]: + """Returns a list of all installed apps, including plugins. + + Arguments: + c: Command line context. + labels: If True, return app labels (e.g. 'auth') rather than full app names (e.g. 'django.contrib.auth'). + plugins_only: If True, only return apps which are provided by plugins. + exclude_plugins: If True, do not return apps which are provided by plugins. + """ + cmd = 'list_apps' + + if labels: + cmd += ' --labels' + if plugins_only: + cmd += ' --plugins-only' + if exclude_plugins: + cmd += ' --exclude-plugins' + + result = manage(c, cmd, pty=False, hide=True) output = result.stdout.strip() # Look for the expected pattern @@ -566,7 +584,8 @@ def installed_apps(c) -> list[str]: if not match: raise ValueError(f"Unexpected output from 'list_apps' command: {output}") - return match[0].split(',') + # An empty list is output as '>>> <<<' - filter out the empty string + return [app for app in match[0].split(',') if app] def run_install( @@ -1278,6 +1297,12 @@ def export_records( allow_sso=include_sso, ) + if exclude_plugins: + # Also exclude any data from apps provided by plugins (AppMixin) + if plugin_labels := installed_apps(c, labels=True, plugins_only=True): + info(f'Excluding plugin apps: {", ".join(plugin_labels)}') + excludes += ' ' + ' '.join(f'--exclude {label}' for label in plugin_labels) + with tempfile.NamedTemporaryFile( suffix='.json', encoding='utf-8', mode='w+t', delete=True ) as tmpfile: @@ -1304,7 +1329,7 @@ def export_records( 'django_version': get_django_version(), 'python_version': python_version(), 'source_commit': get_commit_hash(), - 'installed_apps': installed_apps(c), + 'installed_apps': installed_apps(c, exclude_plugins=exclude_plugins), } def entries_out(): @@ -1502,6 +1527,16 @@ def import_records( # A dict containing metadata associated with the data file metadata = {} + # When excluding plugins, records belonging to plugin-provided apps (AppMixin) + # must also be skipped - those apps will not be installed in the target + # environment (as the plugin configs are not imported), and so the records + # would otherwise fail with "Invalid model identifier" + local_app_labels: Optional[set[str]] = None + skipped_records: dict[str, int] = {} + + if exclude_plugins: + local_app_labels = set(installed_apps(c, labels=True)) + def load_data( title: str, data: list[dict], @@ -1553,6 +1588,18 @@ def import_records( continue if model := entry.get('model', None): + if exclude_plugins: + app_label = model.split('.')[0] + + # Skip records for apps which are not installed (i.e. plugin apps) + if app_label not in local_app_labels: + skipped_records[model] = skipped_records.get(model, 0) + 1 + continue + + # Remove references to plugin configs which are not being imported + if model == 'common.selectionlist': + entry['fields']['source_plugin'] = None + # Clear out any permissions specified for a group # (these are regenerated after import) if model == 'auth.group': @@ -1580,6 +1627,11 @@ def import_records( if strict: sys.exit(1) + for model, count in sorted(skipped_records.items()): + warning( + f"Skipping {count} '{model}' records - app is not installed (--exclude-plugins)" + ) + # Check the metadata associated with the imported data # Do not validate the 'apps' list yet - as the plugins have not yet been loaded validate_import_metadata(c, metadata, strict=strict, apps=False)