Repository navigation
Add SQLite copy and Elasticsearch reindex tasks for the move #1617
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
benrfairless
wants to merge
5
commits into
feature/1579-new-server
Choose a base branch
from
feature/1589-sqlite-and-reindex-tasks
base: feature/1579-new-server
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from 3 commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
a8878a6
Add rsync tasks for the SQLite bulk copy and delta
benrfairless 5a4e631
Add tasks to reindex Elasticsearch and check counts
benrfairless c3ce662
Document the SQLite and Elasticsearch move
benrfairless fd208b2
Fix manifest and rsync edge cases from review
benrfairless d885ea0
Use one shared data directory for SQLite copy
benrfairless File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,119 @@ | ||
| # 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) | ||
|
|
||
| prefix = File.join(File.expand_path(root), "") | ||
| sizes = T.let({}, T::Hash[String, Integer]) | ||
| Find.find(File.expand_path(root)) do |path| | ||
| stat = File.lstat(path) | ||
| next unless stat.file? | ||
|
|
||
| sizes[path.delete_prefix(prefix)] = stat.size | ||
| end | ||
| new(sizes) | ||
| end | ||
|
|
||
| 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? | ||
|
|
||
| path, size = line.split("\t", 2) | ||
| raise ArgumentError, "line #{number} is not path<TAB>size" unless path && 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 | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.