Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions TESTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,3 +58,19 @@ and check the event appears in the Sentry project.




### SQLite copy and Elasticsearch reindex (#1589)

The specs drive the rsync runner and Elasticsearch with doubles, plus one real
copy between temporary directories. These need real servers, so they run on the
rehearsal server and are recorded with each dry run. The commands are in
`docs/sqlite_and_search_migration.md`.

- Run `app:sqlite_migration:bulk` from the old server to the rehearsal
server's shared data directory (for example `/srv/www/data/scrapers`), and record the elapsed time and transfer speed it prints.
Run it again and check it only transfers what changed.
- Run `app:sqlite_migration:delta` with `DELETE=1 MAX_DELETE=N` after a change and a
deletion on the source, then compare the two file listings with
`app:sqlite_migration:verify`.
- Run `app:search_migration:reindex` against Elasticsearch 8.19 and check the
counts match, then search for a scraper and a person on the site.
165 changes: 165 additions & 0 deletions app/lib/morph/search_migration/reindexer.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,165 @@
# typed: strict
# frozen_string_literal: true

module Morph
module SearchMigration
# Rebuilds the Elasticsearch indexes from the database and reports document
# counts, for the move to Elasticsearch 8.19 (#1589). Nothing from the old
# server's index is carried over, so a rebuild on the new server is the
# whole migration.
#
# It uses Searchkick's own Model.reindex, which builds a fresh index, fills
# it and then swaps the alias, so search keeps working throughout. It only
# calls the public Searchkick API, so it behaves the same on 7.17 and 8.19.
# Searching an 8.x server with the 7.17 client also needs the vendor
# Content-Type override from PR #1613.
class Reindexer
extend T::Sig

class ModelCount < T::Struct
extend T::Sig

const :name, String
const :database_count, Integer
const :index_count, Integer
const :seconds, T.nilable(Float)

sig { returns(T::Boolean) }
def match?
database_count == index_count
end
end

# Prints how many documents the new index holds while a reindex runs.
# Searchkick builds a timestamped index and only swaps the alias at the
# end, so the newest index behind the alias name is the one being filled.
class ProgressMonitor
extend T::Sig

sig { params(model: T.untyped, expected: Integer, out: T.untyped).void }
def initialize(model, expected, out)
@model = model
@expected = expected
@out = out
end

sig { void }
def tick
indexed = newest_index_total
return if indexed.nil?

percent = @expected.positive? ? (indexed * 100.0 / @expected).round : 100
@out.puts(" #{@model.name}: #{indexed} of #{@expected} documents (#{percent}%)")
end

private

sig { returns(T.nilable(Integer)) }
def newest_index_total
stats = Searchkick.client.indices.stats(index: "#{@model.search_index.name}_*", metric: "indexing")
_name, newest = stats.fetch("indices", {}).max_by(&:first)
newest&.dig("primaries", "indexing", "index_total")
rescue StandardError
# Progress is a courtesy. A failed poll must never stop the reindex.
nil
end
end

sig { params(models: T::Array[T.untyped], out: T.untyped, poll_seconds: Numeric).void }
def initialize(models: [Scraper, Owner], out: $stdout, poll_seconds: 15)
@models = models
@out = out
@poll_seconds = poll_seconds
end

sig { returns(T::Array[ModelCount]) }
def reindex
@out.puts("Elasticsearch #{Searchkick.server_version}, Searchkick #{Searchkick::VERSION}")
@models.map { |model| reindex_model(model) }
end

# Counts only. Safe to run at any time and as often as you like.
sig { returns(T::Array[ModelCount]) }
def counts
@models.map { |model| count(model) }
end

sig { params(counts: T::Array[ModelCount], source_counts: T::Hash[String, Integer]).returns(String) }
def self.report(counts, source_counts = {})
lines = ["Elasticsearch document counts", ""]
lines << "#{' ' * 10} #{'database'.rjust(12)} #{'index'.rjust(12)} #{'old index'.rjust(12)}"
counts.each do |c|
old = source_counts[c.name]
lines << format("%-10<name>s %12<db>d %12<idx>d %12<old>s %<flag>s",
name: c.name, db: c.database_count, idx: c.index_count, old: old || "-",
flag: ok?([c], source_counts) ? "" : "differs").rstrip
end
lines << ""
lines << (ok?(counts, source_counts) ? "RESULT: match" : "RESULT: MISMATCH")
"#{lines.join("\n")}\n"
end

