2020-06-02 13:37:38 +03:00
|
|
|
defmodule Plausible.Workers.ProvisionSslCertificates do
|
2020-02-26 11:54:21 +03:00
|
|
|
use Plausible.Repo
|
2020-07-03 11:33:43 +03:00
|
|
|
use Oban.Worker, queue: :provision_ssl_certificates, max_attempts: 1
|
2020-07-03 11:01:07 +03:00
|
|
|
require Logger
|
2021-04-14 15:31:36 +03:00
|
|
|
@timeout 20_000
|
2020-02-26 11:54:21 +03:00
|
|
|
|
2020-06-02 13:37:38 +03:00
|
|
|
@impl Oban.Worker
|
2020-06-04 14:33:54 +03:00
|
|
|
def perform(_args, _job, ssh \\ SSHEx) do
|
2020-06-04 20:25:13 +03:00
|
|
|
config = get_config()
|
|
|
|
|
2020-06-08 10:35:13 +03:00
|
|
|
{:ok, conn} =
|
|
|
|
ssh.connect(
|
|
|
|
ip: to_charlist(config[:ip]),
|
|
|
|
user: to_charlist(config[:user]),
|
|
|
|
password: to_charlist(config[:password])
|
|
|
|
)
|
2020-06-04 14:33:54 +03:00
|
|
|
|
2020-06-08 10:35:13 +03:00
|
|
|
recent_custom_domains =
|
|
|
|
Repo.all(
|
|
|
|
from cd in Plausible.Site.CustomDomain,
|
|
|
|
where: cd.updated_at > fragment("now() - '3 days'::interval"),
|
|
|
|
where: not cd.has_ssl_certificate
|
|
|
|
)
|
2020-02-26 11:54:21 +03:00
|
|
|
|
|
|
|
for domain <- recent_custom_domains do
|
2021-04-14 15:04:53 +03:00
|
|
|
{:ok, res, code} =
|
|
|
|
ssh.run(
|
|
|
|
conn,
|
2021-04-14 15:31:36 +03:00
|
|
|
'sudo certbot certonly --webroot -w /root/webroot -n -d \"#{domain.domain}\"',
|
|
|
|
channel_timeout: @timeout,
|
|
|
|
exec_timeout: @timeout
|
2021-04-14 15:04:53 +03:00
|
|
|
)
|
|
|
|
|
2020-06-04 14:33:54 +03:00
|
|
|
report_result({res, code}, domain)
|
2020-02-26 11:54:21 +03:00
|
|
|
end
|
2020-06-08 10:35:13 +03:00
|
|
|
|
2020-06-04 20:25:13 +03:00
|
|
|
:ok
|
2020-02-26 11:54:21 +03:00
|
|
|
end
|
|
|
|
|
|
|
|
defp report_result({_, 0}, domain) do
|
2020-06-08 10:35:13 +03:00
|
|
|
Ecto.Changeset.change(domain, has_ssl_certificate: true) |> Repo.update!()
|
2020-02-26 11:54:21 +03:00
|
|
|
Plausible.Slack.notify("Obtained SSL cert for #{domain.domain}")
|
2020-06-02 13:37:38 +03:00
|
|
|
:ok
|
2020-02-26 11:54:21 +03:00
|
|
|
end
|
|
|
|
|
|
|
|
defp report_result({error_msg, error_code}, domain) do
|
2021-03-30 15:51:05 +03:00
|
|
|
Logger.warn(
|
2021-03-03 12:36:19 +03:00
|
|
|
"Error obtaining SSL certificate for #{domain.domain}: #{error_msg} (code=#{error_code})"
|
2020-06-08 10:35:13 +03:00
|
|
|
)
|
|
|
|
|
|
|
|
# Failing to obtain is expected, not a failure for the job queue
|
|
|
|
:ok
|
2020-02-26 11:54:21 +03:00
|
|
|
end
|
2020-06-04 20:25:13 +03:00
|
|
|
|
|
|
|
defp get_config() do
|
|
|
|
Application.get_env(:plausible, :custom_domain_server)
|
|
|
|
end
|
2020-02-26 11:54:21 +03:00
|
|
|
end
|