Skip to content

Commit

Permalink
DEV(cache_critical_dns): add option to run once and exit
Browse files Browse the repository at this point in the history
There are situations where a container running Discourse may want to
cache the critical DNS services without running the cache_critical_dns
service, for example running migrations prior to running a full bore
application container.

Add a `--once` argument for the cache_critical_dns script that will
only execute the main loop once, and return the status code for the
script to use when exiting. 0 indicates no errors occured during SRV
resolution, and 1 indicates a failure during the SRV lookup.

Nothing is reported to prometheus in run_once mode. Generally this
mode of operation would be a part of a unix pipeline, in which the exit
status is a more meaningful and immediate signal than a prometheus metric.

The reporting has been moved into it's own method that can be called
only when the script is running as a service.

See /t/69597.
  • Loading branch information
fitzy101 committed Jul 6, 2022
1 parent 6c49ec3 commit 1867202
Showing 1 changed file with 27 additions and 6 deletions.
33 changes: 27 additions & 6 deletions script/cache_critical_dns
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
#!/usr/bin/env ruby
# frozen_string_literal: true

require 'optparse'

# cache_critical_dns is intended to be used for performing DNS lookups against
# the services critical for Discourse to run - PostgreSQL and Redis. The
# cache mechanism is storing the resolved host addresses in /etc/hosts. This can
Expand Down Expand Up @@ -360,6 +362,15 @@ def env_srv_name(env_name)
nilempty(ENV[env_srv_var(env_name)])
end

def run_and_report(hostname_vars)
errors = run(hostname_vars)
if errors.empty?
report_success
else
report_failure(errors)
end
end

def run(hostname_vars)
# HOSTNAME: [IP_ADDRESS, ...]
# this will usually be a single address
Expand Down Expand Up @@ -411,11 +422,7 @@ rescue => e
error("DNS lookup failed: #{e}")
errors[nil] = 1
ensure
if errors == {}
report_success
else
report_failure(errors)
end
return errors
end

# If any of the host variables are an explicit IP we will not attempt to cache
Expand Down Expand Up @@ -448,7 +455,21 @@ CRITICAL_HOST_ENV_VARS.each do |v|
end
end

options = {
once: false,
}
OptionParser.new do |opts|
opts.on("--once", "run script once instead of indefinitely") do |o|
options[:once] = true
end
end.parse!

if options[:once]
errors = run(all_hostname_vars)
exit errors.empty? ? 0 : 1
end

while true
run(all_hostname_vars)
run_and_report(all_hostname_vars)
sleep REFRESH_SECONDS
end

0 comments on commit 1867202

Please sign in to comment.