# Index matches the database, and the old server's count where one was given
sig { params(counts: T::Array[ModelCount], source_counts: T::Hash[String, Integer]).returns(T::Boolean) }
def self.ok?(counts, source_counts = {})
counts.all? { |c| c.match? && (source_counts[c.name].nil? || source_counts[c.name] == c.index_count) }
end

# "Scraper=11127,Owner=5000" as typed from the old server's `_cat/count`
sig { params(text: String).returns(T::Hash[String, Integer]) }
def self.parse_source_counts(text)
text.split(",").to_h do |pair|
name, number = pair.strip.split("=", 2)
raise ArgumentError, "expected Name=count, got #{pair.inspect}" unless name && number&.match?(/\A\d+\z/)

[name, number.to_i]
end
end

private

sig { params(model: T.untyped).returns(ModelCount) }
def reindex_model(model)
expected = model.count
@out.puts("Reindexing #{model.name} (#{expected} rows)...")
started = Process.clock_gettime(Process::CLOCK_MONOTONIC).to_f
with_progress(model, expected) { model.reindex }
seconds = Process.clock_gettime(Process::CLOCK_MONOTONIC).to_f - started
result = count(model, seconds)
@out.puts("Finished #{model.name}: #{result.index_count} documents in #{seconds.round(1)}s")
result
end

sig { params(model: T.untyped, seconds: T.nilable(Float)).returns(ModelCount) }
def count(model, seconds = nil)
ModelCount.new(name: model.name, database_count: model.count, index_count: index_count(model), seconds: seconds)
end

# The count API is exact. Index#total_docs uses a search, which stops
# counting at 10,000 and production has more than that many scrapers.
# Before the first reindex there is no index at all, which is 0 documents.
sig { params(model: T.untyped).returns(Integer) }
def index_count(model)
index = model.search_index
return 0 unless index.exists?

Searchkick.client.count(index: index.name)["count"]
end

sig { params(model: T.untyped, expected: Integer, block: T.proc.void).void }
def with_progress(model, expected, &block)
monitor = ProgressMonitor.new(model, expected, @out)
thread = Thread.new do
loop do
sleep(@poll_seconds)
monitor.tick
end
end
block.call
ensure
thread&.kill
thread&.join
end
end
end
end
68 changes: 68 additions & 0 deletions app/lib/morph/sqlite_migration/comparison_report.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
# typed: strict
# frozen_string_literal: true

module Morph
module SqliteMigration
# Turns a Manifest::Comparison into plain text that can be pasted into the
# dry run record on the rehearsal ticket.
class ComparisonReport
extend T::Sig

LISTED = 20

sig { params(comparison: Manifest::Comparison).void }
def initialize(comparison)
@comparison = comparison
end

sig { returns(String) }
def to_s
lines = ["SQLite copy verification", ""]
lines.concat(summary_table)
lines << ""
lines.concat(problems)
lines << (@comparison.match? ? "RESULT: match" : "RESULT: MISMATCH")
"#{lines.join("\n")}\n"
end

private

sig { returns(T::Array[String]) }
def summary_table
source = @comparison.source_summary
destination = @comparison.destination_summary
keys = (source.keys | destination.keys).sort
rows = keys.map do |key|
s = source.fetch(key, 0)
d = destination.fetch(key, 0)
format("%-22<key>s %16<src>s %16<dst>s %<flag>s", key: key, src: s, dst: d, flag: s == d ? "" : "differs").rstrip
end
["#{' ' * 22} #{'source'.rjust(16)} #{'destination'.rjust(16)}"] + rows
end

sig { returns(T::Array[String]) }
def problems
lines = []
lines.concat(listing("Missing from destination", @comparison.missing_from_destination))
lines.concat(listing("Extra in destination", @comparison.extra_in_destination))
lines.concat(listing("Size differs (path, source, destination)",
@comparison.size_mismatches.map { |p, a, b| "#{p}\t#{a}\t#{b}" }))
lines
end

sig { params(title: String, items: T::Array[String]).returns(T::Array[String]) }
def listing(title, items)
return [] if items.empty?

