domains_cli.rb 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. # frozen_string_literal: true
  2. require 'concurrent'
  3. require_relative '../../config/boot'
  4. require_relative '../../config/environment'
  5. require_relative 'cli_helper'
  6. module Mastodon
  7. class DomainsCLI < Thor
  8. include CLIHelper
  9. def self.exit_on_failure?
  10. true
  11. end
  12. option :concurrency, type: :numeric, default: 5, aliases: [:c]
  13. option :verbose, type: :boolean, aliases: [:v]
  14. option :dry_run, type: :boolean
  15. option :limited_federation_mode, type: :boolean
  16. option :by_uri, type: :boolean
  17. desc 'purge [DOMAIN...]', 'Remove accounts from a DOMAIN without a trace'
  18. long_desc <<-LONG_DESC
  19. Remove all accounts from a given DOMAIN without leaving behind any
  20. records. Unlike a suspension, if the DOMAIN still exists in the wild,
  21. it means the accounts could return if they are resolved again.
  22. When the --limited-federation-mode option is given, instead of purging accounts
  23. from a single domain, all accounts from domains that have not been explicitly allowed
  24. are removed from the database.
  25. When the --by-uri option is given, DOMAIN is used to match the domain part of actor
  26. URIs rather than the domain part of the webfinger handle. For instance, an account
  27. that has the handle `foo@bar.com` but whose profile is at the URL
  28. `https://mastodon-bar.com/users/foo`, would be purged by either
  29. `tootctl domains purge bar.com` or `tootctl domains purge --by-uri mastodon-bar.com`.
  30. LONG_DESC
  31. def purge(*domains)
  32. dry_run = options[:dry_run] ? ' (DRY RUN)' : ''
  33. scope = begin
  34. if options[:limited_federation_mode]
  35. Account.remote.where.not(domain: DomainAllow.pluck(:domain))
  36. elsif !domains.empty?
  37. if options[:by_uri]
  38. domains.map { |domain| Account.remote.where(Account.arel_table[:uri].matches("https://#{domain}/%", false, true)) }.reduce(:or)
  39. else
  40. Account.remote.where(domain: domains)
  41. end
  42. else
  43. say('No domain(s) given', :red)
  44. exit(1)
  45. end
  46. end
  47. processed, = parallelize_with_progress(scope) do |account|
  48. DeleteAccountService.new.call(account, reserve_username: false, skip_side_effects: true) unless options[:dry_run]
  49. end
  50. DomainBlock.where(domain: domains).destroy_all unless options[:dry_run]
  51. say("Removed #{processed} accounts#{dry_run}", :green)
  52. custom_emojis = CustomEmoji.where(domain: domains)
  53. custom_emojis_count = custom_emojis.count
  54. custom_emojis.destroy_all unless options[:dry_run]
  55. Instance.refresh unless options[:dry_run]
  56. say("Removed #{custom_emojis_count} custom emojis", :green)
  57. end
  58. option :concurrency, type: :numeric, default: 50, aliases: [:c]
  59. option :format, type: :string, default: 'summary', aliases: [:f]
  60. option :exclude_suspended, type: :boolean, default: false, aliases: [:x]
  61. desc 'crawl [START]', 'Crawl all known peers, optionally beginning at START'
  62. long_desc <<-LONG_DESC
  63. Crawl the fediverse by using the Mastodon REST API endpoints that expose
  64. all known peers, and collect statistics from those peers, as long as those
  65. peers support those API endpoints. When no START is given, the command uses
  66. this server's own database of known peers to seed the crawl.
  67. The --concurrency (-c) option controls the number of threads performing HTTP
  68. requests at the same time. More threads means the crawl may complete faster.
  69. The --format (-f) option controls how the data is displayed at the end. By
  70. default (`summary`), a summary of the statistics is returned. The other options
  71. are `domains`, which returns a newline-delimited list of all discovered peers,
  72. and `json`, which dumps all the aggregated data raw.
  73. The --exclude-suspended (-x) option means that domains that are suspended
  74. instance-wide do not appear in the output and are not included in summaries.
  75. This also excludes subdomains of any of those domains.
  76. LONG_DESC
  77. def crawl(start = nil)
  78. stats = Concurrent::Hash.new
  79. processed = Concurrent::AtomicFixnum.new(0)
  80. failed = Concurrent::AtomicFixnum.new(0)
  81. start_at = Time.now.to_f
  82. seed = start ? [start] : Instance.pluck(:domain)
  83. blocked_domains = Regexp.new('\\.?' + DomainBlock.where(severity: 1).pluck(:domain).join('|') + '$')
  84. progress = create_progress_bar
  85. pool = Concurrent::ThreadPoolExecutor.new(min_threads: 0, max_threads: options[:concurrency], idletime: 10, auto_terminate: true, max_queue: 0)
  86. work_unit = ->(domain) do
  87. next if stats.key?(domain)
  88. next if options[:exclude_suspended] && domain.match?(blocked_domains)
  89. stats[domain] = nil
  90. begin
  91. Request.new(:get, "https://#{domain}/api/v1/instance").perform do |res|
  92. next unless res.code == 200
  93. stats[domain] = Oj.load(res.to_s)
  94. end
  95. Request.new(:get, "https://#{domain}/api/v1/instance/peers").perform do |res|
  96. next unless res.code == 200
  97. Oj.load(res.to_s).reject { |peer| stats.key?(peer) }.each do |peer|
  98. pool.post(peer, &work_unit)
  99. end
  100. end
  101. Request.new(:get, "https://#{domain}/api/v1/instance/activity").perform do |res|
  102. next unless res.code == 200
  103. stats[domain]['activity'] = Oj.load(res.to_s)
  104. end
  105. rescue StandardError
  106. failed.increment
  107. ensure
  108. processed.increment
  109. progress.increment unless progress.finished?
  110. end
  111. end
  112. seed.each do |domain|
  113. pool.post(domain, &work_unit)
  114. end
  115. sleep 20
  116. sleep 20 until pool.queue_length.zero?
  117. pool.shutdown
  118. pool.wait_for_termination(20)
  119. ensure
  120. progress.finish
  121. pool.shutdown
  122. case options[:format]
  123. when 'summary'
  124. stats_to_summary(stats, processed, failed, start_at)
  125. when 'domains'
  126. stats_to_domains(stats)
  127. when 'json'
  128. stats_to_json(stats)
  129. end
  130. end
  131. private
  132. def stats_to_summary(stats, processed, failed, start_at)
  133. stats.compact!
  134. total_domains = stats.size
  135. total_users = stats.reduce(0) { |sum, (_key, val)| val.is_a?(Hash) && val['stats'].is_a?(Hash) ? sum + val['stats']['user_count'].to_i : sum }
  136. total_active = stats.reduce(0) { |sum, (_key, val)| val.is_a?(Hash) && val['activity'].is_a?(Array) && val['activity'].size > 2 && val['activity'][1].is_a?(Hash) ? sum + val['activity'][1]['logins'].to_i : sum }
  137. total_joined = stats.reduce(0) { |sum, (_key, val)| val.is_a?(Hash) && val['activity'].is_a?(Array) && val['activity'].size > 2 && val['activity'][1].is_a?(Hash) ? sum + val['activity'][1]['registrations'].to_i : sum }
  138. say("Visited #{processed.value} domains, #{failed.value} failed (#{(Time.now.to_f - start_at).round}s elapsed)", :green)
  139. say("Total servers: #{total_domains}", :green)
  140. say("Total registered: #{total_users}", :green)
  141. say("Total active last week: #{total_active}", :green)
  142. say("Total joined last week: #{total_joined}", :green)
  143. end
  144. def stats_to_domains(stats)
  145. say(stats.keys.join("\n"))
  146. end
  147. def stats_to_json(stats)
  148. stats.compact!
  149. say(Oj.dump(stats))
  150. end
  151. end
  152. end