===================
/etc/tklbam/hooks.d
===================

------------
TKLBAM Hooks
------------

:Author: Liraz Siri <liraz@turnkeylinux.org>
:Date:   2013-08-26
:Manual section: 5
:Manual group: backup


DESCRIPTION
===========

TKLBAM has a nifty, general purpose hooks mechanism you can use to trigger
useful actions on backup and restore.

Things you might want to use hooks for:

- Cleaning up temporary files
- Stopping/starting services to increase data consistency
- Encoding/decoding data from non-supported databases
- Using LVM to create/restore a snapshot of a fast changing volume

Hooks are located at /etc/tklbam/hooks.d

Only executable hooks are executed. To enable a hook::

    chmod +x /etc/tklbam/hooks.d/example

Outline of hook invocation
==========================

Tip: try enabling the example hook and examine the backup or restore console
output to see where the hook is executed.

Outline of hook invocation in backup process::

    "pre" hook
    tklbam creates "extras" (backup metadata)
    "inspect" hook: current working directory is /TKLBAM
    tklbam runs duplicity to create/update backup archives
    "post" hook

Outline of hook invocation in restore process::

    "pre" hook
    tklbam runs duplicity to get extras (backup metadata) + overlay
    "inspect" hook: current working directory is /tmp/<random-archive-path>/TKLBAM
    tklbam applies restore to system
    "post" hook

Hook context and profile capabilities
=====================================

For opted-in profiles, ``TKLBAM_BACKUP_CONTEXT`` is a versioned JSON object containing
boolean ``skip_files``, ``skip_database``, ``skip_packages``, ``simulate`` and
``resume`` fields and an ``overrides`` array. During an opted-in restore,
``TKLBAM_RESTORE_CONTEXT`` has the same skip and simulate fields and a
``limits`` array and boolean ``no_rollback``. Hooks can reject combinations they cannot safely handle
before making changes.

A profile can opt into capabilities with a signed, non-executable
``hooks.d/capabilities.json``. For example::

    {"strict_postgresql": true, "failure_hook": true,
     "operation_lock": "chatwoot", "preflight_hook": true,
     "protected_paths": ["/var/lib/turnkey-chatwoot-public"]}

The adjacent detached signature must verify against the packaged profile
keyring. Each property is optional. Strict PostgreSQL mode propagates
individual database restore errors; profile hooks must separately verify any
required roles and credentials. The operation lock serializes backup and
restore for profiles using the same lock name. Protected paths and their
ancestors remain unchanged during file restore. Verified capability values are
available as JSON in ``TKLBAM_BACKUP_CAPABILITIES`` or
``TKLBAM_RESTORE_CAPABILITIES``.

When failure notification is enabled, signed profile hooks receive
``backup failure`` or ``restore failure`` after the corresponding operation
raises after entering its pre-hook. Signed profile hooks receive
``restore preflight`` when ``preflight_hook`` is enabled, after the extract is
available but before a rollback directory is created. The working directory is
the extract extras directory. A nonzero result stops the restore before that
allocation. This phase is not called for profiles that do not opt in. An
opted-in simulation does not allocate or replace rollback state. Local hooks retain their existing
phases. A forced process termination or system failure can prevent
notification, so recovery state must be durable. The existing ``restore post``
phase runs after successful restore only.

Example hook
============

:: 

    #!/bin/bash -e
    # This is a disabled hook example. 
    # To enable, make it executable: chmod +x /etc/tklbam/hooks.d/example

    # hooks are always called with two arguments
    op=$1
    state=$2

    if [ "$op" = "restore" ]; then
        echo -n "A restore operation called this hook "
    elif [ "$op" = "backup" ]; then
        echo -n "A backup operation called this hook "
    fi

    if [ "$state" = "pre" ]; then
        echo "BEFORE $op started"
    elif [ "$state" = "inspect"]; then

        if [ "$op" = "restore" ]; then
            echo -n "Inspect hook runs after duplicity downloaded backup archive. extras path = $(pwd)"
        elif [ "$op" = "backup" ]; then
            echo -n "Inspect hook runs before duplicity uploads backup archive. extras path = $(pwd)"
        fi

    elif [ "$state" = "post" ]; then
        echo "AFTER $op finished"
    fi

    # `false` returns a non-zero exitcode
    # Uncomment the next line to raise an error

    #false

Default hooks
=============

- /etc/tklbam/hooks.d/fixclock: activated by default, this hooks uses ntpdate
  to sync the clock, to prevent duplicity from ignoring backup archives "from
  the future".

- /etc/tklbam/hooks.d/example: disabled by default. When enabled this hook
  prints out "debugging" messages showing where the hook is being executed.
  This is designed to illustrate how tklbam hooks work.

Signed rollback participants
============================

A profile that needs native application rollback can add a
``rollback_participant`` object to its signed capabilities, with a ``name``
matching one executable profile hook and its lowercase ``sha256`` digest.
It must also opt into ``preflight_hook`` and ``operation_lock``. The signed
preflight must validate the backup and reject unsupported partial selections.
A real restore requires rollback enabled. TKLBAM retains the signed capability
and matching hook in its protected rollback directory and calls that hook with
``restore prepare`` before applying generic changes. ``TKLBAM_ROLLBACK_DIR``
identifies the private participant directory for destination recovery data.
Simulation does not register or prepare a participant.

A rollback participant that owns the appliance's PostgreSQL cluster can set
``native_postgresql`` to true. Its hooks must verify the supported databases and
roles on both appliances and manage their own backup, restore and rollback.
TKLBAM records this mode in the backup and delegates PostgreSQL data entirely
to the participant. Restore requires the signed capability and rejects archives
that contain generic PostgreSQL data. MySQL retains its usual behavior.

The normal rollback command verifies the retained signatures and digest, runs
the generic rollback, and invokes the retained hook with ``restore rollback``.
A failed participant keeps its state for retry. Generic rollback completion is
recorded so a participant retry does not repeat completed generic work. A previous rollback is retained as ``tklbam-rollback.previous`` until the
new restore completes and its completion marker is durable. A later restore
may then replace the completed rollback. If the new restore is interrupted or
fails, both recovery records are retained. Successfully rolling back that
restore makes the previous recovery point available again. The generic rollback
phases retain their existing interruption behavior; an interruption within one
of those phases may require inspection.