shown = items.first(LISTED)
more = items.size - shown.size
[
"#{title}: #{items.size}",
*shown.map { |item| " #{item}" },
*(more.positive? ? [" ... and #{more} more"] : []),
""
]
end
end
end
end
128 changes: 128 additions & 0 deletions app/lib/morph/sqlite_migration/manifest.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
# typed: strict
# frozen_string_literal: true

require "find"

module Morph
module SqliteMigration
# A listing of every regular file under a directory, with its size in bytes.
#
# The text form is one `relative/path<TAB>size` line per file, sorted. The
# old server runs main on Ruby 3.0.7 and cannot run this class, so it makes
# the same listing with plain shell:
#
# find db/scrapers -type f -printf '%P\t%s\n' | sort > manifest.tsv
#
# This class only reads. It never writes to the directory it scans.
class Manifest
extend T::Sig

class Comparison < T::Struct
extend T::Sig

const :source_summary, T::Hash[Symbol, Integer]
const :destination_summary, T::Hash[Symbol, Integer]
const :missing_from_destination, T::Array[String]
const :extra_in_destination, T::Array[String]
const :size_mismatches, T::Array[[String, Integer, Integer]]

sig { returns(T::Boolean) }
def match?
missing_from_destination.empty? && extra_in_destination.empty? && size_mismatches.empty?
end
end

sig { returns(T::Hash[String, Integer]) }
attr_reader :sizes

sig { params(sizes: T::Hash[String, Integer]).void }
def initialize(sizes)
@sizes = sizes
end

# Symlinks are skipped (File.file? follows them, so check lstat), because
# rsync -a copies them as links and they have no size worth comparing.
sig { params(root: String).returns(Manifest) }
def self.scan(root)
raise ArgumentError, "#{root} is not a directory" unless File.directory?(root)

# db/scrapers is a Capistrano linked_dir, so the root is usually a
# symlink, and Find does not enter a symlink.
real_root = File.realpath(root)
prefix = File.join(real_root, "")
sizes = T.let({}, T::Hash[String, Integer])
Find.find(real_root) do |path|
# Scrapers are running, so a file can vanish between listing and stat
stat = begin
File.lstat(path)
rescue Errno::ENOENT, Errno::ENOTDIR
next
end
next unless stat.file?

sizes[path.delete_prefix(prefix)] = stat.size
end
new(sizes)
end
Comment thread
sentry[bot] marked this conversation as resolved.
Resolved

sig { params(text: String).returns(Manifest) }
def self.parse(text)
sizes = T.let({}, T::Hash[String, Integer])
text.each_line.with_index(1) do |line, number|
line = line.chomp
next if line.empty?

# Split on the last tab, because a file name can contain tabs
path, _tab, size = line.rpartition("\t")
raise ArgumentError, "line #{number} is not path<TAB>size" if path.empty? || !size.match?(/\A\d+\z/)

sizes[path] = size.to_i
end
new(sizes)
end

sig { returns(String) }
def to_s
sizes.sort.map { |path, size| "#{path}\t#{size}\n" }.join
end

# File and byte counts overall, for *.sqlite files, and for each top level
# directory (db/scrapers has data/ and repos/), so the figures line up
# with the 123 GB measured in #1558.
sig { returns(T::Hash[Symbol, Integer]) }
def summary
result = Hash.new(0)
sizes.each do |path, size|
result[:files] += 1
result[:bytes] += size
if path.end_with?(".sqlite")
result[:sqlite_files] += 1
result[:sqlite_bytes] += size
end
top = path.include?("/") ? path.split("/", 2).first : "(top level)"
result[:"#{top}_files"] += 1
result[:"#{top}_bytes"] += size
end
result.to_h
end

sig { params(source: Manifest, destination: Manifest).returns(Comparison) }
def self.compare(source, destination)
missing = source.sizes.keys - destination.sizes.keys
extra = destination.sizes.keys - source.sizes.keys
mismatches = (source.sizes.keys & destination.sizes.keys).filter_map do |path|
a = T.must(source.sizes[path])
b = T.must(destination.sizes[path])
[path, a, b] if a != b
end
Comparison.new(
source_summary: source.summary,
destination_summary: destination.summary,
missing_from_destination: missing.sort,
extra_in_destination: extra.sort,
size_mismatches: mismatches.sort_by(&:first)
)
end
end
end
end
Loading
Loading