litebackup 1.3.0-x86_64-darwin

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,520 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Litebackup
4
+ # Talks to the Litebackup daemon of one session over its unix socket,
5
+ # starting it like the CLI does. It connects on first use. Pass a block to
6
+ # Client.open, or call close, which never shuts the daemon down:
7
+ #
8
+ # Litebackup::Client.open do |litebackup|
9
+ # litebackup.backups.start("/var/lib/app/main.sqlite")
10
+ # end
11
+ #
12
+ # A client is safe to share between threads. One made before a fork is
13
+ # refused in the child with invalid_argument; make a new one there, as
14
+ # Puma's workers do after boot.
15
+ class Client
16
+ # What a client was created with, resolved once.
17
+ class Settings
18
+ attr_reader :environment, :api_key, :session, :socket_path, :binary_path, :launch
19
+
20
+ def initialize(api_key:, session:, socket_path:, binary_path:, launch:, environment:)
21
+ @environment = Launch.process_environment(environment)
22
+ @api_key = api_key.nil? ? @environment[API_KEY_ENVIRONMENT] : api_key
23
+ Credential.credential_type(@api_key)
24
+ raise Litebackup.invalid_argument("socket_path needs a path") if socket_path == ""
25
+
26
+ @explicit_socket = !socket_path.nil?
27
+ @binary_path = binary_path
28
+ @launch = launch
29
+ if @explicit_socket
30
+ @session = session
31
+ @socket_path = Wire.path_text(socket_path)
32
+ else
33
+ @session, @socket_path = Paths.session_socket(session, @environment)
34
+ end
35
+ end
36
+
37
+ def explicit_socket?
38
+ @explicit_socket
39
+ end
40
+
41
+ def foreground_command(source, name:, prefix:, durability:, timeout:)
42
+ if explicit_socket?
43
+ raise Litebackup.invalid_argument("foreground backup needs a named session and cannot target socket_path")
44
+ end
45
+
46
+ binary = Binary.litebackup_binary(environment, binary_path)
47
+ Foreground.backup_command(binary, source, session: session, name: name, prefix: prefix,
48
+ durability: durability, timeout: timeout)
49
+ end
50
+
51
+ def foreground_environment
52
+ api_key.nil? ? environment : environment.merge(API_KEY_ENVIRONMENT => api_key)
53
+ end
54
+ end
55
+
56
+ attr_reader :backups, :rules, :databases, :replicas, :events, :session, :failovers
57
+
58
+ # api_key: the credential the daemon uses when it starts: an API key, or a
59
+ # join token it exchanges once for a key of this machine, then @ and the
60
+ # server's address; LITEBACKUP_API_KEY by default, and "" for none. The
61
+ # daemon keeps the key it saved unless this holds a different credential,
62
+ # which the launch refuses with drain_required while the client has write
63
+ # locks; a daemon already running keeps its key until it restarts.
64
+ # Foreground backups use it too.
65
+ # session: the session name; LITEBACKUP_SESSION, then "default".
66
+ # socket_path: connect to this socket and never start a daemon.
67
+ # binary_path: the litebackup binary that starts the daemon; see Litebackup.binary.
68
+ # launch: start the session daemon when it is not running.
69
+ # environment: the environment for resolving paths and starting the daemon; ENV by default.
70
+ def initialize(api_key: nil, session: nil, socket_path: nil, binary_path: nil, launch: true, environment: nil)
71
+ @settings = Settings.new(api_key: api_key, session: session, socket_path: socket_path,
72
+ binary_path: binary_path, launch: launch, environment: environment)
73
+ @transport = Transport.new(@settings.socket_path)
74
+ @owner_pid = Process.pid
75
+ @connect_lock = Mutex.new
76
+ @connected = false
77
+ @closed = false
78
+ @lock = Mutex.new
79
+ @failovers_followed = []
80
+ @jobs = []
81
+ @client_version = ""
82
+ @backups = Backups.new(self)
83
+ @rules = Rules.new(self)
84
+ @databases = Databases.new(self)
85
+ @replicas = Replicas.new(self)
86
+ @events = Events.new(self)
87
+ @session = Session.new(self)
88
+ @failovers = Failovers.new(self)
89
+ end
90
+
91
+ # A client for the block, closed when the block ends; without a block, the client.
92
+ def self.open(**, &block)
93
+ client = new(**)
94
+ return client if block.nil?
95
+
96
+ begin
97
+ block.call(client)
98
+ ensure
99
+ client.close
100
+ end
101
+ end
102
+
103
+ # The daemon's version, from its last answer.
104
+ attr_reader :client_version
105
+
106
+ def socket_path
107
+ @settings.socket_path
108
+ end
109
+
110
+ # The session name, or nil for a client of an explicit socket path.
111
+ def session_name
112
+ @settings.session
113
+ end
114
+
115
+ def closed?
116
+ @closed
117
+ end
118
+
119
+ # Connects, starting the daemon when needed; fails with daemon_unsupported
120
+ # for a daemon older than 1.1.0.
121
+ def connect
122
+ ensure_open
123
+ @connect_lock.synchronize do
124
+ return if @connected
125
+
126
+ settings = @settings
127
+ if !settings.explicit_socket? && settings.launch && settings.session
128
+ Launch.launch_daemon(settings.session, settings.socket_path, settings.environment,
129
+ settings.api_key, settings.binary_path)
130
+ end
131
+ send_call(Wire.connect_probe)
132
+ Wire.check_daemon_version(@client_version, settings.session)
133
+ @connected = true
134
+ end
135
+ end
136
+
137
+ # Stops following failovers, ends running foreground backups, and closes
138
+ # connections. The daemon keeps running, and so do its failovers and
139
+ # acquired databases.
140
+ def close
141
+ failovers, jobs = @lock.synchronize do
142
+ @closed = true
143
+ [@failovers_followed.dup, @jobs.dup]
144
+ end
145
+ # A forked child has neither the followers nor the jobs, and its copies
146
+ # of the parent's connections are closed without ending the parent's calls.
147
+ return @transport.close unless Process.pid == @owner_pid
148
+
149
+ # Closing the transport first ends the calls that wait, the followers'
150
+ # long-polls and any call a failover callback waits on included, so
151
+ # stopping a follower never waits on a callback that waits on this client.
152
+ @transport.close
153
+ failovers.each(&:stop_following)
154
+ jobs.each(&:stop)
155
+ failovers.each(&:join_follower)
156
+ nil
157
+ end
158
+
159
+ # Raises closed after close, and invalid_argument in a forked child.
160
+ def ensure_open
161
+ raise Error.new(ErrorCode::CLOSED, "the client is closed") if @closed
162
+ return if Process.pid == @owner_pid
163
+
164
+ raise Litebackup.invalid_argument(
165
+ "this client was made in process #{@owner_pid} and cannot be used after a fork; " \
166
+ "make a new client in this process"
167
+ )
168
+ end
169
+
170
+ # Sends a call without connecting first.
171
+ def send_call(call)
172
+ answer = @transport.request(call.http_method, call.target, call.encoded_body, call.deadline_seconds)
173
+ @client_version = answer.client_version
174
+ Wire.decode_answer(call, answer.status, answer.body)
175
+ end
176
+
177
+ # Connects, then sends a call.
178
+ def call(call)
179
+ connect
180
+ send_call(call)
181
+ end
182
+
183
+ # The settings it was made with; for the groups.
184
+ attr_reader :settings
185
+
186
+ def add_failover(failover)
187
+ @lock.synchronize { @failovers_followed << failover }
188
+ end
189
+
190
+ def remove_failover(failover)
191
+ @lock.synchronize { @failovers_followed.delete(failover) }
192
+ end
193
+
194
+ # Registers a running job so close stops it; false once the client closed.
195
+ def add_job(job)
196
+ @lock.synchronize do
197
+ @jobs << job
198
+ !@closed
199
+ end
200
+ end
201
+
202
+ def remove_job(job)
203
+ @lock.synchronize { @jobs.delete(job) }
204
+ end
205
+ end
206
+
207
+ # The base of the client's groups.
208
+ class Group
209
+ def initialize(client)
210
+ @client = client
211
+ end
212
+ end
213
+
214
+ # Continuous backups and one-shot backup jobs.
215
+ class Backups < Group
216
+ # Saves a continuous backup rule for a file, directory, or glob; returns
217
+ # once the daemon saved it. Starting the same path again with the same
218
+ # settings returns the saved rule, so call it on every start. Different
219
+ # settings for a saved path raise rule_exists with the saved rule in
220
+ # details["rule"].
221
+ def start(source, name: nil, prefix: nil, maximum_local_databases: nil,
222
+ offload_durability: Durability::SERVER, offload_rollback_journal: false)
223
+ @client.call(Wire.start_backup(source, name: name, prefix: prefix,
224
+ maximum_local_databases: maximum_local_databases,
225
+ offload_durability: offload_durability,
226
+ offload_rollback_journal: offload_rollback_journal))
227
+ end
228
+
229
+ # Runs one foreground backup job and returns once it exits, after the
230
+ # chosen destination acknowledged it. With a timeout, a job still running
231
+ # 30 seconds after it ran out is killed and raises timeout. close ends a
232
+ # running job, which then raises closed.
233
+ def once(source, name: nil, prefix: nil, durability: Durability::SERVER, timeout: nil)
234
+ @client.ensure_open
235
+ settings = @client.settings
236
+ command = settings.foreground_command(source, name: name, prefix: prefix, durability: durability,
237
+ timeout: timeout)
238
+ deadline = Foreground.job_deadline(timeout)
239
+ job = Foreground.start_job(command, settings.foreground_environment)
240
+ begin
241
+ job.stop unless @client.add_job(job)
242
+ begin
243
+ stderr, timed_out = job.await(deadline)
244
+ rescue Exception # rubocop:disable Lint/RescueException
245
+ # An interrupt, such as Ctrl-C or Timeout, never leaves the job running.
246
+ job.signal(:KILL)
247
+ job.await(nil)
248
+ raise
249
+ end
250
+ ensure
251
+ @client.remove_job(job)
252
+ end
253
+ raise Foreground.timed_out_backup if timed_out
254
+
255
+ status = job.exit_status
256
+ return nil if status.success?
257
+ raise Error.new(ErrorCode::CLOSED, "the client is closed") if @client.closed?
258
+
259
+ raise Foreground.backup_failure(stderr, status.exitstatus || status.termsig)
260
+ end
261
+
262
+ # Stops the single-file backup with this exact remote name on this machine.
263
+ def stop(name)
264
+ @client.call(Wire.stop_backup(name))
265
+ end
266
+ end
267
+
268
+ # Saved backup and failover rules.
269
+ class Rules < Group
270
+ def list
271
+ @client.call(Wire.list_rules)
272
+ end
273
+
274
+ # Stops a whole rule, including future matches.
275
+ def stop(rule_id)
276
+ @client.call(Wire.stop_rule(rule_id))
277
+ end
278
+ end
279
+
280
+ # Databases on this machine and on the server.
281
+ class Databases < Group
282
+ def get(name)
283
+ @client.call(Wire.database(name))
284
+ end
285
+
286
+ # One page; pass its next as after to continue.
287
+ def page(after: "", limit: 100)
288
+ @client.call(Wire.databases_page(after: after, limit: limit))
289
+ end
290
+
291
+ # Every database on this machine, a page at a time: an Enumerator
292
+ # without a block.
293
+ def all(limit: 100, &block)
294
+ return to_enum(:all, limit: limit) if block.nil?
295
+
296
+ after = ""
297
+ loop do
298
+ listing = page(after: after, limit: limit)
299
+ listing.databases.each(&block)
300
+ return nil if listing.next.nil? || listing.next.empty?
301
+
302
+ after = listing.next
303
+ end
304
+ end
305
+
306
+ def list
307
+ all.to_a
308
+ end
309
+
310
+ def versions_page(name, after: 0, limit: nil)
311
+ @client.call(Wire.versions_page(name, after: after, limit: limit))
312
+ end
313
+
314
+ # The versions the server restores, oldest first; at most limit when set.
315
+ # An Enumerator without a block.
316
+ def all_versions(name, after: 0, limit: nil, &block)
317
+ return to_enum(:all_versions, name, after: after, limit: limit) if block.nil?
318
+ return nil if limit == 0
319
+
320
+ listed = 0
321
+ loop do
322
+ listing = versions_page(name, after: after, limit: limit.nil? ? nil : limit - listed)
323
+ listing.versions.each do |version|
324
+ block.call(version)
325
+ listed += 1
326
+ return nil if !limit.nil? && listed >= limit
327
+ end
328
+ return nil if listing.next.nil? || listing.next.zero? || listing.next <= after || listing.versions.empty?
329
+
330
+ after = listing.next
331
+ end
332
+ end
333
+
334
+ def versions(name, after: 0, limit: nil)
335
+ all_versions(name, after: after, limit: limit).to_a
336
+ end
337
+
338
+ # Writes a version to a new file and checks it. An existing file is never
339
+ # overwritten (file_exists). The file gets 0666 less umask, this
340
+ # process's umask when nil.
341
+ def restore(name, path:, version: nil, time: nil, umask: nil)
342
+ @client.call(Wire.restore(name, path: path, version: version, time: time, umask: umask))
343
+ end
344
+
345
+ # Rolls a database back under its own name: a past version's content
346
+ # becomes a new head, one past the current head. Pass version or time, one
347
+ # of them; every later version stays restorable. The database must be one
348
+ # this machine acquired or backs up, and its file closed (still_open
349
+ # otherwise); a replica or a failover standby is refused
350
+ # (invalid_argument), and a file holding writes the server lacks is
351
+ # refused with conflict and left untouched.
352
+ def revert(name, version: nil, time: nil)
353
+ @client.call(Wire.revert(name, version: version, time: time))
354
+ end
355
+
356
+ def sync(name)
357
+ @client.call(Wire.sync(name))
358
+ end
359
+
360
+ # Removes the local file of a released database once the server has its
361
+ # last version, or the bucket with "cloud".
362
+ def offload(name, durability: nil)
363
+ @client.call(Wire.offload(name, durability: durability))
364
+ end
365
+
366
+ def writer(name)
367
+ @client.call(Wire.writer(name))
368
+ end
369
+
370
+ # Locks the database for this machine and makes the local file the
371
+ # server's head. A pool's lease also opens, keeps, and releases it. A
372
+ # local file that diverged from the head is refused with conflict and
373
+ # left untouched; discard_local replaces it with the head instead. While
374
+ # another machine has the write lock, the daemon asks again for up to
375
+ # lock_timeout; without it the acquire fails at once with lock_unavailable.
376
+ def acquire(name, path: nil, maintenance: false, offload_on_release: false, offload_durability: Durability::SERVER,
377
+ machine_label: nil, timeout: nil, lock_timeout: nil, umask: nil, discard_local: false)
378
+ @client.call(Wire.acquire(name, path: path, maintenance: maintenance, offload_on_release: offload_on_release,
379
+ offload_durability: offload_durability, machine_label: machine_label,
380
+ timeout: timeout, lock_timeout: lock_timeout, umask: umask,
381
+ discard_local: discard_local))
382
+ end
383
+
384
+ # Syncs a final time and releases the write lock. Close every connection
385
+ # first, or it fails with still_open.
386
+ def release(name, durability: nil, offload: false, timeout: nil)
387
+ @client.call(Wire.release(name, durability: durability, offload: offload, timeout: timeout))
388
+ end
389
+
390
+ # A pool that keeps databases open for calls, opened and closed with
391
+ # adapter. With a block, the pool is closed when the block ends:
392
+ #
393
+ # litebackup.databases.pool(Litebackup::Integrations::SQLite3.adapter) do |pool|
394
+ # pool.lease("agents/42.sqlite", path: path) do |db|
395
+ # db.execute("INSERT INTO steps (body) VALUES (?)", [step])
396
+ # end
397
+ # end
398
+ #
399
+ # See Pool for idle_close, idle_release, cleanup_timeout, machine_label,
400
+ # and on_release_error.
401
+ def pool(adapter, idle_close: nil, idle_release: nil, cleanup_timeout: nil, machine_label: nil,
402
+ on_release_error: nil, &block)
403
+ settings = Pool::Settings.build(adapter, idle_close: idle_close, idle_release: idle_release,
404
+ cleanup_timeout: cleanup_timeout, machine_label: machine_label,
405
+ on_release_error: on_release_error)
406
+ pool = Pool.new(@client, adapter, settings)
407
+ return pool if block.nil?
408
+
409
+ begin
410
+ block.call(pool)
411
+ ensure
412
+ pool.close
413
+ end
414
+ end
415
+ end
416
+
417
+ # Live readonly replicas on this machine.
418
+ class Replicas < Group
419
+ # Keeps a live readonly replica and returns once its first version is local.
420
+ def start(name, path: nil, write_protection: nil, timeout: nil)
421
+ @client.call(Wire.start_replica(name, path: path, write_protection: write_protection, timeout: timeout))
422
+ end
423
+
424
+ # Replicates current and future databases under a prefix into a
425
+ # directory; downloads go on in the background.
426
+ def start_prefix(prefix, directory:, write_protection: nil)
427
+ @client.call(Wire.start_prefix_replica(prefix, directory: directory, write_protection: write_protection))
428
+ end
429
+
430
+ def list
431
+ @client.call(Wire.list_replicas)
432
+ end
433
+
434
+ def stop(name)
435
+ @client.call(Wire.stop_replica(name))
436
+ end
437
+
438
+ def stop_prefix(prefix, directory:)
439
+ @client.call(Wire.stop_prefix_replica(prefix, directory: directory))
440
+ end
441
+ end
442
+
443
+ # The daemon's event log.
444
+ class Events < Group
445
+ # One page after an event ID; -1 returns none and, as next, where the log ends.
446
+ def page(after: 0, wait: nil, limit: nil)
447
+ @client.call(Wire.events_page(after: after, wait: wait, limit: limit))
448
+ end
449
+
450
+ # Yields events, oldest first, by long-polling until the caller stops:
451
+ # an Enumerator without a block. A failed long-poll is retried with
452
+ # backoff from the same cursor, and on_error hears each failure;
453
+ # sdk_unsupported, closed, cancelled, invalid_argument, and cursor_expired
454
+ # (the cursor is older than the oldest event kept; choose a new one) end
455
+ # the watch by raising.
456
+ def watch(after: 0, wait: nil, on_error: nil, &block)
457
+ return to_enum(:watch, after: after, wait: wait, on_error: on_error) if block.nil?
458
+
459
+ wait_seconds = Wire.seconds(wait, "the event wait") || Wire::EVENT_WAIT_SECONDS
460
+ delay = Wire::FIRST_RETRY_SECONDS
461
+ loop do
462
+ begin
463
+ listing = page(after: after, wait: wait_seconds)
464
+ rescue Error => e
465
+ raise if Wire.terminal_watch_error?(e)
466
+
467
+ on_error&.call(e)
468
+ sleep(delay)
469
+ delay = [delay * 2, Wire::MAXIMUM_RETRY_SECONDS].min
470
+ next
471
+ end
472
+ delay = Wire::FIRST_RETRY_SECONDS
473
+ listing.events.each do |event|
474
+ after = [after, event.id].max
475
+ block.call(event)
476
+ end
477
+ after = [after, listing.next].max
478
+ end
479
+ end
480
+ end
481
+
482
+ # The session and its daemon.
483
+ class Session < Group
484
+ def status(after: "", limit: 100)
485
+ @client.call(Wire.status(after: after, limit: limit))
486
+ end
487
+
488
+ # Final-syncs every database, releases every write lock, and stops the
489
+ # daemon. A backup another machine writes has no lock and stays waiting.
490
+ # Each database it could not sync or release is in failed, with its code,
491
+ # and keeps any write lock it has; the session and the daemon then stay.
492
+ # An empty failed is the only complete shutdown. close never does this.
493
+ def shutdown(durability: nil, timeout: nil)
494
+ @client.call(Wire.shutdown(durability: durability, timeout: timeout))
495
+ end
496
+ end
497
+
498
+ # Databases run on several identical machines.
499
+ class Failovers < Group
500
+ # Runs the database at path, the same on every machine; returns once this
501
+ # machine is the origin or has a replica. See Failover for the callbacks:
502
+ # on_role_change hears the role the start answered, then every change;
503
+ # on_refused hears the daemon's message when it refused this machine's
504
+ # file; on_error hears each failed read. A file at the path that differs
505
+ # from the server head, and is not a clean copy of the version this
506
+ # machine last synced, is refused with conflict and left untouched;
507
+ # discard_local replaces it with the head.
508
+ def start(path, name: nil, timeout: nil, discard_local: false, on_role_change: nil, on_refused: nil, on_error: nil)
509
+ call = Wire.start_failover(path, name: name, timeout: timeout, discard_local: discard_local)
510
+ log_end = @client.call(Wire.events_page(after: -1))
511
+ started = @client.call(call)
512
+ @client.ensure_open
513
+ failover = Failover.new(@client, started, log_end.next, on_role_change: on_role_change,
514
+ on_refused: on_refused, on_error: on_error)
515
+ @client.add_failover(failover)
516
+ failover.start_following
517
+ failover
518
+ end
519
+ end
520
+ end
@@ -0,0 +1,65 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Litebackup
4
+ # Holds the credential a daemon uses when it starts: an API key, or a join
5
+ # token the daemon exchanges once for a key of the machine, then @ and the
6
+ # server's address.
7
+ API_KEY_ENVIRONMENT = "LITEBACKUP_API_KEY"
8
+
9
+ # Telling an API key from a join token, as the daemon does.
10
+ module Credential
11
+ # Join and invite tokens start with longer prefixes of an API key's.
12
+ API_KEY_PREFIX = "litebackup_"
13
+ JOIN_TOKEN_PREFIX = "litebackup_join_"
14
+ INVITE_PREFIX = "litebackup_invite_"
15
+ API_KEY = "api_key"
16
+ JOIN_TOKEN = "join_token"
17
+
18
+ # The server address a credential names, as the daemon checks it: an
19
+ # optional http:// or https:// in any case, a host name or a bracketed
20
+ # IPv6 address, an optional port, and an optional path without a query or
21
+ # fragment, of ASCII URL characters and percent escapes.
22
+ SERVER_ADDRESS = %r{
23
+ \A
24
+ (?:[Hh][Tt][Tt][Pp][Ss]?://)?
25
+ (?:[A-Za-z0-9._-]+|\[[0-9A-Fa-f:.]+\])
26
+ (?::[0-9]{1,5})?
27
+ (?:/(?:[A-Za-z0-9._~!$&'()*+,;=:/-]|%[0-9A-Fa-f]{2})*)?
28
+ \z
29
+ }x
30
+
31
+ module_function
32
+
33
+ # Tells an API key from a join token by prefix: "api_key" or
34
+ # "join_token", or nil for an empty credential, which leaves the daemon
35
+ # its saved key. Raises invalid_argument, without repeating the
36
+ # credential, for an invite token, a credential with neither prefix, or
37
+ # one without @ and the server's address.
38
+ def credential_type(key_and_server)
39
+ stripped = key_and_server.to_s.strip
40
+ return nil if stripped.empty?
41
+
42
+ separator = stripped.rindex("@")
43
+ secret = separator.nil? ? "" : stripped[0...separator]
44
+ server = separator.nil? ? "" : stripped[(separator + 1)..]
45
+ if secret.empty? || !SERVER_ADDRESS.match?(server)
46
+ raise Litebackup.invalid_argument(
47
+ "expected <API_KEY>@<HOST>: an API key or a join token from Machines → Add machine, " \
48
+ "then @ and the server's address: a host, or an http:// or https:// URL of one"
49
+ )
50
+ end
51
+ if secret.start_with?(INVITE_PREFIX)
52
+ raise Litebackup.invalid_argument(
53
+ "this is an invite token, which signs a person in to the console; " \
54
+ "use an API key or a join token from Machines → Add machine"
55
+ )
56
+ end
57
+ return JOIN_TOKEN if secret.start_with?(JOIN_TOKEN_PREFIX)
58
+ return API_KEY if secret.start_with?(API_KEY_PREFIX)
59
+
60
+ raise Litebackup.invalid_argument(
61
+ "expected an API key or a join token, which start with #{API_KEY_PREFIX}; get one from Machines → Add machine"
62
+ )
63
+ end
64
+ end
65
+ end