### Build and Install gpupdate from Source Source: https://github.com/altlinux/gpupdate/blob/master/README.md Commands to clone the repository, build RPM packages, and install the gpupdate and gpoa-lib components. ```bash # Clone the repository git clone https://github.com/altlinux/gpupdate.git cd gpupdate # Build RPM packages (produces gpupdate and gpoa-lib) rpmbuild -ba gpupdate.spec # Install both packages rpm -ivh ~/rpmbuild/RPMS/noarch/gpupdate-*.rpm ~/rpmbuild/RPMS/noarch/gpoa-lib-*.rpm # Or install only the library rpm -ivh ~/rpmbuild/RPMS/noarch/gpoa-lib-*.rpm ``` -------------------------------- ### Install gpupdate packages Source: https://github.com/altlinux/gpupdate/wiki/Quickstart Use apt-get to update package lists and install the gpupdate utility. ```bash apt-get update apt-get install gpupdate ``` -------------------------------- ### Enable group policy applier Source: https://github.com/altlinux/gpupdate/wiki/Quickstart Run the setup utility to enable the group policy service, followed by a system reboot. ```bash gpupdate-setup enable ``` -------------------------------- ### Compile and Install Translations Source: https://github.com/altlinux/gpupdate/blob/master/PLUGIN_DEVELOPMENT_GUIDE.md Compile the .po file into a .mo file and move it to the system locale directory. ```bash # Compile .po to .mo msgfmt my_plugin.po -o my_plugin.mo # Place in correct directory mkdir -p /usr/share/locale/ru/LC_MESSAGES/ cp my_plugin.mo /usr/share/locale/ru/LC_MESSAGES/ ``` -------------------------------- ### Implement a Custom FrontendPlugin Source: https://github.com/altlinux/gpupdate/blob/master/API_REFERENCE.md Example implementation of a custom plugin inheriting from FrontendPlugin, requiring an override of the run method. ```python from gpoa_lib.plugin import FrontendPlugin class MyPlugin(FrontendPlugin): def run(self, **kwargs): data = self.get_dict_registry('Software/MyOrg/Policies') for key, value in data.items(): self.log('D1', {'key': key, 'value': value}) def create_machine_applier(dict_dconf_db, username, file_cache): return MyPlugin(dict_dconf_db, username, file_cache) def create_user_applier(dict_dconf_db, username, file_cache): return MyPlugin(dict_dconf_db, username, file_cache) ``` -------------------------------- ### Configure Python Path for Plugins Source: https://github.com/altlinux/gpupdate/blob/master/EXAMPLES.md Required setup to import plugins located in the non-standard directory /usr/lib/gpoa/plugins. ```python import sys sys.path.insert(0, '/usr/lib/gpoa/plugins') ``` -------------------------------- ### Install Alterator graphical tools Source: https://github.com/altlinux/gpupdate/wiki/Quickstart Install optional Alterator modules for graphical group policy management. ```bash apt-get install alterator-auth alterator-gpupdate ``` -------------------------------- ### Define Translation File Content Source: https://github.com/altlinux/gpupdate/blob/master/PLUGIN_DEVELOPMENT_GUIDE.md Example structure for a .po translation file. ```po # my_plugin.po msgid "Plugin initialized" msgstr "" msgid "Configuration applied successfully" msgstr "" ``` -------------------------------- ### filter_hklm_entries(startswith) Source: https://github.com/altlinux/gpupdate/blob/master/API_REFERENCE.md Returns a list of PregDconf objects whose keyname starts with the provided prefix. A trailing '%' in the prefix is stripped before matching. ```APIDOC ## filter_hklm_entries(startswith) ### Description Return a list of `PregDconf` objects whose keyname starts with `startswith`. A trailing `%` in `startswith` is stripped before matching. ### Parameters - **startswith** (str) - Required - Registry path prefix. Trailing `%` is accepted and stripped. ### Returns - `list[PregDconf]` ``` -------------------------------- ### Initialize and execute a plugin with a custom registry path Source: https://github.com/altlinux/gpupdate/blob/master/PLUGIN_DEVELOPMENT_GUIDE.md Demonstrates manual plugin instantiation using a custom registry path via the StorageAdapter. ```python from gpoa_lib import StorageAdapter from my_plugin import MyPlugin storage = StorageAdapter.from_dict({'Custom/Path': {'key': 'value'}}) plugin = MyPlugin(storage.get_dict(), registry_path='Custom/Path') plugin.apply() ``` -------------------------------- ### Execute Plugins with Custom Data Source: https://github.com/altlinux/gpupdate/blob/master/README.md Demonstrates manual plugin execution by loading storage adapters and applying them with custom registry paths. ```python import sys sys.path.insert(0, '/usr/lib/gpoa/plugins') from gpoa_lib import StorageAdapter from udev_applier import UdevApplier # From dict with default registry path storage = StorageAdapter.from_dict({ 'Software/BaseALT/Policies/Udev': {'BlockUSBAll': '1'} }) plugin = UdevApplier(storage.get_dict()) plugin.apply() # With custom registry_path plugin = UdevApplier(storage.get_dict(), registry_path='My/Custom/Path') plugin.apply() ``` -------------------------------- ### Create a Plugin for Machine and User Contexts Source: https://github.com/altlinux/gpupdate/blob/master/EXAMPLES.md Implement a plugin that supports both machine and user contexts by providing separate factory functions. ```python from gpoa_lib.plugin.plugin_base import FrontendPlugin class DualPlugin(FrontendPlugin): def __init__(self, dict_dconf_db, username=None, fs_file_cache=None, registry_path=None): super().__init__(dict_dconf_db, username, fs_file_cache, registry_path) self._init_plugin_log( message_dict={ 'i': {1: "DualPlugin running for {who}"}, }, domain="dual_plugin", ) self.config = self.get_dict_registry('Software/MyOrg/Policies/Dual') def run(self, **kwargs): who = self.username or 'machine' self.log("I1", {"who": who}) def create_machine_applier(dict_dconf_db, username=None, fs_file_cache=None, registry_path=None): return DualPlugin(dict_dconf_db, username, fs_file_cache, registry_path) def create_user_applier(dict_dconf_db, username=None, fs_file_cache=None, registry_path=None): return DualPlugin(dict_dconf_db, username, fs_file_cache, registry_path) ``` -------------------------------- ### Initialize ApplierRunner from dconf Source: https://github.com/altlinux/gpupdate/blob/master/EXAMPLES.md Demonstrates basic initialization of ApplierRunner using a dconf database name. ```python from gpoa_lib import ApplierRunner runner = ApplierRunner(db_name='mydb') result = runner.create('control') if result: result.data.apply() ``` -------------------------------- ### run(applier_name, prefix=None, keys=None) Source: https://github.com/altlinux/gpupdate/blob/master/API_REFERENCE.md Creates an applier and executes its apply method. ```APIDOC ## run(applier_name, prefix=None, keys=None) ### Description Creates an applier and calls its apply() method. Exceptions are caught and returned as a failed Result. ### Parameters - **applier_name** (str) - Required - Key in the internal applier map. - **prefix** (str) - Optional - Override base prefix. - **keys** (list[str]) - Optional - Specific registry keys to load. ### Returns - **Result** ``` -------------------------------- ### Create StorageAdapter from Dictionary Source: https://github.com/altlinux/gpupdate/blob/master/API_REFERENCE.md Instantiate an adapter using a plain Python dictionary mapping registry paths to key-value pairs. ```python adapter = StorageAdapter.from_dict({ 'Software/BaseALT/Policies/Control': { 'sshd-gssapi-auth': '1', } }) ``` -------------------------------- ### Create a Custom GPOA Frontend Plugin Source: https://github.com/altlinux/gpupdate/blob/master/README.md Implement a custom plugin by inheriting from FrontendPlugin and defining the required initialization and run methods. ```python from gpoa_lib.plugin.plugin_base import FrontendPlugin class MyPlugin(FrontendPlugin): domain = 'my_plugin' def __init__(self, dict_dconf_db, username=None, fs_file_cache=None, registry_path=None): super().__init__(dict_dconf_db, username, fs_file_cache, registry_path) self._init_plugin_log(message_dict={ 'i': {1: "Plugin initialized"}, 'e': {1: "Plugin failed"} }, domain="my_plugin") self.config = self.get_dict_registry( self._registry_path or 'Software/MyOrg/Policies/MyPlugin') def run(self, **kwargs): self.log("I1") return True def create_machine_applier(dict_dconf_db, username=None, fs_file_cache=None, registry_path=None): return MyPlugin(dict_dconf_db, username, fs_file_cache, registry_path) ``` -------------------------------- ### Initialize Logger with Translation Support Source: https://github.com/altlinux/gpupdate/blob/master/PLUGIN_DEVELOPMENT_GUIDE.md Configure the logger with a domain that matches the translation file lookup. ```python self._init_plugin_log( message_dict={ 'i': { 1: "Plugin initialized", 2: "Configuration applied successfully" }, 'e': { 10: "Configuration error" } }, domain="my_plugin" # Domain for translation file lookup ) ``` -------------------------------- ### Initialize plugin_manager Source: https://github.com/altlinux/gpupdate/blob/master/API_REFERENCE.md Instantiate the plugin manager with the target context and username. ```python plugin_manager(is_machine, username) ``` -------------------------------- ### Run Plugin from Plain Dictionary Source: https://github.com/altlinux/gpupdate/blob/master/EXAMPLES.md Initializes a plugin using a standard Python dictionary instead of a dconf database. ```python import sys sys.path.insert(0, '/usr/lib/gpoa/plugins') from gpoa_lib import StorageAdapter from udev_applier import UdevApplier storage = StorageAdapter.from_dict({ 'Software/BaseALT/Policies/Udev': { 'BlockUSBAll': '1', 'USBAllowList': '1234:5678;abcd:ef01', } }) plugin = UdevApplier(storage.get_dict()) plugin.apply() ``` -------------------------------- ### Initialize StorageAdapter Source: https://github.com/altlinux/gpupdate/blob/master/API_REFERENCE.md Constructor for creating a new StorageAdapter instance. ```python StorageAdapter(db_name=None, uid=None, prefix=None, keys=None, data=None) ``` -------------------------------- ### Create a Minimal Machine-Only Plugin Source: https://github.com/altlinux/gpupdate/blob/master/EXAMPLES.md Implement a basic plugin by inheriting from FrontendPlugin and defining a machine applier factory function. ```python from gpoa_lib.plugin.plugin_base import FrontendPlugin class MyPlugin(FrontendPlugin): def __init__(self, dict_dconf_db, username=None, fs_file_cache=None, registry_path=None): super().__init__(dict_dconf_db, username, fs_file_cache, registry_path) self._init_plugin_log( message_dict={ 'i': {1: "MyPlugin started"}, 'w': {1: "No configuration found"}, }, domain="my_plugin", ) self.config = self.get_dict_registry('Software/MyOrg/Policies/MyPlugin') def run(self, **kwargs): self.log("I1") if not self.config: self.log("W1") return # Apply configuration... for key, value in self.config.items(): pass # your logic here def create_machine_applier(dict_dconf_db, username=None, fs_file_cache=None, registry_path=None): return MyPlugin(dict_dconf_db, username, fs_file_cache, registry_path) ``` -------------------------------- ### Initialize GppStateManager Source: https://github.com/altlinux/gpupdate/blob/master/API_REFERENCE.md Constructor for the GppStateManager class. Use 'Machine' or None for machine-wide context. ```python GppStateManager(username=None) ``` -------------------------------- ### Initialize RegistryKeyMetadata Source: https://github.com/altlinux/gpupdate/blob/master/API_REFERENCE.md Create a metadata object for a registry key by specifying policy name, type, list status, and previous value modifiers. ```python meta = RegistryKeyMetadata( policy_name='ControlPolicy', type='string', is_list=False, mod_previous_value=None, ) ``` -------------------------------- ### List Available Appliers Source: https://github.com/altlinux/gpupdate/blob/master/EXAMPLES.md Retrieve a list of all currently available appliers in the system. ```python from gpoa_lib import ApplierRunner print(ApplierRunner.list_appliers()) # ['control', 'chromium', 'firefox', 'thunderbird', 'yandex_browser', # 'firewall', 'gsettings', 'kde', 'ntp', 'package', 'polkit', 'systemd'] ``` -------------------------------- ### Standalone plugin without plugin_manager Source: https://github.com/altlinux/gpupdate/blob/master/EXAMPLES.md Implement a custom FrontendPlugin and execute it using a StorageAdapter. ```python from gpoa_lib import StorageAdapter from gpoa_lib.plugin.plugin_base import FrontendPlugin # Define a custom plugin inline class HelloPlugin(FrontendPlugin): def __init__(self, dict_dconf_db, username=None, fs_file_cache=None, registry_path=None): super().__init__(dict_dconf_db, username, fs_file_cache, registry_path) def run(self, **kwargs): greeting = self.get_dict_registry('Software/MyOrg/Hello') msg = greeting.get('Message', 'Hello World') print(msg) # Use with StorageAdapter storage = StorageAdapter.from_dict({ 'Software/MyOrg/Hello': { 'Message': 'Hello from gpoa_lib!', } }) plugin = HelloPlugin(storage.get_dict()) plugin.apply() # Output: Hello from gpoa_lib! ``` -------------------------------- ### Construct RegistryKeyMetadata Source: https://github.com/altlinux/gpupdate/blob/master/API_REFERENCE.md Instantiate the RegistryKeyMetadata class with required policy parameters. ```python RegistryKeyMetadata(policy_name, type, is_list=None, mod_previous_value=None) ``` -------------------------------- ### Initialize and use DynamicAttributes Source: https://github.com/altlinux/gpupdate/blob/master/API_REFERENCE.md Create a container for arbitrary key-value pairs and convert it to a dictionary or iterate over its items. ```python attr = DynamicAttributes(name='test', value=42) attr.items() # yields (key, value) pairs dict(attr) # convert to dict ``` -------------------------------- ### Import FilterChecker Source: https://github.com/altlinux/gpupdate/blob/master/API_REFERENCE.md Import the FilterChecker class to evaluate GPO targeting filters. ```python from gpoa_lib.util.check_filters import FilterChecker ``` -------------------------------- ### Initialize plugin constructor Source: https://github.com/altlinux/gpupdate/blob/master/API_REFERENCE.md Constructor for the plugin base class, accepting optional configuration for policy data, user context, file caching, and registry paths. ```python plugin(dict_dconf_db=None, username=None, fs_file_cache=None, registry_path=None) ``` -------------------------------- ### Run Plugin from dconf Database with Custom Registry Path Source: https://github.com/altlinux/gpupdate/blob/master/EXAMPLES.md Combines dconf database loading with a custom registry path override. ```python import sys sys.path.insert(0, '/usr/lib/gpoa/plugins') from gpoa_lib import StorageAdapter from udev_applier import UdevApplier storage = StorageAdapter.from_dconf_db('mydb') plugin = UdevApplier( storage.get_dict(), registry_path='Software/MyOrg/Policies/DeviceRules', ) plugin.apply() ``` -------------------------------- ### Apply Policies via Command Line Source: https://github.com/altlinux/gpupdate/blob/master/README.md Commands for applying system-wide or user-specific policies, and forcing a policy refresh. ```bash # Run as root for system-wide policies sudo gpoa ``` ```bash # Run as root for user-specific policies sudo gpoa username ``` ```bash # Can be run as regular user gpupdate --force ``` -------------------------------- ### Apply control via StorageAdapter Source: https://github.com/altlinux/gpupdate/blob/master/EXAMPLES.md Manual application of control settings using StorageAdapter and a specific applier class. ```python from gpoa_lib import StorageAdapter from gpoa_lib.frontend import control_applier storage = StorageAdapter.from_dict({ 'Software/BaseALT/Policies/Control': { 'sshd-gssapi-auth': '1', } }) ctrl = control_applier(storage) ctrl.apply() ``` ```python from gpoa_lib import StorageAdapter from gpoa_lib.frontend import control_applier storage = StorageAdapter.from_dconf_db('mydb') ctrl = control_applier(storage) ctrl.apply() ``` ```python from gpoa_lib import StorageAdapter from gpoa_lib.frontend import control_applier storage = StorageAdapter.from_dconf_db_prefix( 'mydb', prefix='Software/MyOrg/Policies/Control', ) ctrl = control_applier(storage) ctrl.apply() ``` -------------------------------- ### Initialize Result object Source: https://github.com/altlinux/gpupdate/blob/master/API_REFERENCE.md Constructor signature for creating a new Result instance. ```python Result(ok, data=None, error=None) ``` -------------------------------- ### Initialize StorageWriter Source: https://github.com/altlinux/gpupdate/blob/master/API_REFERENCE.md Constructor for creating a new StorageWriter instance for a specific database. ```python StorageWriter(db_name, uid=None) ``` -------------------------------- ### compile() Source: https://github.com/altlinux/gpupdate/blob/master/API_REFERENCE.md Compiles the database from its INI sources. ```APIDOC ## compile() ### Description Executes the dconf compile command to generate the binary database from existing INI sources. ``` -------------------------------- ### StorageAdapter.from_dict Source: https://github.com/altlinux/gpupdate/blob/master/API_REFERENCE.md Creates a StorageAdapter instance from a plain Python dictionary containing registry path mappings. ```APIDOC ## StorageAdapter.from_dict(data) ### Description Creates an adapter from a plain Python dict. ### Parameters - **data** (dict) - Required - Nested dict mapping registry paths to {name: value} dicts. ### Returns - **StorageAdapter** - An instance of the StorageAdapter class. ``` -------------------------------- ### Write flat dictionary keys Source: https://github.com/altlinux/gpupdate/blob/master/API_REFERENCE.md Writes a flat dictionary of full registry paths to the INI file and compiles the database. ```python writer = StorageWriter('local') writer.write_keys({ 'Software/BaseALT/Policies/Control/sshd-gssapi-auth': '1', 'Software/BaseALT/Policies/Control/ssh-gssapi-auth': 'enabled', }) writer.compile() ``` -------------------------------- ### Run Applier and Process Results Source: https://github.com/altlinux/gpupdate/blob/master/API_REFERENCE.md Demonstrates executing an applier via ApplierRunner and iterating through the resulting ApplierResult to handle successes and failures. ```python from gpoa_lib import ApplierRunner runner = ApplierRunner(data=my_dict) result = runner.run('control') if result and result.data: status = result.data # ApplierResult print(f'{status.name}: {status.status}') print(f' applied: {status.applied_count}') for item in status.items: if item.result == 'failed': print(f' FAIL: {item.key} — {item.detail}') ``` -------------------------------- ### Implement a Basic GPOA Plugin Source: https://github.com/altlinux/gpupdate/blob/master/PLUGIN_DEVELOPMENT_GUIDE.md Defines a plugin class inheriting from FrontendPlugin with logging and registry access, including factory functions for instantiation. ```python #!/usr/bin/env python3 # # GPOA - GPO Applier for Linux # # Copyright (C) 2025 BaseALT Ltd. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. from gpoa_lib.plugin.plugin_base import FrontendPlugin class ExampleApplier(FrontendPlugin): """ Example simple plugin with logging and registry access. """ # Domain for translations domain = 'example_applier' def __init__(self, dict_dconf_db, username=None, fs_file_cache=None, registry_path=None): """ Initialize the plugin. Args: dict_dconf_db (dict): Dictionary with registry data username (str): Username fs_file_cache: File system cache registry_path (str): Override registry path for data lookup """ super().__init__(dict_dconf_db, username, fs_file_cache, registry_path) # Initialize logging system self._init_plugin_log( message_dict={ 'i': { # Informational messages 1: "Example Applier initialized", 2: "Configuration applied successfully" }, 'w': { # Warnings 10: "No configuration found in registry" }, 'e': { # Errors 20: "Failed to apply configuration" } }, domain="example_applier" ) def run(self, **kwargs): """ Main plugin execution method. Returns: bool: True if successful, False on error """ try: self.log("I1") # Plugin initialized # Get data from registry self.config = self.get_dict_registry( self._registry_path or 'Software/BaseALT/Policies/Example') if not self.config: self.log("W10") # No configuration found in registry return True # Log registry data self.log("I2") # Configuration applied successfully return True except Exception as e: self.log("E20", {"error": str(e)}) return False def create_machine_applier(dict_dconf_db, username=None, fs_file_cache=None, registry_path=None): """ Factory function for creating plugin instance for machine context. Args: dict_dconf_db (dict): Dictionary with registry data username (str): Username fs_file_cache: File system cache registry_path (str): Override registry path Returns: ExampleApplier: Plugin instance """ return ExampleApplier(dict_dconf_db, username, fs_file_cache, registry_path) def create_user_applier(dict_dconf_db, username=None, fs_file_cache=None, registry_path=None): """ Factory function for creating plugin instance for user context. Args: dict_dconf_db (dict): Dictionary with registry data username (str): Username fs_file_cache: File system cache registry_path (str): Override registry path Returns: ExampleApplier: Plugin instance """ return ExampleApplier(dict_dconf_db, username, fs_file_cache, registry_path) ``` -------------------------------- ### Project Directory Structure Source: https://github.com/altlinux/gpupdate/blob/master/README.md Overview of the gpupdate repository layout, including core logic, libraries, and configuration files. ```text gpupdate/ ├── gpoa/ # Entry points and thin wrappers → gpoa_lib │ ├── backend/ # Samba, FreeIPA, nodomain backends │ ├── frontend/ # Thin wrappers for appliers │ │ └── appliers/ # Individual applier wrappers │ ├── frontend_plugins/ # Built-in frontend plugins │ ├── gpt/ # GPT parsing and filter processing │ ├── locale/ # Russian translations │ ├── messages/ # Message code definitions │ ├── plugin/ # Plugin manager wrapper │ ├── storage/ # Storage wrapper │ ├── templates/ # Jinja2 templates (autofs, dconf) │ ├── util/ # Utility wrappers │ ├── gpoa # Main GPOA entry point │ ├── gpupdate # gpupdate CLI entry point │ └── gpupdate-setup # Enable/disable configuration tool │ ├── gpoa_lib/ │ └── gpoa_lib/ # Standalone library (gpoa-lib RPM) │ ├── frontend/ # 20 policy appliers │ │ └── appliers/ # Individual applier implementations │ ├── frontend_plugins/ # Built-in plugin implementations │ ├── plugin/ # Plugin framework (base, manager, logging) │ ├── storage/ # Dconf registry, GPP state, StorageAdapter │ ├── util/ # Utilities, filters, logging, paths │ ├── messages/ # Localized message definitions │ ├── test/ # Unit tests (430+ tests) │ ├── __init__.py # Public API exports │ ├── applier_runner.py # ApplierRunner facade │ └── result.py # Result type (ok/fail pattern) │ ├── dist/ # systemd units, polkit, PAM rules ├── doc/ # Man pages ├── completions/ # Bash completion scripts ├── tools/ # Auxiliary scripts ├── gpupdate.spec # RPM spec (gpupdate + gpoa-lib subpackage) ├── API_REFERENCE.md # API reference (English) ├── API_REFERENCE_RU.md # API reference (Russian) ├── PLUGIN_DEVELOPMENT_GUIDE.md # Plugin development guide (English) ├── PLUGIN_DEVELOPMENT_GUIDE_RU.md # Plugin development guide (Russian) └── EXAMPLES.md # External API usage examples ``` -------------------------------- ### resolve(key_or_prefix) Source: https://github.com/altlinux/gpupdate/blob/master/API_REFERENCE.md Determines the applier name from a registry key path or prefix. ```APIDOC ## resolve(key_or_prefix) ### Description Determines the applier name from a registry key path or prefix. Comparison is case-insensitive. ### Parameters - **key_or_prefix** (str) - Required - Full registry path or prefix. ### Returns - **str or None** ``` -------------------------------- ### Initialize PregDconf Source: https://github.com/altlinux/gpupdate/blob/master/API_REFERENCE.md Represents a single registry entry extracted from dconf. ```python PregDconf(keyname, valuename, type_preg, data) ``` -------------------------------- ### Run Plugin from Specific dconf Keys Source: https://github.com/altlinux/gpupdate/blob/master/EXAMPLES.md Loads only the specified keys from a dconf database for plugin configuration. ```python import sys sys.path.insert(0, '/usr/lib/gpoa/plugins') from gpoa_lib import StorageAdapter from udev_applier import UdevApplier storage = StorageAdapter.from_dconf_db_keys('my_custom_db', [ 'Software/BaseALT/Policies/Udev/BlockUSBAll', 'Software/BaseALT/Policies/Udev/USBAllowList', ]) plugin = UdevApplier(storage.get_dict()) plugin.apply() ``` -------------------------------- ### Load StorageAdapter with Key Filter Source: https://github.com/altlinux/gpupdate/blob/master/API_REFERENCE.md Load data from a dconf database while restricting the result set to a specific list of registry key paths. ```python adapter = StorageAdapter.from_dconf_db_keys('policy', [ 'Software/BaseALT/Policies/Control/sshd-gssapi-auth', 'Software/BaseALT/Policies/Control/ldap-tls-check', ]) ``` -------------------------------- ### Load StorageAdapter from dconf Database Source: https://github.com/altlinux/gpupdate/blob/master/API_REFERENCE.md Load policy data from a dconf binary database, optionally specifying a user UID. ```python adapter = StorageAdapter.from_dconf_db('policy') adapter = StorageAdapter.from_dconf_db('policy', uid=1000) ``` -------------------------------- ### Register Plugin Log Messages Source: https://github.com/altlinux/gpupdate/blob/master/PLUGIN_DEVELOPMENT_GUIDE.md Initialize the logging system with a dictionary of informational, warning, and error message codes. ```python self._init_plugin_log( message_dict={ 'i': { # Informational messages 1: "Example Applier initialized", 2: "Configuration applied successfully" }, 'w': { # Warnings 10: "No configuration found in registry" }, 'e': { # Errors 20: "Failed to apply configuration" } }, domain="example_applier" ) ``` -------------------------------- ### Initialize ApplierRunner Source: https://github.com/altlinux/gpupdate/blob/master/API_REFERENCE.md Constructor for creating an ApplierRunner instance with optional database, user, or data parameters. ```python ApplierRunner(db_name=None, uid=None, data=None, force=False) ``` -------------------------------- ### Import gpoa_lib components Source: https://github.com/altlinux/gpupdate/blob/master/API_REFERENCE.md Standard import statement for accessing core classes and utilities from the gpoa_lib package. ```python from gpoa_lib import ( Result, ApplierResult, ItemStatus, StorageAdapter, StorageWriter, ApplierRunner, FrontendPlugin, applier_frontend, DualContextApplier, Dconf_registry, GppStateManager, DynamicAttributes, RegistryKeyMetadata, ) ``` -------------------------------- ### Run an Applier Source: https://github.com/altlinux/gpupdate/blob/master/API_REFERENCE.md Execute an applier directly and handle the resulting status or errors. ```python runner = ApplierRunner(data=my_dict) result = runner.run('control') if not result: print('Error:', result.error) elif result.data: status = result.data # ApplierResult print(f'{status.name}: {status.status}, applied={status.applied_count}') runner.run('gsettings', prefix='Software/MyOrg') ``` -------------------------------- ### ApplierRunner Constructor Source: https://github.com/altlinux/gpupdate/blob/master/API_REFERENCE.md Initializes a new ApplierRunner instance. ```APIDOC ## ApplierRunner(db_name=None, uid=None, data=None, force=False) ### Description Initializes the ApplierRunner with optional database, user, or data parameters. ### Parameters - **db_name** (str or None) - Optional - Dconf database name. - **uid** (int or None) - Optional - User UID. - **data** (dict or None) - Optional - Plain dict; when given, no dconf access is performed. - **force** (bool) - Optional - If True, bypass merged profile and re-apply. Default False. ``` -------------------------------- ### Create an Applier Instance Source: https://github.com/altlinux/gpupdate/blob/master/API_REFERENCE.md Instantiate an applier without immediate execution using the create method. ```python runner = ApplierRunner(data=my_dict) result = runner.create('control') if result: applier = result.data applier.apply() ``` -------------------------------- ### Plugin with locale/translations Source: https://github.com/altlinux/gpupdate/blob/master/EXAMPLES.md Implement a plugin that supports gettext localization by initializing the plugin log with a message dictionary. ```python from gpoa_lib.plugin.plugin_base import FrontendPlugin class LocalizedPlugin(FrontendPlugin): def __init__(self, dict_dconf_db, username=None, fs_file_cache=None, registry_path=None): super().__init__(dict_dconf_db, username, fs_file_cache, registry_path) self._init_plugin_log( message_dict={ 'i': {1: "Localized greeting: {text}"}, 'w': {1: "Missing key {key}"}, }, domain="localized_plugin", ) self.config = self.get_dict_registry('Software/MyOrg/Localized') def run(self, **kwargs): text = self.config.get('Greeting', '') if text: self.log("I1", {"text": text}) else: self.log("W1", {"key": "Greeting"}) def create_machine_applier(dict_dconf_db, username=None, fs_file_cache=None, registry_path=None): return LocalizedPlugin(dict_dconf_db, username, fs_file_cache, registry_path) ``` -------------------------------- ### create(applier_name, prefix=None, keys=None) Source: https://github.com/altlinux/gpupdate/blob/master/API_REFERENCE.md Creates an applier instance without executing it. ```APIDOC ## create(applier_name, prefix=None, keys=None) ### Description Creates an applier instance based on the provided name and optional configuration. ### Parameters - **applier_name** (str) - Required - Key in the internal applier map. - **prefix** (str) - Optional - Override base prefix. - **keys** (list[str]) - Optional - Specific registry keys to load. ### Returns - **Result** - result.data holds the applier instance on success. ``` -------------------------------- ### Check Module Configuration Flags Source: https://github.com/altlinux/gpupdate/blob/master/API_REFERENCE.md Module-level helper functions to verify if specific applier modules are enabled via registry flags. ```python check_experimental_enabled(storage) -> bool check_windows_mapping_enabled(storage) -> bool check_module_enabled(storage, module_name) -> Optional[bool] check_enabled(storage, module_name, is_experimental) -> bool ``` -------------------------------- ### Run Plugins Programmatically Source: https://github.com/altlinux/gpupdate/blob/master/EXAMPLES.md Execute plugins using the plugin_manager for specific contexts or retrieve individual plugins by name. ```python from gpoa_lib.plugin.plugin_manager import plugin_manager # Machine context pm = plugin_manager(is_machine=True, username=None) pm.run() # User context pm = plugin_manager(is_machine=False, username='someuser') pm.run() # Get a specific loaded plugin by name plugin = pm.get_plugin('my_plugin') if plugin: plugin.apply() ``` -------------------------------- ### Load StorageAdapter with Prefix Filter Source: https://github.com/altlinux/gpupdate/blob/master/API_REFERENCE.md Load data from a dconf database while restricting the result set to keys under a specific registry path prefix. ```python adapter = StorageAdapter.from_dconf_db_prefix('policy', 'Software/BaseALT/Policies/Control') ``` -------------------------------- ### StorageWriter Constructor Source: https://github.com/altlinux/gpupdate/blob/master/API_REFERENCE.md Initializes a new StorageWriter instance for a specific dconf database. ```APIDOC ## StorageWriter(db_name, uid=None) ### Description Initializes the writer for a database located under /etc/dconf/db/. ### Parameters - **db_name** (str) - Required - Database name (e.g., 'local'). - **uid** (int) - Optional - User UID for per-user databases. ``` -------------------------------- ### StorageAdapter.from_dconf_db Source: https://github.com/altlinux/gpupdate/blob/master/API_REFERENCE.md Loads policy data from a dconf binary database located in /etc/dconf/db/. ```APIDOC ## StorageAdapter.from_dconf_db(db_name, uid=None) ### Description Load policy data from a dconf binary database. ### Parameters - **db_name** (str) - Required - Database filename under /etc/dconf/db/. - **uid** (int) - Optional - Optional user UID. Reads /etc/dconf/db/policy{uid}. ### Returns - **StorageAdapter** - An instance of the StorageAdapter class. ``` -------------------------------- ### run_auto(keys) Source: https://github.com/altlinux/gpupdate/blob/master/API_REFERENCE.md Automatically detects the applier from the first key path and runs it. ```APIDOC ## run_auto(keys) ### Description Automatically detects the applier from the first key path and runs it. ### Parameters - **keys** (list[str]) - Required - Registry key paths to apply. ### Returns - **str or None** - Name of the applier that was run. ``` -------------------------------- ### FrontendPlugin Constructor Signature Source: https://github.com/altlinux/gpupdate/blob/master/API_REFERENCE.md Constructor signature for the FrontendPlugin base class. ```python FrontendPlugin(dict_dconf_db=None, username=None, fs_file_cache=None, registry_path=None) ``` -------------------------------- ### Access Registry Data Source: https://github.com/altlinux/gpupdate/blob/master/PLUGIN_DEVELOPMENT_GUIDE.md Retrieve configuration data from the registry using the specified path. ```python self.config = self.get_dict_registry('Software/BaseALT/Policies/Example') ``` -------------------------------- ### Run Applier Automatically Source: https://github.com/altlinux/gpupdate/blob/master/API_REFERENCE.md Automatically detect and execute the correct applier based on the provided registry key paths. ```python runner = ApplierRunner(data=my_dict) name = runner.run_auto([ 'Software/BaseALT/Policies/Control/sshd-gssapi-auth', ]) print(name) # 'control' ``` -------------------------------- ### Define an applier_frontend Implementation Source: https://github.com/altlinux/gpupdate/blob/master/API_REFERENCE.md Abstract base class structure for policy appliers requiring an implementation of the apply method. ```python class applier_frontend(ABC): def __init__(self, regobj): pass @abstractmethod def apply(self, **kwargs): '''Apply policies. Optionally return ApplierResult for status reporting.''' raise NotImplementedError ``` -------------------------------- ### Run ApplierRunner with auto-detection Source: https://github.com/altlinux/gpupdate/blob/master/EXAMPLES.md Automatically detects the appropriate applier based on the provided key paths. ```python from gpoa_lib import ApplierRunner runner = ApplierRunner(data={ 'Software/BaseALT/Policies/Control': {'sshd-gssapi-auth': '1'}, }) name = runner.run_auto([ 'Software/BaseALT/Policies/Control/sshd-gssapi-auth', ]) print(name) # 'control' ``` -------------------------------- ### write_keys(keys_dict) Source: https://github.com/altlinux/gpupdate/blob/master/API_REFERENCE.md Writes a flat dictionary of registry paths to the database INI file. ```APIDOC ## write_keys(keys_dict) ### Description Writes a flat dictionary {full_path: value} where paths are split at the last '/' into section and key. ### Parameters - **keys_dict** (dict) - Required - Flat dictionary mapping full registry paths to values. ``` -------------------------------- ### Utility Functions Source: https://github.com/altlinux/gpupdate/blob/master/API_REFERENCE.md A collection of helper functions for system and user operations. ```APIDOC ## Utility Functions ### Functions - **get_machine_name()** -> str: Get the machine NetBIOS name. - **is_machine_name(name: str)** -> bool: Check if a name is the machine name. - **get_homedir(username: str)** -> str: Get user's home directory path. - **get_user_info(username: str)** -> pwd.struct_passwd: Get passwd entry (cached). - **homedir_exists(username: str)** -> bool: Check home directory exists. - **mk_homedir_path(username: str, path: str)** -> None: Create subdirectory in user's home. - **string_to_literal_eval(string_: str)** -> any: Safely evaluate a string literal. - **get_uid_by_username(username: str)** -> int: Resolve username to UID. - **runcmd(command_name: list)** -> (int, str): Run a command, return (rc, stdout). - **traverse_dir(root_dir: str)** -> list[str]: Recursively list files. - **utc_to_local(utc_str: str)** -> str: Convert UTC timestamp to local time. ``` -------------------------------- ### Write Policy Data with StorageWriter Source: https://github.com/altlinux/gpupdate/blob/master/README.md Utility for writing policy keys to dconf databases and compiling them. ```python from gpoa_lib import StorageWriter writer = StorageWriter('local') writer.write_keys({ 'Software/BaseALT/Policies/Control/sshd-gssapi-auth': '1', }) writer.compile() ``` -------------------------------- ### Run Plugin from dconf Database Source: https://github.com/altlinux/gpupdate/blob/master/EXAMPLES.md Executes a plugin using data loaded from a specific dconf database. ```python import sys sys.path.insert(0, '/usr/lib/gpoa/plugins') from gpoa_lib import StorageAdapter from udev_applier import UdevApplier storage = StorageAdapter.from_dconf_db('my_custom_db') plugin = UdevApplier(storage.get_dict()) plugin.apply() ``` -------------------------------- ### Resolve Applier Name Source: https://github.com/altlinux/gpupdate/blob/master/API_REFERENCE.md Determine the appropriate applier name based on a registry key path or prefix. ```python >>> ApplierRunner.resolve('Software/BaseALT/Policies/Control/sshd-gssapi-auth') 'control' >>> ApplierRunner.resolve('Software/Policies/Mozilla/Firefox') 'firefox' >>> ApplierRunner.resolve('Software/Unknown/Path') None ``` -------------------------------- ### Check ApplierRunner creation result Source: https://github.com/altlinux/gpupdate/blob/master/EXAMPLES.md Attempts to create an applier instance and applies it if successful. ```python from gpoa_lib import ApplierRunner runner = ApplierRunner(data={}) result = runner.create('control') if result: applier = result.data applier.apply() else: print(f'Could not create: {result.error}') ``` -------------------------------- ### get_entry(path, preg=True) Source: https://github.com/altlinux/gpupdate/blob/master/API_REFERENCE.md Retrieves a single entry or raw value from the registry. Backslashes in the path are normalized. ```APIDOC ## get_entry(path, preg=True) ### Description Get a single entry or raw value. ### Parameters - **path** (str) - Required - Full registry path. Backslashes are normalised. - **preg** (bool) - Optional - If `True` (default), return a `PregDconf`. If `False`, return the raw value. ### Returns - `PregDconf` | any | `None` ``` -------------------------------- ### Construct DynamicAttributes Source: https://github.com/altlinux/gpupdate/blob/master/API_REFERENCE.md Instantiate the DynamicAttributes container using keyword arguments. ```python DynamicAttributes(**kwargs) ``` -------------------------------- ### Resolve applier name from key path Source: https://github.com/altlinux/gpupdate/blob/master/EXAMPLES.md Maps a policy key path to its corresponding applier name. ```python from gpoa_lib import ApplierRunner name = ApplierRunner.resolve('Software/BaseALT/Policies/Control/sshd-gssapi-auth') print(name) # 'control' name = ApplierRunner.resolve('Software/Policies/Mozilla/Firefox') print(name) # 'firefox' ``` -------------------------------- ### Run Plugin from dconf Database with Prefix Filter Source: https://github.com/altlinux/gpupdate/blob/master/EXAMPLES.md Filters dconf database entries by a specific prefix before passing to the plugin. ```python import sys sys.path.insert(0, '/usr/lib/gpoa/plugins') from gpoa_lib import StorageAdapter from udev_applier import UdevApplier storage = StorageAdapter.from_dconf_db_prefix( 'my_custom_db', prefix='Software/BaseALT/Policies/Udev', ) plugin = UdevApplier(storage.get_dict()) plugin.apply() ``` -------------------------------- ### Write to local database using StorageWriter Source: https://github.com/altlinux/gpupdate/blob/master/EXAMPLES.md Writes specific key-value pairs to a local database and compiles the changes. ```python from gpoa_lib import StorageWriter writer = StorageWriter('local') writer.write_keys({ 'Software/BaseALT/Policies/Control/sshd-gssapi-auth': '1', 'Software/BaseALT/Policies/Control/ssh-gssapi-auth': 'enabled', }) writer.compile() ``` -------------------------------- ### Measure execution time Source: https://github.com/altlinux/gpupdate/blob/master/EXAMPLES.md Uses the TimedExecution context manager to track and print the duration of an applier run. ```python from gpoa_lib import ApplierRunner from gpoa_lib.util.timing import TimedExecution runner = ApplierRunner(data=my_dict) with TimedExecution('control') as t: result = runner.run('control') print(f'{t.name}: {t.elapsed:.3f}s') ``` -------------------------------- ### Extract Strings for Translation Source: https://github.com/altlinux/gpupdate/blob/master/PLUGIN_DEVELOPMENT_GUIDE.md Use xgettext to extract translatable strings from the plugin source code. ```bash # Extract strings from plugin code xgettext -d my_plugin -o my_plugin.po my_plugin.py ``` -------------------------------- ### StorageAdapter Source: https://github.com/altlinux/gpupdate/blob/master/README.md Provides low-level access to policy data stored in dconf or dictionaries. ```APIDOC ## StorageAdapter ### Description Low-level access to policy data from dconf or dict sources. ### Methods - **from_dconf_db(db_name)**: Creates an adapter from a dconf database. - **from_dict(data)**: Creates an adapter from a dictionary. - **get_dict()**: Returns the raw dictionary data. - **filter_hklm_entries(path)**: Queries specific entries under a path. - **get_key_value(key_path)**: Retrieves the value for a specific key path. ``` -------------------------------- ### Force from dict with auto-resolve Source: https://github.com/altlinux/gpupdate/blob/master/EXAMPLES.md Use ApplierRunner with a dictionary input to force policy application with auto-resolution. ```python from gpoa_lib import ApplierRunner runner = ApplierRunner(data={ 'Software/BaseALT/Policies/KDE': {'kwinrc': '1'}, }, force=True) result = runner.run('kde') ``` -------------------------------- ### list_appliers() Source: https://github.com/altlinux/gpupdate/blob/master/API_REFERENCE.md Returns the list of available applier names. ```APIDOC ## list_appliers() ### Description Returns the list of available applier names. ### Returns - **list[str]** ``` -------------------------------- ### Manage Policies with ApplierRunner Source: https://github.com/altlinux/gpupdate/blob/master/README.md High-level facade for executing policy appliers from dconf databases or dictionaries. ```python from gpoa_lib import ApplierRunner # From a dconf database runner = ApplierRunner(db_name='mydb') result = runner.run('control') if not result: print('Error:', result.error) # From a plain dict (no dconf needed) runner = ApplierRunner(data={ 'Software/BaseALT/Policies/Control': { 'sshd-gssapi-auth': '1', } }) runner.run('control') # Auto-detect applier from key path runner.run_auto(['Software/BaseALT/Policies/Control/sshd-gssapi-auth']) # Force re-apply from a specific database runner = ApplierRunner(db_name='policy', force=True) runner.run('control') # List available appliers print(ApplierRunner.list_appliers()) # Resolve applier name from key path print(ApplierRunner.resolve('Software/BaseALT/Policies/Control/sshd')) ``` -------------------------------- ### Run ApplierRunner from dictionary Source: https://github.com/altlinux/gpupdate/blob/master/EXAMPLES.md Executes an applier using data provided directly via a dictionary, bypassing dconf. ```python from gpoa_lib import ApplierRunner runner = ApplierRunner(data={ 'Software/BaseALT/Policies/Control': { 'sshd-gssapi-auth': '1', 'writeable': '0', } }) runner.run('control') ``` -------------------------------- ### check_enable_key(key) Source: https://github.com/altlinux/gpupdate/blob/master/API_REFERENCE.md Checks if a registry key value is considered 'truthy' (e.g., 'true', 'yes', 'enabled', '1'). ```APIDOC ## check_enable_key(key) ### Description Check whether a registry key is "truthy". Recognises string values `True`, `true`, `TRUE`, `yes`, `Yes`, `enabled`, `enable`, `Enabled`, `Enable`, `1` and non-zero integers. ### Returns - `bool` ``` -------------------------------- ### Run ApplierRunner with custom prefix Source: https://github.com/altlinux/gpupdate/blob/master/EXAMPLES.md Configures ApplierRunner to look for policies under a specific dconf path prefix. ```python from gpoa_lib import ApplierRunner runner = ApplierRunner(db_name='mydb') # Looks under: Software/MyOrg/Policies/Control (applier name appended) runner.run('control', prefix='Software/MyOrg/Policies') ``` -------------------------------- ### Returning Execution Status with ApplierResult Source: https://github.com/altlinux/gpupdate/blob/master/PLUGIN_DEVELOPMENT_GUIDE.md Use ApplierResult to track the status of individual items during plugin execution. This approach is preferred over returning simple booleans for better observability. ```python from gpoa_lib import ApplierResult, ItemStatus class MyPlugin(FrontendPlugin): def run(self, **kwargs): items = [] try: # apply logic... items.append(ItemStatus(key='ssh', action='set', result='success')) except Exception as exc: items.append(ItemStatus(key='ssh', action='set', result='failed', detail=str(exc))) return ApplierResult.applied('my_plugin', items) ``` -------------------------------- ### Measure execution time with TimedExecution Source: https://github.com/altlinux/gpupdate/blob/master/API_REFERENCE.md Use as a context manager to track the duration of a block of code. The elapsed time is accessible via the instance attribute after the block completes. ```python from gpoa_lib.util.timing import TimedExecution with TimedExecution('my_operation') as t: do_work() print(f'{t.name}: {t.elapsed:.3f}s') ``` -------------------------------- ### ApplierRunner Source: https://github.com/altlinux/gpupdate/blob/master/README.md A high-level facade for executing policy appliers from dconf databases or dictionaries. ```APIDOC ## ApplierRunner ### Description High-level facade for running policy appliers. It supports execution from dconf databases or plain dictionaries. ### Methods - **ApplierRunner(db_name=None, data=None, force=False)**: Initializes the runner. - **run(applier_name)**: Executes a specific policy applier. - **run_auto(key_paths)**: Auto-detects and runs the appropriate applier based on key paths. - **list_appliers()**: Returns a list of available appliers. - **resolve(key_path)**: Resolves an applier name from a given key path. ``` -------------------------------- ### Run ApplierRunner with specific keys Source: https://github.com/altlinux/gpupdate/blob/master/EXAMPLES.md Restricts the ApplierRunner operation to a defined list of dconf keys. ```python from gpoa_lib import ApplierRunner runner = ApplierRunner(db_name='mydb') runner.run('control', keys=[ 'Software/BaseALT/Policies/Control/sshd-gssapi-auth', 'Software/BaseALT/Policies/Control/writeable', ]) ``` -------------------------------- ### StorageAdapter.from_dconf_db_prefix Source: https://github.com/altlinux/gpupdate/blob/master/API_REFERENCE.md Loads policy data from a dconf database, filtering to keep only keys under a specific prefix. ```APIDOC ## StorageAdapter.from_dconf_db_prefix(db_name, prefix, uid=None) ### Description Load from a dconf database and keep only keys under the given prefix. ### Parameters - **db_name** (str) - Required - Database filename under /etc/dconf/db/. - **prefix** (str) - Required - Registry path prefix to filter by. - **uid** (int) - Optional - Optional user UID. ### Returns - **StorageAdapter** - An instance of the StorageAdapter class. ``` -------------------------------- ### write(data) Source: https://github.com/altlinux/gpupdate/blob/master/API_REFERENCE.md Writes a nested dictionary of sections and keys to the database INI file. ```APIDOC ## write(data) ### Description Merges a nested dictionary {section: {key: value}} into the database INI file. ### Parameters - **data** (dict) - Required - Nested dictionary of sections and key-value pairs. ``` -------------------------------- ### StorageWriter Source: https://github.com/altlinux/gpupdate/blob/master/README.md Utility for writing policy data to dconf databases. ```APIDOC ## StorageWriter ### Description Writes policy data to arbitrary dconf databases. ### Methods - **StorageWriter(db_name)**: Initializes the writer for a specific database. - **write_keys(data_dict)**: Writes a dictionary of keys to the database. - **compile()**: Compiles the written keys into the database. ``` -------------------------------- ### Filter HKLM registry entries Source: https://github.com/altlinux/gpupdate/blob/master/API_REFERENCE.md Retrieves a list of PregDconf objects matching a specific registry path prefix. ```python for entry in adapter.filter_hklm_entries('Software/BaseALT/Policies/Control'): print(entry.keyname, entry.valuename, entry.data) ``` -------------------------------- ### Implement DualContextApplier subclass Source: https://github.com/altlinux/gpupdate/blob/master/API_REFERENCE.md Define a custom applier by inheriting from DualContextApplier and overriding the context-specific apply methods. ```python from gpoa_lib import DualContextApplier class my_applier_user(DualContextApplier): def __init__(self, storage, username): self.storage = storage self.username = username def admin_context_apply(self): # runs as root pass def user_context_apply(self): # runs with user privileges pass ```