mirror of
https://github.com/retspen/webvirtcloud
synced 2026-12-02 08:56:07 +00:00
feat(alerts): mail and webhook alerts, and /healthz for a monitor
A failed backup, a scheduled backup not taken, backups the daily check finds missing and a job that ends uncertain could only be seen on the pages. They are now queued as alerts in the transaction of the change they tell of (never stopping it) and sent by the worker's periodic pass to the Settings page's alert e-mail addresses (the server's SMTP settings) and alert webhook (a JSON POST), each tried again for ten passes on its own. A skip for a host in maintenance is no alert. Setting values take 255 characters. /healthz answers 200 while the database answers and the job worker runs, 503 otherwise, without a login.
This commit is contained in:
parent
2cf7dbe577
commit
dcd7e32df7
21 changed files with 695 additions and 74 deletions
|
|
@ -486,6 +486,12 @@ Set `OTP_ENABLED = True` in `settings.py` to ask for a one-time code at login. I
|
|||
|
||||
The QR code is mailed as a link to a page that shows it, good for one hour: the mail does not hold the code's secret. Email OTP QR code on a user's page (Users) sends it; Lost OTP? on the login page sends it to an enrolled user who gives their address.
|
||||
|
||||
### Alerts
|
||||
|
||||
On the Settings page (Alerts), **Alert e-mail addresses** get a mail, through the server's SMTP settings (`EMAIL_HOST` and the others, as for OTP), and **Alert webhook** a JSON POST (`subject`, `text`, `time`; Slack, Mattermost and ntfy take it) when a backup job fails, a scheduled backup is not taken (not for a host in maintenance), the daily target check finds backups missing, a verification finds a backup damaged, or a job ends uncertain. The job worker sends them within a minute and tries a failed channel again for ten minutes.
|
||||
|
||||
`/healthz`, without a login, answers 200 while the database answers and the job worker runs, 503 otherwise: point a monitor at it.
|
||||
|
||||
### Serial console
|
||||
|
||||
A VM without graphics (no `<graphics>` device, a `<console type='pty'>`) opens a serial console (xterm.js) instead of VNC. It is off by default. To turn it on, set `WEBVIRTCLOUD_SERIAL_CONSOLE=1` (Docker: in `docker-compose.override.yml`, then `docker compose up -d`) or `SERIAL_CONSOLE_ENABLED = True` in `settings.py` and `systemctl restart webvirt-cloud webvirt-socketiod`.
|
||||
|
|
|
|||
35
appsettings/migrations/0027_alert_settings.py
Normal file
35
appsettings/migrations/0027_alert_settings.py
Normal file
|
|
@ -0,0 +1,35 @@
|
|||
from django.core.management.color import no_style
|
||||
from django.db import migrations, models
|
||||
from django.utils.translation import gettext_noop as _
|
||||
|
||||
SETTINGS = (
|
||||
(_("Alert e-mail addresses"), "ALERT_EMAILS",
|
||||
_("Comma-separated; mailed when a backup fails, is skipped, missing or damaged, or a job is uncertain")),
|
||||
(_("Alert webhook"), "ALERT_WEBHOOK", _("An http(s) URL that gets the same alerts as a JSON POST (subject, text, time)")),
|
||||
)
|
||||
|
||||
|
||||
def add_settings(apps, schema_editor):
|
||||
setting = apps.get_model("appsettings", "AppSettings")
|
||||
db_alias = schema_editor.connection.alias
|
||||
# see 0014: move a PostgreSQL id sequence past the fixed ids first
|
||||
with schema_editor.connection.cursor() as cursor:
|
||||
for sql in schema_editor.connection.ops.sequence_reset_sql(no_style(), [setting]):
|
||||
cursor.execute(sql)
|
||||
for name, key, description in SETTINGS:
|
||||
setting.objects.using(db_alias).get_or_create(
|
||||
key=key, defaults={"name": name, "value": "", "choices": "", "description": description})
|
||||
|
||||
|
||||
def del_settings(apps, schema_editor):
|
||||
apps.get_model("appsettings", "AppSettings").objects.using(schema_editor.connection.alias).filter(
|
||||
key__in=[key for _name, key, _description in SETTINGS]).delete()
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
dependencies = [("appsettings", "0026_repair_number_settings")]
|
||||
|
||||
operations = [
|
||||
migrations.AlterField("appsettings", "value", models.CharField(max_length=255, verbose_name="value")),
|
||||
migrations.RunPython(add_settings, del_settings),
|
||||
]
|
||||
|
|
@ -8,6 +8,6 @@ class AppSettings(models.Model):
|
|||
|
||||
name = models.CharField(_("name"), max_length=25, null=False)
|
||||
key = models.CharField(_("key"), db_index=True, max_length=50, unique=True)
|
||||
value = models.CharField(_("value"), max_length=25)
|
||||
value = models.CharField(_("value"), max_length=255)
|
||||
choices = models.CharField(_("choices"), max_length=70)
|
||||
description = models.CharField(_("description"), max_length=100, null=True)
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
from django.db import DatabaseError
|
||||
from django.db import Error as DatabaseError
|
||||
|
||||
from .models import AppSettings
|
||||
|
||||
|
|
|
|||
|
|
@ -86,7 +86,7 @@
|
|||
min="{{ setting.bounds.0 }}" max="{{ setting.bounds.1 }}" step="1" required aria-describedby="help-{{ setting.key }}">
|
||||
{% else %}
|
||||
<input id="setting-{{ setting.key }}" class="form-control" type="text" name="{{ setting.key }}" value="{{ setting.value }}"
|
||||
maxlength="25" aria-describedby="help-{{ setting.key }}">
|
||||
maxlength="255" aria-describedby="help-{{ setting.key }}">
|
||||
{% endif %}
|
||||
{% endif %}
|
||||
<input type="hidden" name="was-{{ setting.key }}" value="{{ setting.value }}">
|
||||
|
|
|
|||
|
|
@ -1,8 +1,11 @@
|
|||
import re
|
||||
from urllib.parse import urlsplit
|
||||
from pathlib import Path
|
||||
|
||||
from admin.decorators import superuser_only
|
||||
from django.conf import settings
|
||||
from django.core.exceptions import ValidationError
|
||||
from django.core.validators import URLValidator, validate_email
|
||||
from django.contrib import messages
|
||||
from django.db import DatabaseError, transaction
|
||||
from django.http import HttpResponseRedirect
|
||||
|
|
@ -33,6 +36,9 @@ NUMBERS = {
|
|||
}
|
||||
|
||||
|
||||
# settings whose values the audit log does not show
|
||||
SECRET_SETTINGS = {"ALERT_WEBHOOK"}
|
||||
|
||||
# the Settings page's groups, in order; a setting in none shows under Other. The
|
||||
# titles stay English here: the page links them by slug and translates them
|
||||
GROUPS = [
|
||||
|
|
@ -50,6 +56,7 @@ GROUPS = [
|
|||
(gettext_noop("Snapshots and jobs"), ["SNAPSHOT_FREE_SPACE_PERCENT", "SNAPSHOT_FREE_SPACE_MIN_GIB",
|
||||
"WORKER_CONCURRENCY", "JOB_RETENTION_DAYS"]),
|
||||
(gettext_noop("Login"), ["LOGIN_FAILURE_LIMIT", "LOGIN_LOCKOUT_MINUTES"]),
|
||||
(gettext_noop("Alerts"), ["ALERT_EMAILS", "ALERT_WEBHOOK"]),
|
||||
(gettext_noop("Lists and pages"), ["VIEW_INSTANCES_LIST_STYLE", "VM_DRBD_STATUS", "LOGS_PER_PAGE",
|
||||
"LOG_RETENTION_DAYS"]),
|
||||
]
|
||||
|
|
@ -71,6 +78,16 @@ def refusal(setting, value):
|
|||
elif setting.key == "CLONE_INSTANCE_DEFAULT_PREFIX" and not re.fullmatch(r"[a-zA-Z0-9-]+", value):
|
||||
# a clone's name is the prefix and a number, and takes only these
|
||||
return _("%(setting)s takes letters, digits and '-' only") % {"setting": setting.name}
|
||||
try:
|
||||
if setting.key == "ALERT_EMAILS":
|
||||
for address in filter(None, (a.strip() for a in value.split(","))):
|
||||
validate_email(address)
|
||||
elif setting.key == "ALERT_WEBHOOK" and value.strip():
|
||||
URLValidator(schemes=["http", "https"])(value.strip())
|
||||
if "@" in urlsplit(value.strip()).netloc: # urllib would take user:password@ for the host
|
||||
raise ValidationError("credentials in the URL")
|
||||
except ValidationError:
|
||||
return _("%(setting)s: %(value)s is not an e-mail address or an http(s) URL") % {"setting": setting.name, "value": value}
|
||||
return None
|
||||
|
||||
|
||||
|
|
@ -121,7 +138,9 @@ def appsettings(request):
|
|||
for refused in refusals:
|
||||
messages.error(request, refused)
|
||||
if changed and not refusals:
|
||||
action = "change " + ", ".join(f"{s.name} to {value}" for s, value in changed)
|
||||
# a webhook URL is a secret of its own (Slack's): not in the log
|
||||
action = "change " + ", ".join(f"{s.name} to {'(not shown)' if s.key in SECRET_SETTINGS else value}"
|
||||
for s, value in changed)
|
||||
try:
|
||||
# one row, and all of the group or none of it
|
||||
with audit(request, None, "Settings", action), transaction.atomic():
|
||||
|
|
|
|||
Binary file not shown.
|
|
@ -11,7 +11,7 @@ msgid ""
|
|||
msgstr ""
|
||||
"Project-Id-Version: PACKAGE VERSION\n"
|
||||
"Report-Msgid-Bugs-To: \n"
|
||||
"POT-Creation-Date: 2026-11-19 13:08+0000\n"
|
||||
"POT-Creation-Date: 2026-11-19 13:10+0000\n"
|
||||
"PO-Revision-Date: 2020-11-04 12:00+0000\n"
|
||||
"Last-Translator: catborise <muhammetalisag@gmail.com>, 2020\n"
|
||||
"Language-Team: Turkish (https://www.transifex.com/catborise/teams/110663/tr/)\n"
|
||||
|
|
@ -1889,6 +1889,28 @@ msgid "Network card model chosen first for a new VM (default: VirtIO)"
|
|||
msgstr ""
|
||||
"Yeni bir sanal makine için önce seçilen ağ kartı modeli (default: VirtIO)"
|
||||
|
||||
#: appsettings/migrations/0027_alert_settings.py:6
|
||||
msgid "Alert e-mail addresses"
|
||||
msgstr "Uyarı e-posta adresleri"
|
||||
|
||||
#: appsettings/migrations/0027_alert_settings.py:7
|
||||
msgid ""
|
||||
"Comma-separated; mailed when a backup fails, is skipped, missing or damaged, "
|
||||
"or a job is uncertain"
|
||||
msgstr ""
|
||||
"Virgülle ayrılmış; bir yedek başarısız olunca, atlanınca, kaybolunca ya da "
|
||||
"hasarlı çıkınca veya bir iş belirsiz kalınca e-posta gider"
|
||||
|
||||
#: appsettings/migrations/0027_alert_settings.py:8
|
||||
msgid "Alert webhook"
|
||||
msgstr "Uyarı webhook'u"
|
||||
|
||||
#: appsettings/migrations/0027_alert_settings.py:8
|
||||
msgid ""
|
||||
"An http(s) URL that gets the same alerts as a JSON POST (subject, text, time)"
|
||||
msgstr ""
|
||||
"Aynı uyarıları JSON POST olarak alan bir http(s) adresi (subject, text, time)"
|
||||
|
||||
#: appsettings/models.py:10
|
||||
msgid "key"
|
||||
msgstr "anahtar"
|
||||
|
|
@ -1944,89 +1966,98 @@ msgstr "Temayı değiştir"
|
|||
msgid "Save %(group_title)s"
|
||||
msgstr "%(group_title)s kaydet"
|
||||
|
||||
#: appsettings/views.py:39
|
||||
#: appsettings/views.py:45
|
||||
msgid "New VM defaults"
|
||||
msgstr "Yeni sanal makine varsayılanları"
|
||||
|
||||
#: appsettings/views.py:42 instances/templates/instance.html:71
|
||||
#: appsettings/views.py:48 instances/templates/instance.html:71
|
||||
#: instances/templates/instances/destroy_instance_form.html:33
|
||||
#: instances/templates/instances/resize_tab.html:21
|
||||
#: instances/templates/instances/settings_tab.html:197
|
||||
msgid "Disks"
|
||||
msgstr "Diskler"
|
||||
|
||||
#: appsettings/views.py:46
|
||||
#: appsettings/views.py:52
|
||||
msgid "Clones"
|
||||
msgstr "Klonlar"
|
||||
|
||||
#: appsettings/views.py:47 console/templates/console-base.html:10
|
||||
#: appsettings/views.py:53 console/templates/console-base.html:10
|
||||
#: console/templates/console-base.html:23
|
||||
#: instances/templates/instance_actions.html:11
|
||||
#: instances/templates/instances/settings_tab.html:32
|
||||
msgid "Console"
|
||||
msgstr "Konsol"
|
||||
|
||||
#: appsettings/views.py:48
|
||||
#: appsettings/views.py:54
|
||||
msgid "VM access and owners"
|
||||
msgstr "Sanal makine erişimi ve sahipleri"
|
||||
|
||||
#: appsettings/views.py:50
|
||||
#: appsettings/views.py:56
|
||||
msgid "Snapshots and jobs"
|
||||
msgstr "Anlık görüntüler ve işler"
|
||||
|
||||
#: appsettings/views.py:52
|
||||
#: appsettings/views.py:58
|
||||
msgid "Login"
|
||||
msgstr "Oturum açma"
|
||||
|
||||
#: appsettings/views.py:53
|
||||
#: appsettings/views.py:59
|
||||
msgid "Alerts"
|
||||
msgstr "Uyarılar"
|
||||
|
||||
#: appsettings/views.py:60
|
||||
msgid "Lists and pages"
|
||||
msgstr "Listeler ve sayfalar"
|
||||
|
||||
#: appsettings/views.py:61
|
||||
#: appsettings/views.py:68
|
||||
#, python-format
|
||||
msgid "%(setting)s takes at most %(length)s characters"
|
||||
msgstr "%(setting)s en fazla %(length)s karakter alır"
|
||||
|
||||
#: appsettings/views.py:66
|
||||
#: appsettings/views.py:73
|
||||
#, python-format
|
||||
msgid "%(setting)s must be a whole number between %(low)s and %(high)s"
|
||||
msgstr "%(setting)s, %(low)s ile %(high)s arasında bir tam sayı olmalıdır"
|
||||
|
||||
#: appsettings/views.py:69
|
||||
#: appsettings/views.py:76
|
||||
#, python-format
|
||||
msgid "%(setting)s must be one of %(choices)s"
|
||||
msgstr "%(setting)s şunlardan biri olmalıdır: %(choices)s"
|
||||
|
||||
#: appsettings/views.py:73
|
||||
#: appsettings/views.py:80
|
||||
#, python-format
|
||||
msgid "%(setting)s takes letters, digits and '-' only"
|
||||
msgstr "%(setting)s yalnızca harf, rakam ve '-' alır"
|
||||
|
||||
#: appsettings/views.py:82
|
||||
#: appsettings/views.py:90
|
||||
#, python-format
|
||||
msgid "%(setting)s: %(value)s is not an e-mail address or an http(s) URL"
|
||||
msgstr "%(setting)s: %(value)s bir e-posta adresi ya da http(s) adresi değil"
|
||||
|
||||
#: appsettings/views.py:99
|
||||
msgid "Disk I/O native needs disk cache none or directsync"
|
||||
msgstr ""
|
||||
"Disk G/Ç native, disk önbelleği none veya directsync olmasını gerektirir"
|
||||
|
||||
#: appsettings/views.py:99
|
||||
#: appsettings/views.py:116
|
||||
#, python-format
|
||||
msgid "Unknown theme: %(theme)s"
|
||||
msgstr "Bilinmeyen tema: %(theme)s"
|
||||
|
||||
#: appsettings/views.py:105
|
||||
#: appsettings/views.py:122
|
||||
#, python-format
|
||||
msgid "Theme is changed. Now: %(theme)s"
|
||||
msgstr "Tema değiştirildi. Şimdi: %(theme)s"
|
||||
|
||||
#: appsettings/views.py:140
|
||||
#: appsettings/views.py:159
|
||||
#, python-format
|
||||
msgid "Saved: %(settings)s"
|
||||
msgstr "Kaydedildi: %(settings)s"
|
||||
|
||||
#: appsettings/views.py:142
|
||||
#: appsettings/views.py:161
|
||||
msgid "Nothing changed"
|
||||
msgstr "Hiçbir şey değişmedi"
|
||||
|
||||
#: appsettings/views.py:149 vrtManager/nodedevs.py:294
|
||||
#: appsettings/views.py:168 vrtManager/nodedevs.py:294
|
||||
#: vrtManager/nodedevs.py:333
|
||||
msgid "Other"
|
||||
msgstr "Diğer"
|
||||
|
|
@ -8713,15 +8744,48 @@ msgstr "Bu iş başladıktan sonra iptal edilemez"
|
|||
msgid "The job has already ended"
|
||||
msgstr "İş zaten bitti"
|
||||
|
||||
#: operations/jobs.py:275
|
||||
#: operations/jobs.py:278
|
||||
#, python-format
|
||||
msgid "%(kind)s: %(resource)s"
|
||||
msgstr "%(kind)s: %(resource)s"
|
||||
|
||||
#: operations/jobs.py:283
|
||||
msgid "No reason was given"
|
||||
msgstr "Bir neden verilmedi"
|
||||
|
||||
#: operations/jobs.py:285
|
||||
#, python-format
|
||||
msgid "Job ended uncertain: %(job)s"
|
||||
msgstr "İş belirsiz bitti: %(job)s"
|
||||
|
||||
#: operations/jobs.py:286
|
||||
#, python-format
|
||||
msgid ""
|
||||
"Job #%(id)s (%(job)s) ended uncertain; it keeps what it holds until a "
|
||||
"superuser resolves it on its page. %(error)s"
|
||||
msgstr ""
|
||||
"#%(id)s numaralı iş (%(job)s) belirsiz bitti; bir süper kullanıcı sayfasında "
|
||||
"çözene kadar tuttuklarını bırakmaz. %(error)s"
|
||||
|
||||
#: operations/jobs.py:289
|
||||
#, python-format
|
||||
msgid "Job failed: %(job)s"
|
||||
msgstr "İş başarısız: %(job)s"
|
||||
|
||||
#: operations/jobs.py:290
|
||||
#, python-format
|
||||
msgid "Job #%(id)s (%(job)s) failed: %(error)s"
|
||||
msgstr "#%(id)s numaralı iş (%(job)s) başarısız: %(error)s"
|
||||
|
||||
#: operations/jobs.py:297
|
||||
msgid "Choose succeeded or failed"
|
||||
msgstr "Başarılı ya da başarısız seçin"
|
||||
|
||||
#: operations/jobs.py:278
|
||||
#: operations/jobs.py:300
|
||||
msgid "Write a note on what was checked"
|
||||
msgstr "Neyin kontrol edildiğine dair bir not yazın"
|
||||
|
||||
#: operations/jobs.py:282
|
||||
#: operations/jobs.py:304
|
||||
msgid "Only an uncertain job can be resolved"
|
||||
msgstr "Yalnızca belirsiz bir iş çözülebilir"
|
||||
|
||||
|
|
@ -10404,7 +10468,12 @@ msgstr ""
|
|||
msgid "Check backup target"
|
||||
msgstr "Yedek hedefini denetle"
|
||||
|
||||
#: vmbackups/jobs.py:1600
|
||||
#: vmbackups/jobs.py:1603
|
||||
#, python-format
|
||||
msgid "Backups missing from %(target)s"
|
||||
msgstr "%(target)s hedefinde kayıp yedekler"
|
||||
|
||||
#: vmbackups/jobs.py:1604 vmbackups/jobs.py:1606
|
||||
#, python-format
|
||||
msgid "Files of these backups are missing from the target: %(backups)s"
|
||||
msgstr "Şu yedeklerin dosyaları hedefte yok: %(backups)s"
|
||||
|
|
@ -10421,6 +10490,16 @@ msgstr "Sunucu bakımdaydı"
|
|||
msgid "The schedule's owner is no longer an active superuser"
|
||||
msgstr "Zamanlamanın sahibi artık etkin bir süper kullanıcı değil"
|
||||
|
||||
#: vmbackups/schedule.py:92
|
||||
#, python-format
|
||||
msgid "Scheduled backup not taken: %(vm)s"
|
||||
msgstr "Zamanlanmış yedek alınmadı: %(vm)s"
|
||||
|
||||
#: vmbackups/schedule.py:93
|
||||
#, python-format
|
||||
msgid "The schedule %(schedule)s did not back up %(vm)s on %(day)s: %(reason)s"
|
||||
msgstr "%(schedule)s planı %(day)s günü %(vm)s yedeğini almadı: %(reason)s"
|
||||
|
||||
#: vmbackups/templates/vmbackups/consistency.html:1
|
||||
msgid "While shut off"
|
||||
msgstr "Kapalıyken"
|
||||
|
|
|
|||
Binary file not shown.
|
|
@ -7,7 +7,7 @@ msgid ""
|
|||
msgstr ""
|
||||
"Project-Id-Version: \n"
|
||||
"Report-Msgid-Bugs-To: \n"
|
||||
"POT-Creation-Date: 2026-11-19 13:08+0000\n"
|
||||
"POT-Creation-Date: 2026-11-19 13:10+0000\n"
|
||||
"PO-Revision-Date: \n"
|
||||
"Last-Translator: \n"
|
||||
"Language-Team: \n"
|
||||
|
|
@ -1814,6 +1814,25 @@ msgstr "VNC 控制台启动时裁剪到窗口大小,不缩放"
|
|||
msgid "Network card model chosen first for a new VM (default: VirtIO)"
|
||||
msgstr "新建虚拟机默认选择的网卡型号(默认:VirtIO)"
|
||||
|
||||
#: appsettings/migrations/0027_alert_settings.py:6
|
||||
msgid "Alert e-mail addresses"
|
||||
msgstr "告警邮件地址"
|
||||
|
||||
#: appsettings/migrations/0027_alert_settings.py:7
|
||||
msgid ""
|
||||
"Comma-separated; mailed when a backup fails, is skipped, missing or damaged, "
|
||||
"or a job is uncertain"
|
||||
msgstr "逗号分隔;备份失败、被跳过、丢失或损坏,或作业状态不确定时发送邮件"
|
||||
|
||||
#: appsettings/migrations/0027_alert_settings.py:8
|
||||
msgid "Alert webhook"
|
||||
msgstr "告警 Webhook"
|
||||
|
||||
#: appsettings/migrations/0027_alert_settings.py:8
|
||||
msgid ""
|
||||
"An http(s) URL that gets the same alerts as a JSON POST (subject, text, time)"
|
||||
msgstr "以 JSON POST 接收相同告警的 http(s) URL(subject、text、time)"
|
||||
|
||||
#: appsettings/models.py:10
|
||||
msgid "key"
|
||||
msgstr "键"
|
||||
|
|
@ -1869,88 +1888,97 @@ msgstr "更改主题"
|
|||
msgid "Save %(group_title)s"
|
||||
msgstr "保存%(group_title)s"
|
||||
|
||||
#: appsettings/views.py:39
|
||||
#: appsettings/views.py:45
|
||||
msgid "New VM defaults"
|
||||
msgstr "新建虚拟机默认值"
|
||||
|
||||
#: appsettings/views.py:42 instances/templates/instance.html:71
|
||||
#: appsettings/views.py:48 instances/templates/instance.html:71
|
||||
#: instances/templates/instances/destroy_instance_form.html:33
|
||||
#: instances/templates/instances/resize_tab.html:21
|
||||
#: instances/templates/instances/settings_tab.html:197
|
||||
msgid "Disks"
|
||||
msgstr "磁盘"
|
||||
|
||||
#: appsettings/views.py:46
|
||||
#: appsettings/views.py:52
|
||||
msgid "Clones"
|
||||
msgstr "克隆"
|
||||
|
||||
#: appsettings/views.py:47 console/templates/console-base.html:10
|
||||
#: appsettings/views.py:53 console/templates/console-base.html:10
|
||||
#: console/templates/console-base.html:23
|
||||
#: instances/templates/instance_actions.html:11
|
||||
#: instances/templates/instances/settings_tab.html:32
|
||||
msgid "Console"
|
||||
msgstr "控制台"
|
||||
|
||||
#: appsettings/views.py:48
|
||||
#: appsettings/views.py:54
|
||||
msgid "VM access and owners"
|
||||
msgstr "虚拟机访问与所有者"
|
||||
|
||||
#: appsettings/views.py:50
|
||||
#: appsettings/views.py:56
|
||||
msgid "Snapshots and jobs"
|
||||
msgstr "快照与任务"
|
||||
|
||||
#: appsettings/views.py:52
|
||||
#: appsettings/views.py:58
|
||||
msgid "Login"
|
||||
msgstr "登录"
|
||||
|
||||
#: appsettings/views.py:53
|
||||
#: appsettings/views.py:59
|
||||
msgid "Alerts"
|
||||
msgstr "告警"
|
||||
|
||||
#: appsettings/views.py:60
|
||||
msgid "Lists and pages"
|
||||
msgstr "列表与页面"
|
||||
|
||||
#: appsettings/views.py:61
|
||||
#: appsettings/views.py:68
|
||||
#, python-format
|
||||
msgid "%(setting)s takes at most %(length)s characters"
|
||||
msgstr "%(setting)s 最多 %(length)s 个字符"
|
||||
|
||||
#: appsettings/views.py:66
|
||||
#: appsettings/views.py:73
|
||||
#, python-format
|
||||
msgid "%(setting)s must be a whole number between %(low)s and %(high)s"
|
||||
msgstr "%(setting)s 必须是 %(low)s 到 %(high)s 之间的整数"
|
||||
|
||||
#: appsettings/views.py:69
|
||||
#: appsettings/views.py:76
|
||||
#, python-format
|
||||
msgid "%(setting)s must be one of %(choices)s"
|
||||
msgstr "%(setting)s 必须是以下之一:%(choices)s"
|
||||
|
||||
#: appsettings/views.py:73
|
||||
#: appsettings/views.py:80
|
||||
#, python-format
|
||||
msgid "%(setting)s takes letters, digits and '-' only"
|
||||
msgstr "%(setting)s 只能包含字母、数字和 '-'"
|
||||
|
||||
#: appsettings/views.py:82
|
||||
#: appsettings/views.py:90
|
||||
#, python-format
|
||||
msgid "%(setting)s: %(value)s is not an e-mail address or an http(s) URL"
|
||||
msgstr "%(setting)s:%(value)s 不是电子邮件地址或 http(s) URL"
|
||||
|
||||
#: appsettings/views.py:99
|
||||
msgid "Disk I/O native needs disk cache none or directsync"
|
||||
msgstr "磁盘 I/O native 需要磁盘缓存为 none 或 directsync"
|
||||
|
||||
#: appsettings/views.py:99
|
||||
#: appsettings/views.py:116
|
||||
#, python-format
|
||||
msgid "Unknown theme: %(theme)s"
|
||||
msgstr "未知主题:%(theme)s"
|
||||
|
||||
#: appsettings/views.py:105
|
||||
#: appsettings/views.py:122
|
||||
#, python-format
|
||||
msgid "Theme is changed. Now: %(theme)s"
|
||||
msgstr "主题已更改。当前:%(theme)s"
|
||||
|
||||
#: appsettings/views.py:140
|
||||
#: appsettings/views.py:159
|
||||
#, python-format
|
||||
msgid "Saved: %(settings)s"
|
||||
msgstr "已保存:%(settings)s"
|
||||
|
||||
#: appsettings/views.py:142
|
||||
#: appsettings/views.py:161
|
||||
msgid "Nothing changed"
|
||||
msgstr "没有任何更改"
|
||||
|
||||
#: appsettings/views.py:149 vrtManager/nodedevs.py:294
|
||||
#: appsettings/views.py:168 vrtManager/nodedevs.py:294
|
||||
#: vrtManager/nodedevs.py:333
|
||||
msgid "Other"
|
||||
msgstr "其他"
|
||||
|
|
@ -8196,15 +8224,46 @@ msgstr "此任务开始后无法取消"
|
|||
msgid "The job has already ended"
|
||||
msgstr "任务已经结束"
|
||||
|
||||
#: operations/jobs.py:275
|
||||
#: operations/jobs.py:278
|
||||
#, python-format
|
||||
msgid "%(kind)s: %(resource)s"
|
||||
msgstr "%(kind)s:%(resource)s"
|
||||
|
||||
#: operations/jobs.py:283
|
||||
msgid "No reason was given"
|
||||
msgstr "未给出原因"
|
||||
|
||||
#: operations/jobs.py:285
|
||||
#, python-format
|
||||
msgid "Job ended uncertain: %(job)s"
|
||||
msgstr "作业以不确定状态结束:%(job)s"
|
||||
|
||||
#: operations/jobs.py:286
|
||||
#, python-format
|
||||
msgid ""
|
||||
"Job #%(id)s (%(job)s) ended uncertain; it keeps what it holds until a "
|
||||
"superuser resolves it on its page. %(error)s"
|
||||
msgstr "作业 #%(id)s(%(job)s)以不确定状态结束;在超级用户于其页面上处理之前,它会保留所占用的资源。%(error)s"
|
||||
|
||||
#: operations/jobs.py:289
|
||||
#, python-format
|
||||
msgid "Job failed: %(job)s"
|
||||
msgstr "作业失败:%(job)s"
|
||||
|
||||
#: operations/jobs.py:290
|
||||
#, python-format
|
||||
msgid "Job #%(id)s (%(job)s) failed: %(error)s"
|
||||
msgstr "作业 #%(id)s(%(job)s)失败:%(error)s"
|
||||
|
||||
#: operations/jobs.py:297
|
||||
msgid "Choose succeeded or failed"
|
||||
msgstr "请选择成功或失败"
|
||||
|
||||
#: operations/jobs.py:278
|
||||
#: operations/jobs.py:300
|
||||
msgid "Write a note on what was checked"
|
||||
msgstr "请写下检查了哪些内容"
|
||||
|
||||
#: operations/jobs.py:282
|
||||
#: operations/jobs.py:304
|
||||
msgid "Only an uncertain job can be resolved"
|
||||
msgstr "只能处理状态不确定的任务"
|
||||
|
||||
|
|
@ -9788,7 +9847,12 @@ msgstr "由于备份的某个文件缺失、已更改或无法读取,未读取
|
|||
msgid "Check backup target"
|
||||
msgstr "检查备份目标"
|
||||
|
||||
#: vmbackups/jobs.py:1600
|
||||
#: vmbackups/jobs.py:1603
|
||||
#, python-format
|
||||
msgid "Backups missing from %(target)s"
|
||||
msgstr "%(target)s 中缺少备份"
|
||||
|
||||
#: vmbackups/jobs.py:1604 vmbackups/jobs.py:1606
|
||||
#, python-format
|
||||
msgid "Files of these backups are missing from the target: %(backups)s"
|
||||
msgstr "以下备份的文件在目标中缺失:%(backups)s"
|
||||
|
|
@ -9805,6 +9869,16 @@ msgstr "主机处于维护中"
|
|||
msgid "The schedule's owner is no longer an active superuser"
|
||||
msgstr "该计划的所有者已不再是活动的超级用户"
|
||||
|
||||
#: vmbackups/schedule.py:92
|
||||
#, python-format
|
||||
msgid "Scheduled backup not taken: %(vm)s"
|
||||
msgstr "未执行计划备份:%(vm)s"
|
||||
|
||||
#: vmbackups/schedule.py:93
|
||||
#, python-format
|
||||
msgid "The schedule %(schedule)s did not back up %(vm)s on %(day)s: %(reason)s"
|
||||
msgstr "计划 %(schedule)s 未在 %(day)s 备份 %(vm)s:%(reason)s"
|
||||
|
||||
#: vmbackups/templates/vmbackups/consistency.html:1
|
||||
msgid "While shut off"
|
||||
msgstr "关机时"
|
||||
|
|
|
|||
102
operations/alerts.py
Normal file
102
operations/alerts.py
Normal file
|
|
@ -0,0 +1,102 @@
|
|||
"""Notices for the operator: a backup that failed, was not taken, is missing or damaged, and a job that ended
|
||||
uncertain. alert() queues one in the caller's transaction, so a failed send never holds up the change it tells
|
||||
of; send(), a periodic task of the worker, mails it to the Settings page's alert addresses and POSTs it as JSON
|
||||
to its alert webhook, trying again at the next passes."""
|
||||
|
||||
import json
|
||||
import logging
|
||||
import urllib.request
|
||||
from datetime import timedelta
|
||||
|
||||
from django.conf import settings
|
||||
from django.core.mail import send_mail
|
||||
from django.db import transaction
|
||||
from django.utils import timezone, translation
|
||||
|
||||
from appsettings.models import AppSettings
|
||||
|
||||
from .models import Alert
|
||||
from .utils import safe_text, words
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
TRIES = 10 # passes, about a minute apart, before a notice is given up
|
||||
ROWS = 20 # notices a pass
|
||||
KEPT = timedelta(days=30)
|
||||
|
||||
|
||||
def channels():
|
||||
"""(the alert addresses, the webhook URL) of the Settings page."""
|
||||
values = dict(AppSettings.objects.filter(key__in=("ALERT_EMAILS", "ALERT_WEBHOOK")).values_list("key", "value"))
|
||||
return [a.strip() for a in values.get("ALERT_EMAILS", "").split(",") if a.strip()], values.get("ALERT_WEBHOOK", "").strip()
|
||||
|
||||
|
||||
def alert(subject, text):
|
||||
"""Queue a notice (subject, text: messages, operations.utils.say); none while no channel is set. It never
|
||||
stops the change it tells of: a failure is logged, in a savepoint of the caller's transaction."""
|
||||
try:
|
||||
with transaction.atomic():
|
||||
if any(channels()):
|
||||
Alert.objects.create(subject=subject, text=text)
|
||||
except Exception:
|
||||
logger.exception("queueing an alert failed")
|
||||
|
||||
|
||||
def send():
|
||||
"""The notices not sent yet, oldest first, ROWS a pass. A channel that fails is not tried again in the
|
||||
pass, so a server that does not answer holds the worker's periodic pass (and the backup schedules) for
|
||||
one timeout at most. Each try is claimed first: a worker that took over meanwhile does not send it
|
||||
again. Without a channel set the notices wait (or expire)."""
|
||||
emails, url = channels()
|
||||
Alert.objects.filter(created_at__lt=timezone.now() - KEPT).delete()
|
||||
if not (emails or url):
|
||||
return
|
||||
down = set()
|
||||
with translation.override(settings.LANGUAGE_CODE):
|
||||
# the least tried first: notices a channel keeps refusing do not hold the new ones back
|
||||
for notice in Alert.objects.filter(sent_at__isnull=True, tries__lt=TRIES).order_by("tries", "pk")[:ROWS]:
|
||||
wanted = {"mail"} if emails and not notice.mailed else set()
|
||||
wanted |= {"webhook"} if url and not notice.posted else set()
|
||||
if wanted <= down:
|
||||
continue # its channels failed in this pass: not a try of its own
|
||||
if not Alert.objects.filter(pk=notice.pk, tries=notice.tries).update(tries=notice.tries + 1):
|
||||
continue
|
||||
subject, text, errors = words(notice.subject), words(notice.text), []
|
||||
if emails and not notice.mailed:
|
||||
errors += _try("mail", down, notice, lambda: send_mail(f"WebVirtCloud: {subject}", text, None, emails))
|
||||
if url and not notice.posted:
|
||||
body = json.dumps({"subject": subject, "text": f"{subject}\n{text}",
|
||||
"time": notice.created_at.isoformat()}).encode()
|
||||
errors += _try("webhook", down, notice, lambda: _post(url, body))
|
||||
done = (not emails or notice.mailed) and (not url or notice.posted)
|
||||
Alert.objects.filter(pk=notice.pk).update(error="; ".join(errors))
|
||||
if done: # never undone: a worker that took over may have sent it meanwhile
|
||||
Alert.objects.filter(pk=notice.pk).update(sent_at=timezone.now())
|
||||
if not done and notice.tries + 1 >= TRIES:
|
||||
logger.error("alert %s given up: %s", notice.pk, "; ".join(errors))
|
||||
|
||||
|
||||
def _try(channel, down, notice, deliver):
|
||||
"""Deliver notice by channel (mail, webhook) and record it: [] when done, [the error] otherwise."""
|
||||
if channel in down:
|
||||
return [f"{channel}: failed earlier in this pass"]
|
||||
try:
|
||||
deliver()
|
||||
except Exception as err:
|
||||
down.add(channel)
|
||||
return [f"{channel}: {safe_text(err)}"]
|
||||
field = "mailed" if channel == "mail" else "posted"
|
||||
setattr(notice, field, True)
|
||||
Alert.objects.filter(pk=notice.pk).update(**{field: True})
|
||||
return []
|
||||
|
||||
|
||||
class _NoRedirect(urllib.request.HTTPRedirectHandler):
|
||||
def redirect_request(self, *args, **kwargs):
|
||||
return None # urllib would follow with a GET without the body: a redirect is an error
|
||||
|
||||
|
||||
def _post(url, body):
|
||||
request = urllib.request.Request(url, body, {"Content-Type": "application/json"})
|
||||
with urllib.request.build_opener(_NoRedirect).open(request, timeout=10):
|
||||
pass
|
||||
|
|
@ -19,7 +19,7 @@ from logs.audit import write
|
|||
from vrtManager.util import OperationError
|
||||
from webvirtcloud.log_context import request_ip
|
||||
|
||||
from . import claims, utils
|
||||
from . import alerts, claims, utils
|
||||
from .models import Claim, LeaseLost, Operation, fenced
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
|
@ -263,11 +263,33 @@ def finish(op, outcome, *, worker=None):
|
|||
if (entry := _entry(op, outcome.state)) is not None:
|
||||
_log(op.username, *entry, {Operation.SUCCEEDED: True, Operation.FAILED: False}.get(outcome.state),
|
||||
op.client_ip)
|
||||
_alert(op, outcome)
|
||||
logger.info("job %s %s: %s", op.pk, op.kind, outcome.state)
|
||||
op.refresh_from_db()
|
||||
return True
|
||||
|
||||
|
||||
# kinds whose failure the operator is told of (operations.alerts); every kind's uncertain end too
|
||||
ALERTED_FAILURES = ("backup.create", "backup.verify")
|
||||
|
||||
|
||||
def _alert(op, outcome):
|
||||
# the kind's label a message: translated when the notice is sent
|
||||
job = utils.say(gettext_noop("%(kind)s: %(resource)s"), kind=utils.say(label_of(op.kind)), resource=op.resource_label) \
|
||||
if op.resource_label else utils.say(label_of(op.kind))
|
||||
# stored messages, each kept, or text as it is
|
||||
error = [m if isinstance(m, dict) and "text" in m else utils.say(utils.safe_text(m))[0]
|
||||
for m in (outcome.error if isinstance(outcome.error, list) else [outcome.error] if outcome.error else [])] \
|
||||
or utils.say(gettext_noop("No reason was given"))
|
||||
if outcome.state == Operation.UNCERTAIN:
|
||||
alerts.alert(utils.say(gettext_noop("Job ended uncertain: %(job)s"), job=job),
|
||||
utils.say(gettext_noop("Job #%(id)s (%(job)s) ended uncertain; it keeps what it holds until a "
|
||||
"superuser resolves it on its page. %(error)s"), id=op.pk, job=job, error=error))
|
||||
elif outcome.state == Operation.FAILED and op.kind in ALERTED_FAILURES:
|
||||
alerts.alert(utils.say(gettext_noop("Job failed: %(job)s"), job=job),
|
||||
utils.say(gettext_noop("Job #%(id)s (%(job)s) failed: %(error)s"), id=op.pk, job=job, error=error))
|
||||
|
||||
|
||||
def resolve(op_id, user, outcome_state, note):
|
||||
if not user.is_superuser:
|
||||
raise PermissionDenied
|
||||
|
|
@ -306,3 +328,6 @@ def take_remembered(request, resource):
|
|||
if taken: # untouched otherwise: no session write on every page view
|
||||
request.session["operations_shown"] = [e for e in entries if e["resource"] != resource]
|
||||
return taken
|
||||
|
||||
|
||||
register_periodic(alerts.send)
|
||||
|
|
|
|||
27
operations/migrations/0005_alert.py
Normal file
27
operations/migrations/0005_alert.py
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
# Generated by Django 5.2.18 on 2026-11-19 12:27
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('operations', '0004_parent'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name='Alert',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('created_at', models.DateTimeField(auto_now_add=True)),
|
||||
('subject', models.JSONField()),
|
||||
('text', models.JSONField()),
|
||||
('mailed', models.BooleanField(default=False)),
|
||||
('posted', models.BooleanField(default=False)),
|
||||
('sent_at', models.DateTimeField(null=True)),
|
||||
('tries', models.PositiveSmallIntegerField(default=0)),
|
||||
('error', models.TextField(blank=True)),
|
||||
],
|
||||
),
|
||||
]
|
||||
|
|
@ -138,3 +138,17 @@ def fenced(holder):
|
|||
if not WorkerLease.objects.select_for_update().filter(name="worker", holder=holder).exists():
|
||||
raise LeaseLost(holder)
|
||||
yield
|
||||
|
||||
|
||||
class Alert(models.Model):
|
||||
"""A notice for the operator (operations.alerts), sent by the worker's periodic pass: by mail to the alert
|
||||
addresses and as a POST to the alert webhook of the Settings page."""
|
||||
|
||||
created_at = models.DateTimeField(auto_now_add=True)
|
||||
subject = models.JSONField() # messages (operations.utils.say)
|
||||
text = models.JSONField()
|
||||
mailed = models.BooleanField(default=False)
|
||||
posted = models.BooleanField(default=False)
|
||||
sent_at = models.DateTimeField(null=True) # every channel set took it
|
||||
tries = models.PositiveSmallIntegerField(default=0)
|
||||
error = models.TextField(blank=True) # the last try's
|
||||
|
|
|
|||
187
operations/tests/test_alerts.py
Normal file
187
operations/tests/test_alerts.py
Normal file
|
|
@ -0,0 +1,187 @@
|
|||
"""Alerts: a failed backup, a scheduled backup not taken, backups found missing and an uncertain job are
|
||||
queued with the change they tell of and sent by mail and webhook; /healthz tells a monitor whether the
|
||||
worker runs."""
|
||||
|
||||
import json
|
||||
from datetime import timedelta
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from django.contrib.auth import get_user_model
|
||||
from django.core import mail
|
||||
from django.test import TestCase, override_settings
|
||||
from django.urls import reverse
|
||||
from django.utils import timezone
|
||||
|
||||
from appsettings.models import AppSettings
|
||||
from operations import alerts, jobs
|
||||
from operations.models import Alert, Operation, WorkerLease
|
||||
from operations.utils import say
|
||||
|
||||
|
||||
def channels(emails="ops@example.com", webhook=""):
|
||||
AppSettings.objects.filter(key="ALERT_EMAILS").update(value=emails)
|
||||
AppSettings.objects.filter(key="ALERT_WEBHOOK").update(value=webhook)
|
||||
|
||||
|
||||
@override_settings(EMAIL_BACKEND="django.core.mail.backends.locmem.EmailBackend")
|
||||
class AlertTests(TestCase):
|
||||
def setUp(self):
|
||||
self.user = get_user_model().objects.create_superuser("al_admin", "al@example.com", "pw")
|
||||
|
||||
def op(self, kind):
|
||||
return Operation.objects.create(kind=kind, user=self.user, username="al_admin", state=Operation.RUNNING,
|
||||
submission_key=f"key-{Operation.objects.count():012d}",
|
||||
resource="backup:x", resource_label="vm1 2026-11-19 03:00", params={}, intent={})
|
||||
|
||||
def test_none_queued_while_no_channel_is_set(self):
|
||||
channels("", "")
|
||||
alerts.alert(say("Subject"), say("Text"))
|
||||
self.assertFalse(Alert.objects.exists())
|
||||
|
||||
def test_a_failed_backup_and_an_uncertain_job_are_alerts_a_failed_other_job_is_not(self):
|
||||
channels()
|
||||
jobs.finish(self.op("backup.create"), jobs.Outcome(Operation.FAILED, error=say("Disk full")))
|
||||
jobs.finish(self.op("instance.migrate"), jobs.Outcome(Operation.FAILED, error=say("Refused")))
|
||||
jobs.finish(self.op("instance.clone"), jobs.Outcome(Operation.UNCERTAIN, error=say("Host gone")))
|
||||
jobs.finish(self.op("backup.create"), jobs.Outcome(Operation.SUCCEEDED))
|
||||
alerts.send()
|
||||
subjects = [m.subject for m in mail.outbox]
|
||||
self.assertEqual(subjects, ["WebVirtCloud: Job failed: Back up VM: vm1 2026-11-19 03:00",
|
||||
"WebVirtCloud: Job ended uncertain: Clone VM: vm1 2026-11-19 03:00"])
|
||||
Alert.objects.all().delete()
|
||||
mail.outbox.clear()
|
||||
with override_settings(LANGUAGE_CODE="tr"): # in the panel's language, the kind's label too
|
||||
jobs.finish(self.op("backup.create"), jobs.Outcome(Operation.FAILED, error=say("Disk full")))
|
||||
alerts.send()
|
||||
self.assertEqual(mail.outbox[0].subject, "WebVirtCloud: İş başarısız: Sanal makineyi yedekle: vm1 2026-11-19 03:00")
|
||||
self.assertIn("Disk full", mail.outbox[0].body)
|
||||
self.assertEqual(mail.outbox[0].to, ["ops@example.com"])
|
||||
self.assertTrue(all(a.sent_at for a in Alert.objects.all()))
|
||||
|
||||
def test_a_plain_text_error_or_a_failing_queue_never_stops_a_job_ending(self):
|
||||
channels()
|
||||
jobs.finish(self.op("instance.clone"), jobs.Outcome(Operation.UNCERTAIN, error=["plain words"]))
|
||||
op = self.op("backup.create")
|
||||
with patch("operations.alerts.Alert.objects.create", side_effect=RuntimeError("queue broke")):
|
||||
jobs.finish(op, jobs.Outcome(Operation.FAILED, error=say("Disk full")))
|
||||
op.refresh_from_db()
|
||||
self.assertEqual(op.state, Operation.FAILED)
|
||||
alerts.send()
|
||||
self.assertEqual(len(mail.outbox), 1)
|
||||
self.assertIn("plain words", mail.outbox[0].body)
|
||||
|
||||
def test_the_webhook_gets_json_and_a_failing_channel_is_tried_again_alone(self):
|
||||
channels("ops@example.com", "https://hooks.example.com/x")
|
||||
alerts.alert(say("Subject"), say("Text"))
|
||||
with patch("operations.alerts._post", side_effect=OSError("refused")):
|
||||
alerts.send()
|
||||
notice = Alert.objects.get()
|
||||
self.assertEqual((notice.mailed, notice.posted, notice.sent_at, notice.tries), (True, False, None, 1))
|
||||
self.assertIn("webhook: refused", notice.error)
|
||||
with patch("operations.alerts._post", MagicMock()) as urlopen:
|
||||
alerts.send()
|
||||
self.assertEqual(len(mail.outbox), 1) # not mailed twice
|
||||
url, body = urlopen.call_args.args
|
||||
self.assertEqual(url, "https://hooks.example.com/x")
|
||||
self.assertEqual(json.loads(body)["subject"], "Subject")
|
||||
self.assertTrue(Alert.objects.get().sent_at)
|
||||
|
||||
def test_a_channel_down_is_tried_once_a_pass_and_notices_wait_without_channels(self):
|
||||
channels("", "https://hooks.example.com/x")
|
||||
for _ in range(3):
|
||||
alerts.alert(say("Subject"), say("Text"))
|
||||
with patch("operations.alerts._post", side_effect=OSError("timed out")) as urlopen:
|
||||
alerts.send()
|
||||
self.assertEqual(urlopen.call_count, 1) # one timeout a pass, not one a notice
|
||||
self.assertEqual(sorted(Alert.objects.values_list("tries", flat=True)), [0, 0, 1]) # the others not tried
|
||||
alerts.alert(say("Newer"), say("Text"))
|
||||
with patch("operations.alerts._post") as urlopen:
|
||||
alerts.send()
|
||||
self.assertEqual(json.loads(urlopen.call_args_list[0].args[1])["subject"], "Subject") # the least tried first
|
||||
self.assertEqual(Alert.objects.filter(sent_at__isnull=True).count(), 0)
|
||||
Alert.objects.update(sent_at=None, posted=False)
|
||||
channels("", "")
|
||||
alerts.send()
|
||||
self.assertFalse(Alert.objects.filter(sent_at__isnull=False).exists())
|
||||
|
||||
def test_a_try_another_worker_claimed_is_not_sent_again(self):
|
||||
channels()
|
||||
alerts.alert(say("Subject"), say("Text"))
|
||||
real = Alert.objects.filter
|
||||
|
||||
def taken_meanwhile(*args, **kwargs):
|
||||
if "tries" in kwargs: # the claim: another worker's came first
|
||||
Alert.objects.update(tries=1)
|
||||
return real(*args, **kwargs)
|
||||
|
||||
with patch.object(Alert.objects, "filter", side_effect=taken_meanwhile):
|
||||
alerts.send()
|
||||
self.assertEqual(mail.outbox, [])
|
||||
|
||||
def test_a_redirect_is_no_delivery(self):
|
||||
from http.server import BaseHTTPRequestHandler, HTTPServer
|
||||
import threading
|
||||
|
||||
class Redirect(BaseHTTPRequestHandler):
|
||||
def do_POST(self):
|
||||
self.send_response(302)
|
||||
self.send_header("Location", "/elsewhere")
|
||||
self.end_headers()
|
||||
|
||||
def do_GET(self):
|
||||
self.send_response(200)
|
||||
self.end_headers()
|
||||
|
||||
def log_message(self, *args):
|
||||
pass
|
||||
|
||||
server = HTTPServer(("127.0.0.1", 0), Redirect)
|
||||
threading.Thread(target=server.handle_request, daemon=True).start()
|
||||
self.addCleanup(server.server_close)
|
||||
with self.assertRaises(Exception):
|
||||
alerts._post(f"http://127.0.0.1:{server.server_port}/notify", b"{}")
|
||||
|
||||
def test_a_notice_is_given_up_after_its_tries_and_old_ones_go(self):
|
||||
channels("", "https://hooks.example.com/x")
|
||||
alerts.alert(say("Subject"), say("Text"))
|
||||
with patch("operations.alerts._post", side_effect=OSError("refused")) as urlopen:
|
||||
for _ in range(alerts.TRIES + 2):
|
||||
alerts.send()
|
||||
self.assertEqual(urlopen.call_count, alerts.TRIES)
|
||||
Alert.objects.update(created_at=timezone.now() - alerts.KEPT - timedelta(minutes=1))
|
||||
alerts.send()
|
||||
self.assertFalse(Alert.objects.exists())
|
||||
|
||||
def test_the_settings_page_refuses_a_bad_address_or_url(self):
|
||||
self.client.force_login(self.user)
|
||||
for key, value in (("ALERT_EMAILS", "ops@example.com, not-an-address"), ("ALERT_WEBHOOK", "ftp://x.example.com/")):
|
||||
with self.subTest(key=key):
|
||||
setting = AppSettings.objects.get(key=key)
|
||||
self.client.post(reverse("appsettings"), {key: value, f"was-{key}": setting.value})
|
||||
self.assertEqual(AppSettings.objects.get(key=key).value, "")
|
||||
self.client.post(reverse("appsettings"), {"ALERT_WEBHOOK": "https://u:secret@hooks.example.com/x", "was-ALERT_WEBHOOK": ""})
|
||||
self.assertEqual(AppSettings.objects.get(key="ALERT_WEBHOOK").value, "")
|
||||
self.client.post(reverse("appsettings"), {"ALERT_EMAILS": "a@example.com, b@example.com", "was-ALERT_EMAILS": ""})
|
||||
self.assertEqual(AppSettings.objects.get(key="ALERT_EMAILS").value, "a@example.com, b@example.com")
|
||||
url = "https://hooks.slack.example.com/services/T0000000/B0000000/" + "x" * 40
|
||||
self.client.post(reverse("appsettings"), {"ALERT_WEBHOOK": url, "was-ALERT_WEBHOOK": ""})
|
||||
self.assertEqual(AppSettings.objects.get(key="ALERT_WEBHOOK").value, url)
|
||||
from logs.models import Logs
|
||||
self.assertFalse(Logs.objects.filter(message__contains="x" * 40).exists()) # a secret of its own
|
||||
self.assertContains(self.client.get(reverse("appsettings")), 'maxlength="255"')
|
||||
|
||||
|
||||
class HealthzTests(TestCase):
|
||||
def test_without_a_login_it_tells_whether_the_worker_runs(self):
|
||||
response = self.client.get(reverse("healthz"))
|
||||
self.assertEqual((response.status_code, response.json()["worker"]), (503, False))
|
||||
WorkerLease.objects.create(holder="w", host="h", heartbeat_at=timezone.now())
|
||||
response = self.client.get(reverse("healthz"))
|
||||
self.assertEqual((response.status_code, response.json()["worker"], response.json()["database"]), (200, True, True))
|
||||
WorkerLease.objects.update(heartbeat_at=timezone.now() - timedelta(minutes=5))
|
||||
self.assertEqual(self.client.get(reverse("healthz")).status_code, 503)
|
||||
from django.db import InterfaceError
|
||||
with patch("operations.views.last_seen", side_effect=InterfaceError("connection already closed")):
|
||||
response = self.client.get(reverse("healthz"))
|
||||
self.assertEqual((response.status_code, response.json()["database"]), (503, False))
|
||||
self.assertIn("no-store", response["Cache-Control"])
|
||||
|
|
@ -1,11 +1,14 @@
|
|||
from urllib.parse import urlencode
|
||||
|
||||
from django.contrib import messages
|
||||
from django.contrib.auth.decorators import login_not_required
|
||||
from django.core.exceptions import PermissionDenied
|
||||
from django.core.paginator import Paginator
|
||||
from django.http import Http404
|
||||
from django.db import Error as DatabaseError
|
||||
from django.http import Http404, JsonResponse
|
||||
from django.shortcuts import redirect, render
|
||||
from django.utils.translation import gettext as _
|
||||
from django.views.decorators.cache import never_cache
|
||||
from django.views.decorators.http import require_POST
|
||||
from vrtManager.util import OperationError
|
||||
|
||||
|
|
@ -84,3 +87,16 @@ def resolve(request, pk):
|
|||
except OperationError as err:
|
||||
messages.error(request, words(said(err)))
|
||||
return redirect("operations:job", pk=op.pk)
|
||||
|
||||
|
||||
@login_not_required
|
||||
@never_cache
|
||||
def healthz(request):
|
||||
"""For a monitor, without a login: 200 while the database answers and the job worker runs, 503 otherwise."""
|
||||
try:
|
||||
seen = last_seen()
|
||||
except DatabaseError:
|
||||
return JsonResponse({"database": False, "worker": False}, status=503)
|
||||
running = not worker_gone(seen)
|
||||
return JsonResponse({"database": True, "worker": running, "worker_seen": seen and seen.isoformat()},
|
||||
status=200 if running else 503)
|
||||
|
|
|
|||
|
|
@ -27,7 +27,7 @@ from computes.models import Compute
|
|||
from instances.jobs import MOVED, PAUSED_FROZEN, THAW_FAILED, _instance, _log, _snapshot_free_space, record_vm, vm_claims
|
||||
from instances.utils import QUOTA_UNVERIFIED, paths_used_on_other_computes, QUOTA_UNVERIFIED_TEXT, check_user_quota, get_random_mac_address, quota_message
|
||||
from instances.models import Instance
|
||||
from operations import claims
|
||||
from operations import alerts, claims
|
||||
from operations.jobs import Cancelled, Kind, Outcome, Plan, register, register_periodic
|
||||
from operations.models import Claim, Operation
|
||||
from operations.utils import safe_text, say
|
||||
|
|
@ -1581,21 +1581,27 @@ class CheckTarget(Kind):
|
|||
pool.refresh(0)
|
||||
present = set(pool.listVolumes())
|
||||
settled = timezone.now() - CHECK_SETTLE
|
||||
missing = []
|
||||
for backup in target.backups.filter(state__in=(Backup.READY, Backup.MISSING)).prefetch_related("files"):
|
||||
needed = {f.volume for f in backup.files.all()} | {f"{backup.prefix}-manifest.json"}
|
||||
try:
|
||||
needed |= {f["volume"] for f in _base_files(backup)} # a restore copies the chain flat
|
||||
state = Backup.READY if needed <= present else Backup.MISSING
|
||||
except util.OperationError: # its base's row is gone
|
||||
state = Backup.MISSING
|
||||
if state == Backup.MISSING and backup.state == Backup.READY and (backup.finished_at or settled) > settled:
|
||||
continue # just written through another compute: this one may not list its files yet (NFS)
|
||||
if state == Backup.MISSING:
|
||||
missing.append(f"{backup.vm_name} {timezone.localtime(backup.created_at):%Y-%m-%d %H:%M}")
|
||||
# only from the state read: a deletion begun meanwhile is left alone
|
||||
Backup.objects.filter(pk=backup.pk, state=backup.state).update(state=state)
|
||||
BackupTarget.objects.filter(pk=target.pk).update(checked_at=timezone.now())
|
||||
missing, lost = [], [] # lost: found missing at this check
|
||||
# the states and their alert together: a worker stopped between them loses no alert
|
||||
with transaction.atomic():
|
||||
for backup in target.backups.filter(state__in=(Backup.READY, Backup.MISSING)).prefetch_related("files"):
|
||||
needed = {f.volume for f in backup.files.all()} | {f"{backup.prefix}-manifest.json"}
|
||||
try:
|
||||
needed |= {f["volume"] for f in _base_files(backup)} # a restore copies the chain flat
|
||||
state = Backup.READY if needed <= present else Backup.MISSING
|
||||
except util.OperationError: # its base's row is gone
|
||||
state = Backup.MISSING
|
||||
if state == Backup.MISSING and backup.state == Backup.READY and (backup.finished_at or settled) > settled:
|
||||
continue # just written through another compute: this one may not list its files yet (NFS)
|
||||
if state == Backup.MISSING:
|
||||
missing.append(f"{backup.vm_name} {timezone.localtime(backup.created_at):%Y-%m-%d %H:%M}")
|
||||
# only from the state read: a deletion begun meanwhile is left alone
|
||||
if Backup.objects.filter(pk=backup.pk, state=backup.state).update(state=state) and backup.state != state == Backup.MISSING:
|
||||
lost.append(missing[-1])
|
||||
BackupTarget.objects.filter(pk=target.pk).update(checked_at=timezone.now())
|
||||
if lost:
|
||||
alerts.alert(say(_("Backups missing from %(target)s"), target=target.name),
|
||||
say(_("Files of these backups are missing from the target: %(backups)s"), backups=", ".join(lost)))
|
||||
if missing:
|
||||
return {"warning": say(_("Files of these backups are missing from the target: %(backups)s"),
|
||||
backups=", ".join(missing))}
|
||||
|
|
|
|||
|
|
@ -8,7 +8,7 @@ import logging
|
|||
from concurrent.futures import ThreadPoolExecutor
|
||||
|
||||
from django.contrib.auth import get_user_model
|
||||
from django.db import close_old_connections
|
||||
from django.db import close_old_connections, transaction
|
||||
from django.core.exceptions import PermissionDenied
|
||||
from django.utils import timezone
|
||||
from django.utils.translation import gettext_noop as _
|
||||
|
|
@ -16,7 +16,7 @@ from libvirt import libvirtError
|
|||
|
||||
from computes.models import Compute
|
||||
from computes.utils import refresh_instance_database
|
||||
from operations import claims, jobs
|
||||
from operations import alerts, claims, jobs
|
||||
from operations.models import Operation
|
||||
from operations.utils import safe_text, said, say
|
||||
from vrtManager.util import ConnectionFailed
|
||||
|
|
@ -57,7 +57,8 @@ def run_schedules(now=None):
|
|||
continue
|
||||
in_maintenance = Compute.objects.filter(pk=vm.compute_id, maintenance_since__isnull=False).exists()
|
||||
if not open_:
|
||||
_record(policy, vm, day, BackupRun.SKIPPED, say(IN_MAINTENANCE if in_maintenance else NOT_STARTED))
|
||||
_record(policy, vm, day, BackupRun.SKIPPED, say(IN_MAINTENANCE if in_maintenance else NOT_STARTED),
|
||||
quiet=in_maintenance) # the operator put the host in maintenance
|
||||
elif not in_maintenance: # deferred while the window lasts
|
||||
due.setdefault(vm.compute_id, []).append((policy.pk, vm.pk, day, start))
|
||||
for compute_id in due.keys() | read.keys():
|
||||
|
|
@ -82,9 +83,15 @@ def occurrences(policy, now):
|
|||
yield day, start
|
||||
|
||||
|
||||
def _record(policy, vm, day, state, note=(), operation=None):
|
||||
BackupRun.objects.get_or_create(policy=policy, instance=vm, day=day,
|
||||
defaults={"state": state, "note": list(note), "operation": operation})
|
||||
def _record(policy, vm, day, state, note=(), operation=None, quiet=False):
|
||||
"""The run of the day; one not submitted is an alert unless quiet."""
|
||||
with transaction.atomic(): # the run and its alert together: a worker stopped between them loses neither
|
||||
_run, made = BackupRun.objects.get_or_create(policy=policy, instance=vm, day=day,
|
||||
defaults={"state": state, "note": list(note), "operation": operation})
|
||||
if made and state != BackupRun.SUBMITTED and not quiet:
|
||||
alerts.alert(say(_("Scheduled backup not taken: %(vm)s"), vm=vm.name),
|
||||
say(_("The schedule %(schedule)s did not back up %(vm)s on %(day)s: %(reason)s"),
|
||||
schedule=policy.name, vm=vm.name, day=day.isoformat(), reason=list(note)))
|
||||
|
||||
|
||||
def _active_superuser(user):
|
||||
|
|
|
|||
|
|
@ -19,6 +19,8 @@ from operations.jobs import Context
|
|||
from operations.models import Operation, acquire
|
||||
from operations.utils import words
|
||||
from vmbackups import schedule
|
||||
from appsettings.models import AppSettings
|
||||
from operations.models import Alert
|
||||
from vmbackups.jobs import CheckTarget, DeleteBackup, _beyond_keep
|
||||
from vmbackups.models import Backup, BackupFile, BackupPolicy, BackupRun, BackupTarget, BackupTargetPool
|
||||
from vrtManager.util import OperationError
|
||||
|
|
@ -212,11 +214,24 @@ class ScheduleTests(TransactionTestCase):
|
|||
self.assertEqual(self.creates(), [])
|
||||
|
||||
def test_a_run_not_started_in_its_window_is_skipped(self):
|
||||
AppSettings.objects.update_or_create(key="ALERT_EMAILS", defaults={"value": "ops@example.com"})
|
||||
self.pass_at(at(2026, 11, 17, 8, 1)) # the worker was down from before 02:00
|
||||
run = BackupRun.objects.get()
|
||||
self.assertEqual(run.state, BackupRun.SKIPPED)
|
||||
self.assertIn("6 hours", words(run.note))
|
||||
self.assertEqual(self.creates(), [])
|
||||
(notice,) = Alert.objects.all() # once, with the reason
|
||||
self.assertEqual(words(notice.subject), "Scheduled backup not taken: vm1")
|
||||
self.assertIn("6 hours", words(notice.text))
|
||||
self.pass_at(at(2026, 11, 17, 8, 2))
|
||||
self.assertEqual(Alert.objects.count(), 1)
|
||||
|
||||
def test_a_skip_for_a_host_in_maintenance_is_no_alert(self):
|
||||
AppSettings.objects.update_or_create(key="ALERT_EMAILS", defaults={"value": "ops@example.com"})
|
||||
Compute.objects.filter(pk=self.c1.pk).update(maintenance_since=at(2026, 11, 16))
|
||||
self.pass_at(at(2026, 11, 17, 8, 1))
|
||||
self.assertEqual(BackupRun.objects.get().state, BackupRun.SKIPPED)
|
||||
self.assertFalse(Alert.objects.exists())
|
||||
|
||||
def test_a_new_schedule_does_not_skip_the_times_before_it(self):
|
||||
BackupPolicy.objects.filter(pk=self.policy.pk).update(created_at=at(2026, 11, 17, 10))
|
||||
|
|
@ -576,8 +591,13 @@ class ScheduleTests(TransactionTestCase):
|
|||
Backup.objects.filter(pk=top.pk).update(parent=base)
|
||||
for b in (base, top):
|
||||
BackupFile.objects.create(backup=b, role=BackupFile.DISK, dev="vda", volume=f"{b.prefix}-vda.qcow2")
|
||||
AppSettings.objects.update_or_create(key="ALERT_EMAILS", defaults={"value": "ops@example.com"})
|
||||
self.run_check([f"{base.prefix}-manifest.json", f"{top.prefix}-vda.qcow2", f"{top.prefix}-manifest.json"])
|
||||
self.assertEqual(Backup.objects.get(pk=top.pk).state, Backup.MISSING)
|
||||
(notice,) = Alert.objects.all() # found missing now: told once
|
||||
self.assertEqual(words(notice.subject), "Backups missing from nfs1")
|
||||
self.run_check([f"{base.prefix}-manifest.json", f"{top.prefix}-vda.qcow2", f"{top.prefix}-manifest.json"])
|
||||
self.assertEqual(Alert.objects.count(), 1)
|
||||
|
||||
def test_a_check_that_reaches_no_pool_marks_nothing(self):
|
||||
(backup,) = self.backups(Backup.READY)
|
||||
|
|
|
|||
|
|
@ -30,6 +30,7 @@ from instances.models import Instance
|
|||
|
||||
# URL name -> why any authenticated user may reach it.
|
||||
ALLOWED_FOR_ANY_USER = {
|
||||
"healthz": "a monitor's check: tells only whether the database and the job worker run",
|
||||
"index": "landing page",
|
||||
"instances:index": "lists only the user's own instances",
|
||||
"instances:find_address": "searches only the user's own instances",
|
||||
|
|
@ -64,6 +65,7 @@ ALLOWED_FOR_ANY_USER = {
|
|||
# URL name -> why an anonymous visitor may reach it. Everything else must
|
||||
# redirect to the login page.
|
||||
ALLOWED_FOR_ANONYMOUS = {
|
||||
"healthz": "a monitor's check: tells only whether the database and the job worker run",
|
||||
"accounts:login": "login page",
|
||||
"accounts:email_otp": "part of the login flow (its own issues are tracked separately)",
|
||||
"accounts:otp_qr": "the OTP QR code a mailed link opens: only with that signed, hour-old-at-most link",
|
||||
|
|
|
|||
|
|
@ -12,6 +12,7 @@ from rest_framework.exceptions import NotFound
|
|||
from appsettings.views import appsettings
|
||||
from console.views import console
|
||||
from instances.views import index
|
||||
from operations import views as operations_views
|
||||
|
||||
|
||||
@extend_schema(exclude=True)
|
||||
|
|
@ -35,6 +36,7 @@ urlpatterns = [
|
|||
path("i18n/", include("django.conf.urls.i18n")),
|
||||
path("logs/", include("logs.urls")),
|
||||
path("jobs/", include("operations.urls")),
|
||||
path("healthz", operations_views.healthz, name="healthz"),
|
||||
path("backups/", include("vmbackups.urls")),
|
||||
path('api/v1/', include("webvirtcloud.urls-api")),
|
||||
path("api/schema/", SpectacularAPIView.as_view(), name="schema"),
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue