litebackup 1.3.0-x86_64-linux-musl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,142 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "litebackup"
4
+ require "rails/railtie"
5
+ require_relative "sqlite_file"
6
+
7
+ module Litebackup
8
+ module Integrations
9
+ # Registers continuous backups of a Rails app's SQLite databases when the
10
+ # app boots. Require it from config/application.rb, after Rails, and
11
+ # name the databases to back up:
12
+ #
13
+ # require "litebackup/integrations/rails"
14
+ #
15
+ # config.litebackup.databases = { primary: {}, queue: { name: "app/queue.sqlite" } }
16
+ #
17
+ # Each name is a database of the environment's config/database.yml,
18
+ # the Solid Queue, Cache, and Cable databases included; its options are
19
+ # backups.start's: name, prefix, maximum_local_databases,
20
+ # offload_durability, and offload_rollback_journal. The client takes
21
+ # api_key, session, socket_path, and binary_path from config.litebackup
22
+ # too. enabled is false in the test environment and in Rake tasks
23
+ # (assets:precompile, db:migrate), and true otherwise: the server, the
24
+ # console, and bin/jobs.
25
+ #
26
+ # Before the first migration, when a database file does not exist yet,
27
+ # it is created empty, the database SQLite would create on first
28
+ # connect, when its directory exists. Registration runs once each time
29
+ # the app initializes: once in Puma's master when it preloads the app
30
+ # before forking its workers, in each worker when it does not, and once
31
+ # in bin/jobs. backups.start returns the saved rule when the same
32
+ # settings were registered before, so every such boot registers again
33
+ # safely; changed settings raise rule_exists at boot.
34
+ # The integration never shuts the daemon down.
35
+ class Railtie < ::Rails::Railtie
36
+ # A config.litebackup setting that cannot be registered; boot stops with it.
37
+ class ConfigurationError < StandardError; end
38
+
39
+ CLIENT_KEYS = %i[api_key session socket_path binary_path].freeze
40
+ START_KEYS = %i[name prefix maximum_local_databases offload_durability offload_rollback_journal].freeze
41
+ SETTING_KEYS = (%i[databases enabled] + CLIENT_KEYS).freeze
42
+
43
+ config.litebackup = ActiveSupport::OrderedOptions.new
44
+ config.litebackup.databases = {}
45
+
46
+ config.after_initialize do |app|
47
+ Railtie.register_backups(app.config.litebackup, ::Rails.env, ::Rails.root)
48
+ end
49
+
50
+ class << self
51
+ # Whether boot registers backups: enabled when set, otherwise false in
52
+ # the test environment and during Rake tasks.
53
+ def enabled?(settings, environment)
54
+ return settings[:enabled] == true unless settings[:enabled].nil?
55
+ return false if environment == "test"
56
+
57
+ !(defined?(::Rake.application) && ::Rake.application.top_level_tasks.any?)
58
+ end
59
+
60
+ # Starts the backup of each named database with a client that closes once they are saved.
61
+ def register_backups(settings, environment, root)
62
+ return unless enabled?(settings, environment)
63
+
64
+ databases = settings[:databases] || {}
65
+ return if databases.empty?
66
+
67
+ unknown = settings.keys.map(&:to_sym) - SETTING_KEYS
68
+ unless unknown.empty?
69
+ raise ConfigurationError,
70
+ "config.litebackup has unknown keys: #{unknown.sort.join(", ")}"
71
+ end
72
+
73
+ registrations = databases.map do |database_name, options|
74
+ [database_file(database_name.to_s, environment, root), start_options(database_name, options)]
75
+ end
76
+ client_options = CLIENT_KEYS.to_h { |key| [key, settings[key]] }.compact
77
+ Litebackup::Client.open(**client_options) do |client|
78
+ registrations.each do |path, options|
79
+ client.backups.start(path, **options)
80
+ rescue Litebackup::Error => e
81
+ raise ConfigurationError, "registering the backup of #{path} failed: #{e.code}: #{e.message}"
82
+ end
83
+ end
84
+ rescue Litebackup::Error => e
85
+ raise ConfigurationError, "config.litebackup: #{e.code}: #{e.message}"
86
+ end
87
+
88
+ def start_options(database_name, options)
89
+ options = (options || {}).to_h.transform_keys(&:to_sym)
90
+ extra = options.keys - START_KEYS
91
+ unless extra.empty?
92
+ raise ConfigurationError,
93
+ "config.litebackup.databases: #{database_name} has unknown keys: #{extra.sort.join(", ")}"
94
+ end
95
+
96
+ options
97
+ end
98
+
99
+ # The file a configured SQLite database opens, created empty when it
100
+ # does not exist yet; refuses other adapters and in-memory and test databases.
101
+ def database_file(database_name, environment, root)
102
+ database_config = ::ActiveRecord::Base.configurations.configs_for(env_name: environment, name: database_name,
103
+ include_hidden: true)
104
+ if database_config.nil?
105
+ raise ConfigurationError,
106
+ "config.litebackup.databases: #{database_name} is not a database of the #{environment} environment"
107
+ end
108
+ unless database_config.adapter == "sqlite3"
109
+ raise ConfigurationError, "config.litebackup.databases: #{database_name} uses the " \
110
+ "#{database_config.adapter} adapter; only SQLite files are backed up"
111
+ end
112
+ if environment == "test"
113
+ raise ConfigurationError,
114
+ "config.litebackup.databases: #{database_name} is a test database, which is not backed up"
115
+ end
116
+
117
+ path = begin
118
+ SQLiteFile.database_file(database_config.database.to_s, root.to_s)
119
+ rescue Litebackup::Error => e
120
+ raise ConfigurationError, "config.litebackup.databases: #{database_name}: #{e.message}"
121
+ end
122
+ create_empty_database(database_name, path)
123
+ path
124
+ end
125
+
126
+ # Before the first migration there is no file yet. An empty file is
127
+ # the empty database SQLite would create on first connect, and the
128
+ # daemon backs it up from its first write.
129
+ def create_empty_database(database_name, path)
130
+ unless File.directory?(File.dirname(path))
131
+ raise ConfigurationError,
132
+ "config.litebackup.databases: #{database_name}: the directory of #{path} does not exist"
133
+ end
134
+
135
+ File.open(path, File::CREAT | File::EXCL | File::WRONLY, 0o644, &:close)
136
+ rescue Errno::EEXIST
137
+ nil
138
+ end
139
+ end
140
+ end
141
+ end
142
+ end
@@ -0,0 +1,55 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "sqlite3"
4
+ require "litebackup"
5
+ require_relative "sqlite_file"
6
+
7
+ module Litebackup
8
+ module Integrations
9
+ # The sqlite3 gem: the file a database has open, and a pool adapter.
10
+ #
11
+ # require "litebackup/integrations/sqlite3"
12
+ #
13
+ # db = SQLite3::Database.new("data/app.sqlite")
14
+ # litebackup.backups.start(Litebackup::Integrations::SQLite3.database_path(db))
15
+ module SQLite3
16
+ # Opens existing files with SQLite3::Database.new(path, flags: READWRITE,
17
+ # **options), which never creates one; a missing file raises
18
+ # Litebackup::Error with code not_found. Closing rolls back a
19
+ # transaction the block left open, never commits it, and closes the
20
+ # database. Commit what the block should keep.
21
+ class Adapter
22
+ include Litebackup::Adapter
23
+
24
+ def initialize(options)
25
+ @options = options.dup.freeze
26
+ end
27
+
28
+ def open(path)
29
+ SQLiteFile.require_existing_file(path)
30
+ ::SQLite3::Database.new(path, **@options, flags: ::SQLite3::Constants::Open::READWRITE)
31
+ end
32
+
33
+ def close(handle)
34
+ handle.rollback if handle.transaction_active?
35
+ ensure
36
+ handle.close
37
+ end
38
+ end
39
+
40
+ module_function
41
+
42
+ # The absolute path of the file a database has open, or of an attached
43
+ # database. Reads PRAGMA database_list, which starts no transaction.
44
+ # Raises invalid_argument for in-memory and temporary databases.
45
+ def database_path(database, schema = "main")
46
+ SQLiteFile.file_from_database_list(database.execute("PRAGMA database_list"), schema)
47
+ end
48
+
49
+ # A pool adapter; options go to SQLite3::Database.new, such as results_as_hash: true.
50
+ def adapter(**options)
51
+ Adapter.new(options)
52
+ end
53
+ end
54
+ end
55
+ end
@@ -0,0 +1,81 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "uri"
4
+
5
+ module Litebackup
6
+ module Integrations
7
+ # SQLite filenames and file: URIs, resolved as sqlite3ParseUri does.
8
+ module SQLiteFile
9
+ NO_FILE = "an in-memory or temporary database has no file to back up; open it from a path"
10
+
11
+ module_function
12
+
13
+ # The absolute file a file: URI opens, against base for a relative path.
14
+ def file_from_uri(uri, base = Dir.pwd)
15
+ rest = uri.delete_prefix("file:")
16
+ if rest.start_with?("//")
17
+ authority_end = rest.index(%r{[/?#]}, 2) || rest.length
18
+ authority = rest[2...authority_end]
19
+ unless ["", "localhost"].include?(authority)
20
+ raise Litebackup.invalid_argument(
21
+ "SQLite opens only local files, and #{uri.inspect} names host #{authority.inspect}"
22
+ )
23
+ end
24
+
25
+ rest = rest[authority_end..]
26
+ end
27
+ encoded_path, query = rest.split("#", 2).first.split("?", 2)
28
+ pairs = query.to_s.split("&").reject(&:empty?).map do |part|
29
+ part.split("=", 2).map do |text|
30
+ decode(text.to_s)
31
+ end
32
+ end
33
+ raise Litebackup.invalid_argument(NO_FILE) if pairs.include?(%w[mode memory]) || pairs.include?(%w[vfs memdb])
34
+
35
+ plain_file(decode(encoded_path.to_s), base)
36
+ end
37
+
38
+ # SQLite URI percent-decoding; unlike a form, + stays +.
39
+ def decode(text)
40
+ URI.decode_uri_component(text)
41
+ end
42
+
43
+ # The absolute file a plain SQLite filename opens; "" and ":memory:" open none.
44
+ def plain_file(filename, base = Dir.pwd)
45
+ raise Litebackup.invalid_argument(NO_FILE) if ["", ":memory:"].include?(filename)
46
+
47
+ Wire.absolute_path(filename.start_with?("/") ? filename : File.join(base, filename))
48
+ end
49
+
50
+ # The file of a SQLite filename or file: URI.
51
+ def database_file(filename, base = Dir.pwd)
52
+ filename.start_with?("file:") ? file_from_uri(filename, base) : plain_file(filename, base)
53
+ end
54
+
55
+ # The file of one schema in PRAGMA database_list entries of seq, name, and file.
56
+ def file_from_database_list(entries, schema)
57
+ entries.each do |entry|
58
+ seq_name_file = entry.is_a?(Hash) ? [entry["seq"], entry["name"], entry["file"]] : entry
59
+ next unless seq_name_file[1] == schema
60
+
61
+ file = seq_name_file[2]
62
+ unless file.is_a?(String) && !file.empty?
63
+ raise Litebackup.invalid_argument(
64
+ "the database #{schema.inspect} is in memory or temporary and has no file to back up"
65
+ )
66
+ end
67
+
68
+ return file
69
+ end
70
+ raise Litebackup.invalid_argument("no attached database named #{schema.inspect}")
71
+ end
72
+
73
+ # Raises not_found unless something is at path: a pool's adapter opens existing databases only.
74
+ def require_existing_file(path)
75
+ return if File.exist?(path)
76
+
77
+ raise Error.new(ErrorCode::NOT_FOUND, "#{path} does not exist; the adapter opens existing databases only")
78
+ end
79
+ end
80
+ end
81
+ end
@@ -0,0 +1,146 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "socket"
5
+
6
+ module Litebackup
7
+ # Starting a session's daemon with litebackup launch, as the CLI does. The
8
+ # launch command locks the session's launch lock, so concurrent processes
9
+ # start one daemon. Launches are never retried.
10
+ module Launch
11
+ LAUNCH_TIMEOUT_SECONDS = 30.0
12
+ # How long a finished command's output pipes may stay open, in a process
13
+ # it started, before reading stops.
14
+ DRAIN_SECONDS = 1.0
15
+
16
+ module_function
17
+
18
+ # Whether something accepts connections on the socket.
19
+ def socket_listening?(socket_path)
20
+ socket = Socket.new(Socket::AF_UNIX, Socket::SOCK_STREAM)
21
+ address = Socket.pack_sockaddr_un(socket_path)
22
+ begin
23
+ socket.connect_nonblock(address)
24
+ rescue IO::WaitWritable
25
+ return false if socket.wait_writable(1.0).nil?
26
+
27
+ begin
28
+ socket.connect_nonblock(address)
29
+ rescue Errno::EISCONN
30
+ nil
31
+ end
32
+ end
33
+ true
34
+ rescue SystemCallError, ArgumentError
35
+ false
36
+ ensure
37
+ socket&.close
38
+ end
39
+
40
+ # The launch command line and its environment.
41
+ def launch_command(session, environment, api_key, binary_path)
42
+ binary = Binary.litebackup_binary(environment, binary_path)
43
+ launch_environment = environment.merge(BINARY_PATH_ENVIRONMENT => binary)
44
+ launch_environment[API_KEY_ENVIRONMENT] = api_key unless api_key.nil?
45
+ [[binary, "launch", "--session", session, "--stdout-format", "json"], launch_environment]
46
+ end
47
+
48
+ # The code and message of the last error the launch command reported as
49
+ # JSON: drain_required when the launch refused a new credential for a
50
+ # client that has write locks, and launch_failed otherwise, also with the
51
+ # whole output when the command reported no error as JSON.
52
+ def launch_refusal(output)
53
+ refusal = ""
54
+ refusal_code = ErrorCode::LAUNCH_FAILED
55
+ output.each_line do |line|
56
+ diagnostic = begin
57
+ JSON.parse(line)
58
+ rescue JSON::ParserError
59
+ next
60
+ end
61
+ # A warning carries an event; an error does not.
62
+ next unless diagnostic.is_a?(Hash) && !diagnostic.key?("event") && diagnostic["code"].is_a?(String)
63
+
64
+ message = diagnostic["message"]
65
+ next unless message.is_a?(String) && !message.empty?
66
+
67
+ refusal = message
68
+ refusal_code = diagnostic["code"] == ErrorCode::DRAIN_REQUIRED ? ErrorCode::DRAIN_REQUIRED : ErrorCode::LAUNCH_FAILED
69
+ end
70
+ return [ErrorCode::LAUNCH_FAILED, output.strip] if refusal.empty?
71
+
72
+ [refusal_code, refusal]
73
+ end
74
+
75
+ def launch_failed(output, cause)
76
+ code, refusal = launch_refusal(output)
77
+ Error.new(code, "starting Litebackup failed: #{refusal.empty? ? cause : refusal}")
78
+ end
79
+
80
+ # Starts the session daemon when nothing listens on its socket.
81
+ def launch_daemon(session, socket_path, environment, api_key, binary_path)
82
+ return if socket_listening?(socket_path)
83
+
84
+ command, launch_environment = launch_command(session, environment, api_key, binary_path)
85
+ stdout, stderr, status = capture_output(launch_environment, command, LAUNCH_TIMEOUT_SECONDS)
86
+ raise launch_failed("", "litebackup launch did not finish within #{LAUNCH_TIMEOUT_SECONDS.to_i} s") if status.nil?
87
+ return if status.success?
88
+
89
+ raise launch_failed(stderr.empty? ? stdout : stderr, "exit status #{status.exitstatus || status.termsig}")
90
+ end
91
+
92
+ # Starts a command with exactly environment and returns its output and
93
+ # exit status; the status is nil when the command was killed after
94
+ # timeout_seconds. Raises launch_failed when the command cannot start.
95
+ def capture_output(environment, command, timeout_seconds)
96
+ stdout_reader, stdout_writer = IO.pipe
97
+ stderr_reader, stderr_writer = IO.pipe
98
+ begin
99
+ pid = Process.spawn(Launch.exact_environment(environment), *command, in: File::NULL, out: stdout_writer,
100
+ err: stderr_writer)
101
+ rescue SystemCallError => e
102
+ [stdout_reader, stderr_reader].each(&:close)
103
+ raise Error.new(ErrorCode::LAUNCH_FAILED, Binary.start_failure_message(command.first, e))
104
+ ensure
105
+ [stdout_writer, stderr_writer].each(&:close)
106
+ end
107
+ readers = [stdout_reader, stderr_reader].map { |pipe| Thread.new { read_pipe(pipe) } }
108
+ waiter = Process.detach(pid)
109
+ if waiter.join(timeout_seconds).nil?
110
+ begin
111
+ Process.kill(:KILL, pid)
112
+ rescue Errno::ESRCH
113
+ nil
114
+ end
115
+ waiter.join
116
+ status = nil
117
+ else
118
+ status = waiter.value
119
+ end
120
+ outputs = readers.map { |reader| reader.join(DRAIN_SECONDS) ? reader.value.to_s : "" }
121
+ [stdout_reader, stderr_reader].each(&:close)
122
+ readers.each { |reader| reader.join if reader.alive? }
123
+ [outputs[0].force_encoding(Encoding::UTF_8).scrub, outputs[1].force_encoding(Encoding::UTF_8).scrub, status]
124
+ end
125
+
126
+ # A pipe's whole text, or what arrived before another thread closed it.
127
+ def read_pipe(pipe)
128
+ text = +""
129
+ loop { text << pipe.readpartial(65_536) }
130
+ rescue IOError
131
+ text
132
+ end
133
+
134
+ # The environment Process.spawn needs so a command gets environment and
135
+ # nothing else: every variable of this process that environment lacks is
136
+ # unset.
137
+ def exact_environment(environment)
138
+ ENV.keys.to_h { |name| [name, nil] }.merge(environment)
139
+ end
140
+
141
+ # The environment a client resolves paths and starts the daemon with: ENV by default.
142
+ def process_environment(environment)
143
+ (environment.nil? ? ENV.to_h : environment.to_h).transform_keys(&:to_s)
144
+ end
145
+ end
146
+ end
@@ -0,0 +1,86 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "tmpdir"
5
+
6
+ module Litebackup
7
+ # Records a litebackup install service install; root and the service's
8
+ # user use its socket.
9
+ SYSTEM_CONFIGURATION_PATH = "/etc/litebackup/client.json"
10
+
11
+ # Session names and sockets, resolved exactly as the litebackup command does.
12
+ module Paths
13
+ DEFAULT_SESSION = "default"
14
+ SESSION_PATTERN = /\A[a-z0-9][a-z0-9._-]*\z/
15
+
16
+ module_function
17
+
18
+ # The runtime directory and uid a service configuration file names, or nil.
19
+ def runtime_directory(path)
20
+ configuration = JSON.parse(File.read(path))
21
+ return nil unless configuration.is_a?(Hash)
22
+
23
+ directory = configuration["runtime_directory"]
24
+ return nil unless directory.is_a?(String) && !directory.empty?
25
+
26
+ uid = configuration["uid"]
27
+ [directory, uid.is_a?(Integer) ? uid : nil]
28
+ rescue SystemCallError, IOError, JSON::ParserError
29
+ nil
30
+ end
31
+
32
+ # The session name and its socket path.
33
+ #
34
+ # Where litebackup install service ran as root, root and the service's
35
+ # user use the service's socket; where a user installed a service of their
36
+ # own, that user uses the directory it saved. Everyone else uses
37
+ # $XDG_RUNTIME_DIR/litebackup/<session>/client.sock, or a per-user
38
+ # directory under the temporary directory, which must be this user's alone.
39
+ def session_socket(session, environment, system_configuration = SYSTEM_CONFIGURATION_PATH)
40
+ name = [session, environment["LITEBACKUP_SESSION"], DEFAULT_SESSION].find { |value| Wire.supplied?(value) }
41
+ unless SESSION_PATTERN.match?(name)
42
+ raise Litebackup.invalid_argument(
43
+ "session names use [a-z0-9._-] and start with a letter or digit, got #{name.inspect}"
44
+ )
45
+ end
46
+ uid = Process.uid
47
+ system = runtime_directory(system_configuration)
48
+ return [name, File.join(system[0], name, "client.sock")] if system && (uid.zero? || uid == system[1])
49
+
50
+ home = Wire.supplied?(environment["HOME"]) ? environment["HOME"] : Dir.home
51
+ user = runtime_directory(File.join(home, ".config", "litebackup", "service.json"))
52
+ return [name, File.join(user[0], name, "client.sock")] if user
53
+
54
+ runtime_root = environment["XDG_RUNTIME_DIR"]
55
+ unless Wire.supplied?(runtime_root)
56
+ temporary = Wire.supplied?(environment["TMPDIR"]) ? environment["TMPDIR"] : Dir.tmpdir
57
+ runtime_root = File.join(temporary, "litebackup-#{uid}")
58
+ private_runtime_directory(runtime_root, uid)
59
+ end
60
+ [name, File.join(runtime_root, "litebackup", name, "client.sock")]
61
+ end
62
+
63
+ # Makes sure the per-user runtime directory used without $XDG_RUNTIME_DIR
64
+ # is this user's own. The temporary directory is shared, so another local
65
+ # user could create it first and answer as the daemon. It is created with
66
+ # mode 0700 when missing; one that is a symlink, is not a directory,
67
+ # belongs to another user, or is open to anyone else is refused, as the
68
+ # litebackup command refuses it.
69
+ def private_runtime_directory(directory, uid)
70
+ begin
71
+ Dir.mkdir(directory, 0o700)
72
+ rescue Errno::EEXIST
73
+ nil
74
+ rescue SystemCallError => e
75
+ raise Litebackup.invalid_argument("creating #{directory} failed: #{e.message}")
76
+ end
77
+ status = File.lstat(directory)
78
+ return if status.directory? && status.uid == uid && status.mode.nobits?(0o077)
79
+
80
+ raise Litebackup.invalid_argument(
81
+ "#{directory} is not a directory of this user's alone; " \
82
+ "remove it or set XDG_RUNTIME_DIR to this user's own directory"
83
+ )
84
+ end
85
+ end
86
+ end