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,132 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Litebackup
4
+ # Codes the SDK raises itself, with status 0, and the daemon codes worth
5
+ # matching. Codes the daemon answers with that are not listed here are kept
6
+ # verbatim.
7
+ module ErrorCode
8
+ # An argument failed local validation; nothing was sent.
9
+ INVALID_ARGUMENT = SpecErrorCodes::INVALID_ARGUMENT
10
+ # No litebackup binary was found to start the daemon or a foreground backup.
11
+ BINARY_NOT_FOUND = "binary_not_found"
12
+ # litebackup launch ran and failed.
13
+ LAUNCH_FAILED = SpecErrorCodes::LAUNCH_FAILED
14
+ # litebackup launch refused api_key, a credential other than the one the
15
+ # session's client locked its databases with; session.shutdown with the
16
+ # current credential releases them first.
17
+ DRAIN_REQUIRED = SpecErrorCodes::DRAIN_REQUIRED
18
+ # The socket refused the connection or closed it mid-call.
19
+ CONNECTION_FAILED = "connection_failed"
20
+ # The daemon is older than MINIMUM_DAEMON_VERSION.
21
+ DAEMON_UNSUPPORTED = "daemon_unsupported"
22
+ # The wait was cancelled; the daemon may still finish the operation.
23
+ CANCELLED = SpecErrorCodes::CANCELLED
24
+ # The client was closed.
25
+ CLOSED = "closed"
26
+ # The daemon answered 200 with a body the SDK cannot decode.
27
+ INVALID_RESPONSE = "invalid_response"
28
+ # A pool could not close or release a leased database; the error is a LeaseCleanupError.
29
+ LEASE_CLEANUP_FAILED = "lease_cleanup_failed"
30
+ # The file a restore or an acquire would write, or a journal file beside it, already exists.
31
+ FILE_EXISTS = SpecErrorCodes::FILE_EXISTS
32
+ # A backup rule on this machine owns the database and its write lock, so
33
+ # it cannot be released; stop its backup instead.
34
+ RULE_DATABASE = SpecErrorCodes::RULE_DATABASE
35
+ # The path already has a backup rule with different settings; details["rule"] is the saved rule.
36
+ RULE_EXISTS = SpecErrorCodes::RULE_EXISTS
37
+ # Another machine writes the database.
38
+ LOCK_UNAVAILABLE = SpecErrorCodes::LOCK_UNAVAILABLE
39
+ # This machine lost the database's write lock, as a pool's lease does when another machine broke it.
40
+ LOCK_LOST = SpecErrorCodes::LOCK_LOST
41
+ NOT_FOUND = SpecErrorCodes::NOT_FOUND
42
+ # A process still has the database open, so it cannot be released.
43
+ STILL_OPEN = SpecErrorCodes::STILL_OPEN
44
+ # The operation's timeout ran out.
45
+ TIMEOUT = SpecErrorCodes::TIMEOUT
46
+ # This SDK is older than the daemon accepts.
47
+ SDK_UNSUPPORTED = SpecErrorCodes::SDK_UNSUPPORTED
48
+ # Another job or a continuous backup has a foreground backup's writer lock.
49
+ BUSY = SpecErrorCodes::BUSY
50
+ # An events cursor is older than the oldest event the daemon keeps; a
51
+ # watch ends with it, and the caller picks a new cursor.
52
+ CURSOR_EXPIRED = SpecErrorCodes::CURSOR_EXPIRED
53
+ end
54
+
55
+ # Every failure the SDK raises: the daemon's answer, or an error the SDK
56
+ # raised itself with status 0.
57
+ #
58
+ # details holds the answer's fields besides code and message under their
59
+ # wire names, such as "rule" for rule_exists from backups.start. For
60
+ # lease_cleanup_failed it holds step, name, path, and acquired or
61
+ # durability. The underlying error, when there is one, is cause.
62
+ class Error < StandardError
63
+ attr_reader :code, :status, :details
64
+
65
+ def initialize(code, message, status = 0, details = nil)
66
+ super(message)
67
+ @code = code
68
+ @status = status
69
+ @details = details.nil? ? {} : details
70
+ end
71
+
72
+ # The code and the message, as an uncaught error shows them.
73
+ def detailed_message(*)
74
+ "#{code}: #{message}"
75
+ end
76
+
77
+ def inspect
78
+ "#<#{self.class.name} code=#{code.inspect} message=#{message.inspect} " \
79
+ "status=#{status.inspect} details=#{details.inspect}>"
80
+ end
81
+ end
82
+
83
+ # The step of a lease's cleanup that failed.
84
+ module LeaseCleanupStep
85
+ # Closing the handle failed, so the database was not released and stays acquired by this machine.
86
+ CLOSE = "close"
87
+ # The release itself failed; the file is intact.
88
+ RELEASE = "release"
89
+ end
90
+
91
+ # A failed release of a leased database, with code lease_cleanup_failed;
92
+ # cause is why.
93
+ #
94
+ # step is "close" when closing the handle failed: the database was not
95
+ # released and stays acquired by this machine with its file as it is; close
96
+ # every connection, then call pool.release(name) again. It is "release"
97
+ # when the release itself failed, as with still_open or an unreachable
98
+ # server: the file is intact; call pool.release(name) again before another
99
+ # machine needs it.
100
+ class LeaseCleanupError < Error
101
+ attr_reader :step, :name
102
+
103
+ def initialize(step, name, message, details)
104
+ super(ErrorCode::LEASE_CLEANUP_FAILED, message, 0, details)
105
+ @step = step
106
+ @name = name
107
+ end
108
+ end
109
+
110
+ # Several errors raised together, the first one first, as a lease that
111
+ # failed and then failed to clean up raises them. Ruby has no
112
+ # ExceptionGroup, so this is the SDK's.
113
+ class ErrorGroup < StandardError
114
+ attr_reader :errors
115
+
116
+ def initialize(message, errors)
117
+ super("#{message} failed in #{errors.length} ways: #{errors.map(&:message).join("; ")}")
118
+ @errors = errors.dup.freeze
119
+ end
120
+ end
121
+
122
+ # The error for a failed local check.
123
+ def self.invalid_argument(message)
124
+ Error.new(ErrorCode::INVALID_ARGUMENT, message)
125
+ end
126
+
127
+ # Raises one error alone, or several as an ErrorGroup, first one first.
128
+ def self.raise_together(failures, message)
129
+ raise failures.first if failures.length == 1
130
+ raise ErrorGroup.new(message, failures) unless failures.empty?
131
+ end
132
+ end
@@ -0,0 +1,416 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "monitor"
4
+
5
+ module Litebackup
6
+ # A failover followed by a background thread; stop, or the client's close,
7
+ # ends following.
8
+ #
9
+ # Each replica asks for the write lock about once a second, so one takes
10
+ # over once the origin's lease runs out. Callbacks run on the following
11
+ # thread, in event order; the first is on_role_change with the role the
12
+ # start answered, and it may run before failovers.start returns, so use its
13
+ # role argument rather than the Failover.
14
+ #
15
+ # role is "origin", "replica", or "unknown": unknown while the daemon does
16
+ # not answer, once the failover stopped, and from a draining or refused
17
+ # event until the next role change or a role read past it. The SDK sets
18
+ # unknown; the daemon never reports it.
19
+ class Failover
20
+ ORIGIN = Models::DatabaseStatus::ROLE_ORIGIN
21
+ REPLICA = Models::DatabaseStatus::ROLE_REPLICA
22
+ UNKNOWN = "unknown"
23
+ EVENT_PAGE = 1000
24
+ ROLE_CHANGED = Models::EventType::ROLE_CHANGED
25
+ DRAINING = Models::EventType::DRAINING
26
+ REFUSED = Models::EventType::REFUSED
27
+ ROLE_EVENT_TYPES = [ROLE_CHANGED, DRAINING, REFUSED].freeze
28
+ # Error codes the event reading never retries: they end following. An
29
+ # expired cursor is not one: a failover resumes at the log's end.
30
+ FATAL_ERROR_CODES = [
31
+ ErrorCode::SDK_UNSUPPORTED, ErrorCode::CLOSED, ErrorCode::CANCELLED, ErrorCode::INVALID_ARGUMENT
32
+ ].freeze
33
+
34
+ class << self
35
+ # How long one failover long-poll waits. It is shorter than
36
+ # confirmation_limit_seconds, so a daemon that answers confirms the
37
+ # role in time.
38
+ attr_accessor :event_wait_seconds
39
+ # The longest a failover keeps reporting a role the daemon has not
40
+ # confirmed. 15 s is the default client heartbeat interval and a
41
+ # quarter of the default 60 s session lease another machine waits out
42
+ # before it takes over. Tests shorten it.
43
+ attr_accessor :confirmation_limit_seconds
44
+ end
45
+ self.event_wait_seconds = 10.0
46
+ self.confirmation_limit_seconds = 15.0
47
+
48
+ # What the follower carries from one read to the next: the newest event
49
+ # ID handed to the failover (cursor), the backoff after the next failed
50
+ # read (delay), when the daemon last confirmed the role (confirmed),
51
+ # whether the role is read before the next long-poll (role_read_pending)
52
+ # and the log's end before that (log_end_pending), and the log's end read
53
+ # before the last role read, whose role_changed events are older than the
54
+ # read and skipped (role_read_log_end).
55
+ class FollowProgress
56
+ attr_accessor :cursor, :delay, :confirmed, :role_read_pending, :log_end_pending, :role_read_log_end
57
+
58
+ def initialize(cursor)
59
+ @cursor = cursor
60
+ @delay = Wire::FIRST_RETRY_SECONDS
61
+ @confirmed = Process.clock_gettime(Process::CLOCK_MONOTONIC)
62
+ @role_read_pending = false
63
+ @log_end_pending = false
64
+ @role_read_log_end = 0
65
+ end
66
+ end
67
+
68
+ # What the daemon answered when the failover started.
69
+ attr_reader :status, :name, :path
70
+
71
+ def initialize(client, status, cursor, on_role_change: nil, on_refused: nil, on_error: nil)
72
+ @client = client
73
+ @status = status
74
+ @name = status.name
75
+ @path = status.path
76
+ @role = status.role
77
+ @cursor = cursor
78
+ @event_wait = Failover.event_wait_seconds
79
+ @confirmation_limit = Failover.confirmation_limit_seconds
80
+ @on_role_change = on_role_change
81
+ @on_refused = on_refused
82
+ @on_error = on_error
83
+ @stopped = false
84
+ @owner_pid = Process.pid
85
+ # Locked across every callback, so once stop_following returns no
86
+ # callback runs; reentrant, so a callback may stop the failover.
87
+ @callback_lock = Monitor.new
88
+ @wake = Queue.new
89
+ @thread = nil
90
+ end
91
+
92
+ # The role this machine has; unknown in a process forked after the
93
+ # failover started, which has no follower and never learns a change.
94
+ def role
95
+ Process.pid == @owner_pid ? @role : UNKNOWN
96
+ end
97
+
98
+ # Whether this machine writes the database now; false while the role is unknown.
99
+ def origin?
100
+ role == ORIGIN
101
+ end
102
+
103
+ def stopped?
104
+ @stopped
105
+ end
106
+
107
+ # Which machine writes the database, when its lease runs out, and whether it ran out.
108
+ def writer
109
+ ensure_owner
110
+ @client.databases.writer(name)
111
+ end
112
+
113
+ # Stops the failover and releases its write lock. The file stays.
114
+ # Following ends first, so no callback runs once the failover is stopped.
115
+ def stop
116
+ ensure_owner
117
+ stop_following
118
+ @client.backups.stop(name)
119
+ end
120
+
121
+ # Starts the following thread; failovers.start calls it.
122
+ def start_following
123
+ @thread = Thread.new { follow(@cursor) }
124
+ @thread.name = "litebackup-failover-#{name}"
125
+ @thread.report_on_exception = true
126
+ self
127
+ end
128
+
129
+ # Stops following events; once it returns, no callback runs. A callback
130
+ # in progress on the following thread is waited for. The thread itself
131
+ # exits when its current long-poll returns; the client's close waits for it.
132
+ def stop_following
133
+ mark_stopped
134
+ @wake << true
135
+ @client.remove_failover(self)
136
+ end
137
+
138
+ def join_follower
139
+ @thread.join unless @thread.nil? || @thread == Thread.current
140
+ end
141
+
142
+ private
143
+
144
+ def ensure_owner
145
+ return if Process.pid == @owner_pid
146
+
147
+ raise Litebackup.invalid_argument(
148
+ "this failover was started in process #{@owner_pid} and is not followed after a fork; " \
149
+ "start it again in this process"
150
+ )
151
+ end
152
+
153
+ def monotonic
154
+ Process.clock_gettime(Process::CLOCK_MONOTONIC)
155
+ end
156
+
157
+ def role_event?(event_type)
158
+ ROLE_EVENT_TYPES.include?(event_type)
159
+ end
160
+
161
+ # The role a status read reports: unknown while the daemon drains the
162
+ # origin, as after a draining event, and while the failover's file is
163
+ # refused (conflicted), as after a refused event.
164
+ def status_role(database)
165
+ database.draining == true || database.state == Wire::STATE_CONFLICTED ? UNKNOWN : database.role
166
+ end
167
+
168
+ # Stops callbacks, waiting for one in progress on another thread to
169
+ # return. Nothing follows the role any more, so it is unknown.
170
+ def mark_stopped
171
+ @callback_lock.synchronize do
172
+ @stopped = true
173
+ @role = UNKNOWN
174
+ end
175
+ end
176
+
177
+ # Calls on_role_change with the role the start answered, so an app can
178
+ # route writes from its callback alone.
179
+ def report_start_role
180
+ @callback_lock.synchronize do
181
+ @on_role_change.call(@role) if !@stopped && !@on_role_change.nil?
182
+ end
183
+ end
184
+
185
+ def apply_event(event, progress)
186
+ @callback_lock.synchronize do
187
+ return if @stopped || event.name != name
188
+
189
+ # An event older than the last role read changes no role, because
190
+ # that read has it; a refusal among them is still reported.
191
+ older_than_role_read = role_event?(event.type) && event.id <= progress.role_read_log_end
192
+ return if older_than_role_read && event.type != REFUSED
193
+
194
+ case event.type
195
+ when ROLE_CHANGED
196
+ change_role(Wire.supplied?(event.role) ? event.role : event.message)
197
+ when DRAINING
198
+ # The daemon drains: it stops being the origin before it releases
199
+ # the lock, so the app stops writing while no machine is allowed to
200
+ # take over yet.
201
+ change_role(UNKNOWN)
202
+ when REFUSED
203
+ # The daemon refused this machine's file and the failover stays
204
+ # conflicted there: this machine neither writes nor follows the database.
205
+ change_role(UNKNOWN) unless older_than_role_read
206
+ # The role callback could have stopped the failover.
207
+ @on_refused.call(event.message) if !@stopped && !@on_refused.nil?
208
+ end
209
+ end
210
+ end
211
+
212
+ # Asks for a role read after a long-poll that brought no role change
213
+ # while the role is unknown. A drain that failed says nothing more after
214
+ # its draining event; its status shows the role once it stopped.
215
+ def read_unknown_role_again(listing, progress)
216
+ return unless @role == UNKNOWN
217
+ return if listing.events.any? do |event|
218
+ event.name == name && role_event?(event.type) && event.id > progress.role_read_log_end
219
+ end
220
+
221
+ progress.role_read_pending = true
222
+ progress.log_end_pending = true
223
+ end
224
+
225
+ # Saves a role and calls on_role_change when it differs; returns whether it changed.
226
+ def change_role(new_role)
227
+ @callback_lock.synchronize do
228
+ return false if @stopped || !Wire.supplied?(new_role) || new_role == @role
229
+
230
+ @role = new_role
231
+ @on_role_change&.call(new_role)
232
+ true
233
+ end
234
+ end
235
+
236
+ def report_error(error)
237
+ @callback_lock.synchronize do
238
+ @on_error.call(error) if !@on_error.nil? && !@stopped
239
+ end
240
+ end
241
+
242
+ # Moves role_read_log_end through a page read after it, up to log_end,
243
+ # and returns whether the page changed this database's role.
244
+ def scan_role_change_page(listing, log_end, progress)
245
+ superseded = false
246
+ listing.events.each do |event|
247
+ break if event.id > log_end
248
+
249
+ superseded = true if event.name == name && role_event?(event.type)
250
+ end
251
+ unless listing.events.empty?
252
+ # Never past log_end: a role change after it came after the role
253
+ # read, and the long-poll applies it.
254
+ progress.role_read_log_end = [progress.role_read_log_end, [listing.events.last.id, log_end].min].max
255
+ end
256
+ superseded
257
+ end
258
+
259
+ # Makes the role unknown without calling on_role_change.
260
+ def clear_role
261
+ @callback_lock.synchronize { @role = UNKNOWN }
262
+ end
263
+
264
+ # Makes the role unknown and, when that changed it, has the follower read
265
+ # the log's end and the role once the daemon answers.
266
+ def lose_role(progress)
267
+ return unless change_role(UNKNOWN)
268
+
269
+ progress.role_read_pending = true
270
+ progress.log_end_pending = true
271
+ end
272
+
273
+ # Makes the role unknown once the daemon has not confirmed it for the confirmation limit.
274
+ def lose_unconfirmed_role(progress)
275
+ lose_role(progress) if @role != UNKNOWN && monotonic - progress.confirmed >= @confirmation_limit
276
+ end
277
+
278
+ # The call with a deadline of the confirmation limit after the last
279
+ # confirmation, or after now once the role is unknown.
280
+ def with_answer_deadline(call, progress)
281
+ now = monotonic
282
+ start = @role == UNKNOWN ? now : progress.confirmed
283
+ call.with(answer_deadline_seconds: [0.0, start + @confirmation_limit - now].max)
284
+ end
285
+
286
+ # After a failed read: makes the role unknown when the daemon did not
287
+ # answer or following ends, reports the error, and returns how long to
288
+ # wait before the next read, or nil when following ends. While the role
289
+ # is known, the wait ends when the confirmation limit passes.
290
+ def retry_delay(error, progress)
291
+ return nil if @stopped
292
+
293
+ ending = FATAL_ERROR_CODES.include?(error.code)
294
+ if error.code == ErrorCode::CLOSED
295
+ # The client is closing and stops following next: no role callback.
296
+ clear_role
297
+ elsif ending || error.status.zero?
298
+ lose_role(progress)
299
+ end
300
+ report_error(error)
301
+ return nil if ending || @stopped
302
+
303
+ wait = progress.delay
304
+ wait = [0.0, [wait, progress.confirmed + @confirmation_limit - monotonic].min].max if @role != UNKNOWN
305
+ progress.delay = [progress.delay * 2, Wire::MAXIMUM_RETRY_SECONDS].min
306
+ wait
307
+ end
308
+
309
+ # Long-polls the daemon's events after cursor until stopped, passing this
310
+ # failover's events to it. It first reports the role the start answered.
311
+ #
312
+ # An expired cursor does not end following: it moves to the log's end,
313
+ # then the role is read again before the next long-poll, so a role change
314
+ # in events the daemon pruned is still reported. The cursor is read first
315
+ # and kept while the role read is retried, so no event after it is lost.
316
+ #
317
+ # A read the daemon did not answer (connection_failed, timeout,
318
+ # daemon_unsupported: any error with status 0) makes the role unknown at
319
+ # once, and so does no answer within the confirmation limit of the last
320
+ # confirmation, or failed reads the daemon answered for that long. Once
321
+ # the daemon answers again, the follower reads the log's end, then the
322
+ # role, then the log's end again and the events up to it: when one
323
+ # changed the role, the role read could predate it, so it reads the role
324
+ # again. A closed client makes the role unknown without a callback.
325
+ def follow(cursor)
326
+ report_start_role
327
+ progress = FollowProgress.new(cursor)
328
+ until @stopped
329
+ begin
330
+ read_daemon(progress)
331
+ rescue Error => e
332
+ wait = retry_delay(e, progress)
333
+ return if wait.nil?
334
+
335
+ @wake.pop(timeout: wait)
336
+ next
337
+ end
338
+ progress.delay = Wire::FIRST_RETRY_SECONDS
339
+ end
340
+ end
341
+
342
+ # The follower's next read: the log's end or the role when a role read is
343
+ # pending, one long-poll otherwise.
344
+ def read_daemon(progress)
345
+ lose_unconfirmed_role(progress)
346
+ if progress.role_read_pending
347
+ read_role(progress)
348
+ return
349
+ end
350
+ long_poll = Wire.events_page(after: progress.cursor, wait: @event_wait, limit: EVENT_PAGE)
351
+ begin
352
+ listing = @client.call(with_answer_deadline(long_poll, progress))
353
+ rescue Error => e
354
+ raise if @stopped || e.code != ErrorCode::CURSOR_EXPIRED
355
+
356
+ report_error(e)
357
+ return if @stopped
358
+
359
+ log_end = @client.call(with_answer_deadline(Wire.events_page(after: -1), progress)).next
360
+ progress.cursor = log_end
361
+ progress.role_read_log_end = log_end
362
+ progress.role_read_pending = true
363
+ progress.log_end_pending = false
364
+ return
365
+ end
366
+ progress.confirmed = monotonic
367
+ listing.events.each do |event|
368
+ progress.cursor = [progress.cursor, event.id].max
369
+ apply_event(event, progress)
370
+ end
371
+ progress.cursor = [progress.cursor, listing.next].max
372
+ read_unknown_role_again(listing, progress)
373
+ end
374
+
375
+ def read_role(progress)
376
+ if progress.log_end_pending
377
+ progress.role_read_log_end = @client.call(with_answer_deadline(Wire.events_page(after: -1), progress)).next
378
+ progress.log_end_pending = false
379
+ end
380
+ read = status_role(@client.call(with_answer_deadline(Wire.database(name), progress)))
381
+ # The role read could predate a role change the log now has: read the
382
+ # role again, then look past the new log end.
383
+ return if role_superseded?(progress)
384
+
385
+ progress.confirmed = monotonic
386
+ progress.role_read_pending = false
387
+ change_role(read)
388
+ end
389
+
390
+ # Reads the log's end as of now, then the events from role_read_log_end
391
+ # through it, without waiting. Returns whether one changed this
392
+ # database's role, so a role read that raced it is not trusted.
393
+ # role_read_log_end moves to that end; events after it came after the
394
+ # role read. When pruning passed role_read_log_end, it returns true with
395
+ # log_end_pending set, so the follower starts again from a fresh log end.
396
+ def role_superseded?(progress)
397
+ log_end = @client.call(with_answer_deadline(Wire.events_page(after: -1), progress)).next
398
+ superseded = false
399
+ while progress.role_read_log_end < log_end
400
+ scan = Wire.events_page(after: progress.role_read_log_end, limit: EVENT_PAGE)
401
+ begin
402
+ listing = @client.call(with_answer_deadline(scan, progress))
403
+ rescue Error => e
404
+ raise unless e.code == ErrorCode::CURSOR_EXPIRED
405
+
406
+ progress.log_end_pending = true
407
+ return true
408
+ end
409
+ superseded = scan_role_change_page(listing, log_end, progress) || superseded
410
+ break if listing.events.empty?
411
+ end
412
+ progress.role_read_log_end = [progress.role_read_log_end, log_end].max
413
+ superseded
414
+ end
415
+ end
416
+ end