Class: Lich::Util::Update::SnapshotManager

Inherits:
Object
  • Object
show all
Defined in:
documented/common/update/snapshot_manager.rb

Overview

Creates and manages timestamped backups of Lich core files and supports rollback to previous versions.

Snapshots capture lib/, lich.rbw, and core scripts before updates. The manager creates timestamped staging directories and publishes them only after all copies succeed. Failed or interrupted snapshots are cleaned up, preventing incomplete installations. Reverts hold an exclusive lock to prevent concurrent operations and swap files atomically using renames; if the swap fails mid-way, it undoes all changes. A revert whose thread is killed during the swap cannot undo it, potentially leaving the installation partially reverted, but the snapshot itself remains intact for manual recovery.

See Also:

Defined Under Namespace

Classes: RevertRunningError

Constant Summary collapse

CORE_SCRIPTS =

Array of core script file names that are included in snapshots and managed during reverts.

These are the scripts that ship with Lich and are always backed up and restored: alias.lic, autostart.lic, dependency.lic, ewaggle.lic, foreach.lic, go2.lic, infomon.lic, jinx.lic, lnet.lic, log.lic, logxml.lic, map.lic, repository.lic, vars.lic, and version.lic.

Returns:

  • (Array<String>) —

    sorted list of core script file names

%w[
  alias.lic autostart.lic dependency.lic ewaggle.lic foreach.lic
  go2.lic infomon.lic jinx.lic lnet.lic log.lic logxml.lic
  map.lic repository.lic vars.lic version.lic
].freeze
SNAPSHOT_PREFIX =

Prefix of a published, restorable snapshot. #revert only ever considers directories matching "#SNAPSHOT_PREFIX*".

'L5-snapshot-'
STAGING_PREFIX =

Prefix of a snapshot still being copied. Deliberately does not start with SNAPSHOT_PREFIX, so a snapshot that is interrupted part way through is never picked by #revert.

'L5-staging-'
REVERT_TEMP_PREFIX =

Prefix of the hidden working directories #revert creates beside the live lib/, scripts/ and lich.rbw while it restores them.

'.lich5-revert-'
REVERT_LOCK_NAME =

Lock file in BACKUP_DIR. #revert holds it exclusively for its whole run and #snapshot holds it exclusively while it copies (and, for an update, while it downloads and installs), so two reverts never swap files at the same time, a snapshot never copies a lib/ that a revert has half swapped, and two updates never install at the same time.

'.lich5-revert.lock'
STAGED_MARKER_NAME =

Empty file #snapshot writes into the staging directory once every copy has succeeded, just before publishing it. A snapshot without it was taken by an older Lich, which copied straight into L5-snapshot- and could leave it cut short (see #legacy_cut_off).

'.lich5-staged'
MAX_PUBLISH_ATTEMPTS =

How many same-second name collisions #snapshot tolerates before giving up on publishing.

100
RENAME_RETRY_DELAYS =

Seconds to wait before each retry of a rename Windows refused with a transient error (see #rename_with_retry); about 3s in all.

[0.1, 0.2, 0.4, 0.8, 1.6].freeze
TRANSIENT_RENAME_ERRORS =

Errors Windows reports when a rename is refused because another process has the entry, or a file inside it, open.

[Errno::EACCES, Errno::EPERM, Errno::EBUSY].freeze

Instance Method Summary collapse

Instance Method Details

#new_data_backup_dir ⇒ String

Creates a fresh timestamped directory under BACKUP_DIR for a data-only backup (e.g. effect-list.xml with no preceding full update). Deliberately uses a different prefix than SNAPSHOT_PREFIX so #revert's "L5-snapshot-*" glob can never mistake a directory containing only backed-up data files -- no lib/, lich.rbw, or scripts/ -- for a real, restorable ecosystem snapshot.

Update.update_core_data_and_scripts is a public entry point with no guard of its own against concurrent callers (e.g. multiboxed Lich processes autostarting within the same second after an update), so this uses Dir.mktmpdir rather than a bare mkdir_p on a second-resolution timestamp -- two calls in the same second must not resolve to the same directory and silently clobber each other's backup.

Returns:

  • (String) —

    path to the newly created directory



116
117
118
# File 'documented/common/update/snapshot_manager.rb', line 116

def new_data_backup_dir
  Dir.mktmpdir("L5-databackup-#{Time.now.strftime('%Y-%m-%d-%H-%M-%S')}-", BACKUP_DIR)
end

#revert ⇒ void

This method returns an undefined value.

Restores most recent snapshot from BACKUP_DIR.

Refuses, without changing anything, when the newest L5-snapshot-* directory is incomplete (no lib/version.rb declaring LICH_VERSION, no lich.rbw, no scripts/, or, in one an older Lich took, core scripts that may have been cut off part way). It names every incomplete directory newer than the next complete snapshot, and that snapshot if there is one, but never falls back to it on its own: an older snapshot may be several versions back.

Holds the revert lock exclusively for the whole run. If another revert, a snapshot, or an update past its snapshot (see #snapshot) on the same installation holds it, says so and changes nothing.



219
220
221
222
223
224
225
226
227
228
229
230
231
# File 'documented/common/update/snapshot_manager.rb', line 219

def revert
  respond
  respond 'Reverting Lich5 to previously installed version.'

  ran = with_revert_lock(File::LOCK_EX) do
    revert_newest_snapshot
    true
  end
  return if ran

  respond
  respond 'Another revert, a snapshot or an update is running on this installation. Nothing was changed.'
end

#snapshot {|snapshot_dir| ... } ⇒ String, Object

Creates timestamped snapshot of lib/, lich.rbw, and core scripts.

The copies go into a staging directory under BACKUP_DIR whose name #revert ignores. Only once every copy has succeeded is STAGED_MARKER_NAME written into it and it renamed to L5-snapshot-. If a copy fails, the staging directory is removed and the error is re-raised, so the caller's update aborts before changing anything. The staging directory is also removed when the thread is killed (Lich kills the client thread running ;lich5-update when it shuts down), since that clean-up is in an ensure. A process killed mid-copy leaves only an L5-staging-* directory, which #revert never restores from.

Holds the revert lock exclusively while copying and publishing. If a revert, another snapshot or another update on the same installation holds it, says so and raises without copying anything: copying a lib/ in the middle of a revert's swap could publish a mix of two versions that looks complete, and two updates installing at once could leave a mix of both releases.

Given a block, yields the published snapshot's path to it and keeps holding the lock until the block returns, so an update that downloads and installs in the block cannot have a revert swap lib/ under it.

Yield Parameters:

  • snapshot_dir (String) —

    path to the published snapshot

Returns:

  • (String, Object) —

    path to the published snapshot directory, or the block's value when given a block

Raises:

  • (SystemCallError) —

    if any copy fails; no snapshot is published

  • (RevertRunningError) —

    if a revert, snapshot or update is running; nothing is copied



151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
# File 'documented/common/update/snapshot_manager.rb', line 151

def snapshot
  respond
  respond 'Creating a snapshot of current Lich core files ONLY.'
  respond
  respond 'You may also wish to copy your entire Lich5 folder to'
  respond 'another location for additional safety, after any'
  respond 'additional requested updates are completed.'

  FileUtils.mkdir_p(BACKUP_DIR)
  snapshot_subdir = nil
  result = nil
  locked = with_revert_lock(File::LOCK_EX) do
    # Interrupts are deferred except while copying and publishing, so
    # a kill can never land between creating the staging directory
    # and the ensure that removes it.
    Thread.handle_interrupt(Object => :never) do
      staging_dir = Dir.mktmpdir(STAGING_PREFIX, BACKUP_DIR)
      begin
        Thread.handle_interrupt(Object => :immediate) do
          # Dir.mktmpdir creates 0700; a published snapshot keeps the
          # permissions a plain mkdir would have given it.
          File.chmod(0o777 & ~File.umask, staging_dir)
          copy_core_files(staging_dir)
          File.write(File.join(staging_dir, STAGED_MARKER_NAME), '')
          snapshot_subdir = publish_snapshot(staging_dir)
        end
      rescue StandardError => e
        respond
        respond "Snapshot failed (#{e.class}: #{e.message})."
        respond 'No snapshot was saved and nothing was changed.'
        raise
      ensure
        # Once published, staging_dir no longer exists, so this only
        # ever removes this call's own unpublished copy.
        FileUtils.rm_rf(staging_dir) unless snapshot_subdir
      end
    end

    respond
    respond 'Current Lich ecosystem files (only) backed up to:'
    respond "    #{snapshot_subdir}"

    result = block_given? ? yield(snapshot_subdir) : snapshot_subdir
    true
  end
  return result if locked

  respond
  respond 'Another update, snapshot or revert is running on this installation, so no snapshot was saved and nothing was changed.'
  respond 'Run the command again once it has finished.'
  raise RevertRunningError, 'another update, snapshot or revert is running on this installation'
end