diff --git a/locale/tr/LC_MESSAGES/django.mo b/locale/tr/LC_MESSAGES/django.mo index 9d1397b6..0bc9c6c3 100644 Binary files a/locale/tr/LC_MESSAGES/django.mo and b/locale/tr/LC_MESSAGES/django.mo differ diff --git a/locale/tr/LC_MESSAGES/django.po b/locale/tr/LC_MESSAGES/django.po index c106ba7d..b175442b 100644 --- a/locale/tr/LC_MESSAGES/django.po +++ b/locale/tr/LC_MESSAGES/django.po @@ -11,7 +11,7 @@ msgid "" msgstr "" "Project-Id-Version: PACKAGE VERSION\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2026-11-17 06:14+0000\n" +"POT-Creation-Date: 2026-11-17 08:38+0000\n" "PO-Revision-Date: 2020-11-04 12:00+0000\n" "Last-Translator: catborise , 2020\n" "Language-Team: Turkish (https://www.transifex.com/catborise/teams/110663/tr/)\n" @@ -3287,17 +3287,17 @@ msgstr "Klonun adını boş adlar listesinden seçin" msgid "%(quota)s: cannot create '%(clone_name)s'." msgstr "%(quota)s: '%(clone_name)s' oluşturulamıyor." -#: instances/jobs.py:206 instances/jobs.py:646 vmbackups/jobs.py:502 +#: instances/jobs.py:206 instances/jobs.py:646 vmbackups/jobs.py:539 #, python-format msgid "Instance '%(clone_name)s' already exists!" msgstr "'%(clone_name)s' sanal makinesi zaten mevcut!" -#: instances/jobs.py:208 vmbackups/jobs.py:504 +#: instances/jobs.py:208 vmbackups/jobs.py:541 #, python-format msgid "Instance name '%(clone_name)s' is longer than 64 characters" msgstr "'%(clone_name)s' sanal makine adı 64 karakterden uzun" -#: instances/jobs.py:211 vmbackups/jobs.py:506 +#: instances/jobs.py:211 vmbackups/jobs.py:543 #, python-format msgid "Instance name '%(clone_name)s' contains invalid characters!" msgstr "Sanal makine adı '%(clone_name)s' geçersiz karakterler içermektedir!" @@ -3454,11 +3454,11 @@ msgid "Clone VM" msgstr "Sanal makineyi klonla" #: instances/jobs.py:656 instances/jobs.py:663 instances/jobs.py:1005 -#: vmbackups/jobs.py:221 vmbackups/jobs.py:606 +#: vmbackups/jobs.py:234 vmbackups/jobs.py:643 msgid "Copying disks" msgstr "Diskler kopyalanıyor" -#: instances/jobs.py:715 vmbackups/jobs.py:297 +#: instances/jobs.py:715 vmbackups/jobs.py:310 msgid "libvirt has no result of the copy" msgstr "libvirt'te kopyanın sonucu yok" @@ -3471,7 +3471,7 @@ msgstr "" "Kopyalama başarısız oldu: %(error)s. Konuğun dosya sistemleri çözülemedi " "(%(thaw)s); şununla çözün: virsh domfsthaw %(vm)s" -#: instances/jobs.py:729 instances/jobs.py:821 vmbackups/jobs.py:303 +#: instances/jobs.py:729 instances/jobs.py:821 vmbackups/jobs.py:316 msgid "The copy failed" msgstr "Kopyalama başarısız oldu" @@ -3493,11 +3493,11 @@ msgstr "" "Klonun bir birimi oluşturuluyordu; şu birimleri kontrol edin, sonra bu işi " "çözün: %(volumes)s" -#: instances/jobs.py:801 vmbackups/jobs.py:340 +#: instances/jobs.py:801 vmbackups/jobs.py:353 msgid "The job stopped before the copy started" msgstr "İş, kopyalama başlamadan durdu" -#: instances/jobs.py:808 vmbackups/jobs.py:388 +#: instances/jobs.py:808 vmbackups/jobs.py:401 msgid "libvirt is still copying the disks" msgstr "libvirt diskleri hâlâ kopyalıyor" @@ -8510,32 +8510,32 @@ msgstr "" msgid "%(phase)s (over its time limit)" msgstr "%(phase)s (süre sınırını aştı)" -#: operations/jobs.py:153 +#: operations/jobs.py:163 msgid "This form was already submitted for another request; reload the page" msgstr "" "Bu form başka bir istek için zaten gönderildi; sayfayı yeniden yükleyin" -#: operations/jobs.py:159 +#: operations/jobs.py:169 msgid "The form has no valid submission key; reload the page" msgstr "Formun geçerli bir gönderim anahtarı yok; sayfayı yeniden yükleyin" -#: operations/jobs.py:205 +#: operations/jobs.py:215 msgid "This job cannot be cancelled once it has started" msgstr "Bu iş başladıktan sonra iptal edilemez" -#: operations/jobs.py:211 +#: operations/jobs.py:221 msgid "The job has already ended" msgstr "İş zaten bitti" -#: operations/jobs.py:265 +#: operations/jobs.py:275 msgid "Choose succeeded or failed" msgstr "Başarılı ya da başarısız seçin" -#: operations/jobs.py:268 +#: operations/jobs.py:278 msgid "Write a note on what was checked" msgstr "Neyin kontrol edildiğine dair bir not yazın" -#: operations/jobs.py:272 +#: operations/jobs.py:282 msgid "Only an uncertain job can be resolved" msgstr "Yalnızca belirsiz bir iş çözülebilir" @@ -8775,7 +8775,7 @@ msgstr "" msgid "%(label)s is %(state)s on this resource (since %(since)s)." msgstr "%(label)s bu kaynakta %(state)s (%(since)s beri)." -#: operations/worker.py:43 +#: operations/worker.py:44 msgid "" "libvirt's merge finished copying but never completed (for example after a " "libvirtd restart); check the VM before resolving" @@ -8784,7 +8784,7 @@ msgstr "" "libvirtd yeniden başlatıldıktan sonra); çözmeden önce sanal makineyi kontrol " "edin" -#: operations/worker.py:45 +#: operations/worker.py:46 msgid "" "The worker that ran this job stopped responding; an administrator must make " "sure it is no longer running, then resolve this job" @@ -8792,11 +8792,11 @@ msgstr "" "Bu işi çalıştıran worker yanıt vermeyi bıraktı; bir yönetici artık " "çalışmadığından emin olmalı, sonra bu işi çözmeli" -#: operations/worker.py:47 +#: operations/worker.py:48 msgid "Waiting for recovery" msgstr "Kurtarma bekleniyor" -#: operations/worker.py:49 +#: operations/worker.py:50 msgid "" "Recovery could not read the job's state for an hour; check the VM, then " "resolve this job" @@ -8804,7 +8804,7 @@ msgstr "" "Kurtarma bir saat boyunca işin durumunu okuyamadı; sanal makineyi kontrol " "edin, sonra bu işi çözün" -#: operations/worker.py:489 +#: operations/worker.py:503 msgid "The worker stopped before the job changed anything" msgstr "Worker, iş herhangi bir şeyi değiştirmeden önce durdu" @@ -9789,16 +9789,26 @@ msgstr "" msgid "Back up VM" msgstr "Sanal makineyi yedekle" -#: vmbackups/jobs.py:237 vmbackups/jobs.py:304 +#: vmbackups/jobs.py:221 +msgid "The schedule's window ended before the backup could start" +msgstr "Yedek başlayamadan zamanlamanın penceresi bitti" + +#: vmbackups/jobs.py:223 +#, python-format +msgid "" +"%(compute)s went into maintenance before the scheduled backup could start" +msgstr "Zamanlanmış yedek başlayamadan %(compute)s bakıma alındı" + +#: vmbackups/jobs.py:250 vmbackups/jobs.py:317 msgid "Writing the backup's files" msgstr "Yedeğin dosyaları yazılıyor" -#: vmbackups/jobs.py:316 +#: vmbackups/jobs.py:329 msgid "The guest's file systems could not be thawed; trying again" msgstr "" "Konuğun dosya sistemlerinin dondurulması kaldırılamadı; yeniden deneniyor" -#: vmbackups/jobs.py:365 +#: vmbackups/jobs.py:378 #, python-format msgid "" "The VM is no longer on the compute the job ran on; check these volumes of the" @@ -9807,7 +9817,7 @@ msgstr "" "Sanal makine artık işin çalıştığı sunucuda değil; yedek hedefindeki şu " "birimleri kontrol edin, sonra bu işi çözün: %(volumes)s" -#: vmbackups/jobs.py:382 +#: vmbackups/jobs.py:395 #, python-format msgid "" "A disk was being copied when the job stopped; check these volumes of the " @@ -9816,7 +9826,7 @@ msgstr "" "İş durduğunda bir disk kopyalanıyordu; yedek hedefindeki şu birimleri kontrol" " edin, sonra bu işi çözün: %(volumes)s" -#: vmbackups/jobs.py:392 +#: vmbackups/jobs.py:405 #, python-format msgid "" "Another backup runs on the VM; check these volumes of the backup target, then" @@ -9825,7 +9835,7 @@ msgstr "" "Sanal makinede başka bir yedekleme çalışıyor; yedek hedefindeki şu birimleri " "kontrol edin, sonra bu işi çözün: %(volumes)s" -#: vmbackups/jobs.py:398 +#: vmbackups/jobs.py:411 #, python-format msgid "" "libvirt has no result of the copy; check these volumes of the backup target, " @@ -9834,68 +9844,72 @@ msgstr "" "libvirt'te kopyanın sonucu yok; yedek hedefindeki şu birimleri kontrol edin, " "sonra bu işi çözün: %(volumes)s" -#: vmbackups/jobs.py:406 +#: vmbackups/jobs.py:419 msgid "The job stopped before the copy ended" msgstr "İş, kopyalama bitmeden durdu" -#: vmbackups/jobs.py:413 +#: vmbackups/jobs.py:426 #, python-format msgid "The backup's files could not be written: %(error)s" msgstr "Yedeğin dosyaları yazılamadı: %(error)s" -#: vmbackups/jobs.py:433 +#: vmbackups/jobs.py:446 #, python-format msgid "No compute of backup target %(target)s reaches its storage pool" msgstr "" "%(target)s yedek hedefinin hiçbir sunucusu depolama havuzuna erişemiyor" -#: vmbackups/jobs.py:446 +#: vmbackups/jobs.py:480 msgid "Delete backup" msgstr "Yedeği sil" -#: vmbackups/jobs.py:455 +#: vmbackups/jobs.py:491 msgid "This backup is being made; cancel its job to stop it" msgstr "Bu yedek alınıyor; durdurmak için işini iptal edin" -#: vmbackups/jobs.py:519 +#: vmbackups/jobs.py:504 +msgid "The backup is no longer beyond what its schedule keeps; it is kept" +msgstr "Yedek artık zamanlamasının tuttuğu sayının dışında değil; tutuluyor" + +#: vmbackups/jobs.py:556 #, python-format msgid "The backup's file %(name)s is missing from the target" msgstr "Yedeğin %(name)s dosyası hedefte yok" -#: vmbackups/jobs.py:522 vmbackups/jobs.py:524 +#: vmbackups/jobs.py:559 vmbackups/jobs.py:561 #, python-format msgid "The backup's file %(name)s differs from the one written" msgstr "Yedeğin %(name)s dosyası yazılandan farklı" -#: vmbackups/jobs.py:534 vmbackups/templates/vmbackups/restore.html:7 +#: vmbackups/jobs.py:571 vmbackups/templates/vmbackups/restore.html:7 msgid "Restore backup" msgstr "Yedeği geri yükle" -#: vmbackups/jobs.py:547 +#: vmbackups/jobs.py:584 msgid "Only a ready backup is restored" msgstr "Yalnızca hazır bir yedek geri yüklenir" -#: vmbackups/jobs.py:577 +#: vmbackups/jobs.py:614 #, python-format msgid "A VM named %(name)s exists on %(compute)s" msgstr "%(compute)s üzerinde %(name)s adlı bir sanal makine var" -#: vmbackups/jobs.py:585 +#: vmbackups/jobs.py:622 #, python-format msgid "This host has no active directory storage pool %(pool)s" msgstr "Bu sunucuda %(pool)s adlı etkin bir dizin depolama havuzu yok" -#: vmbackups/jobs.py:602 +#: vmbackups/jobs.py:639 #, python-format msgid "The NVRAM file %(path)s exists already" msgstr "%(path)s NVRAM dosyası zaten var" -#: vmbackups/jobs.py:633 +#: vmbackups/jobs.py:670 #, python-format msgid "The VM was restored; it did not start: %(error)s" msgstr "Sanal makine geri yüklendi; başlamadı: %(error)s" -#: vmbackups/jobs.py:655 +#: vmbackups/jobs.py:692 #, python-format msgid "" "A disk was being copied when the job stopped; check this volume, then resolve" @@ -9904,7 +9918,7 @@ msgstr "" "İş durduğunda bir disk kopyalanıyordu; bu birimi kontrol edin, sonra bu işi " "çözün: %(volumes)s" -#: vmbackups/jobs.py:660 +#: vmbackups/jobs.py:697 #, python-format msgid "" "Storage pool %(pool)s is not active; the restore's copies in it are removed " @@ -9913,15 +9927,15 @@ msgstr "" "%(pool)s depolama havuzu etkin değil; geri yüklemenin içindeki kopyaları " "havuz etkin olunca kaldırılır" -#: vmbackups/jobs.py:669 +#: vmbackups/jobs.py:706 msgid "The VM was not defined; its copies were removed" msgstr "Sanal makine tanımlanmadı; kopyaları kaldırıldı" -#: vmbackups/jobs.py:688 vmbackups/templates/vmbackups/target.html:18 +#: vmbackups/jobs.py:725 vmbackups/templates/vmbackups/target.html:18 msgid "Read backups from target" msgstr "Yedekleri hedeften oku" -#: vmbackups/jobs.py:736 +#: vmbackups/jobs.py:773 #, python-format msgid "" "Not read, as a file of the backup is missing, changed or unreadable: " @@ -9930,6 +9944,27 @@ msgstr "" "Yedeğin bir dosyası eksik, değişmiş ya da okunamaz olduğu için okunmadı: " "%(names)s" +#: vmbackups/jobs.py:789 +msgid "Check backup target" +msgstr "Yedek hedefini denetle" + +#: vmbackups/jobs.py:816 +#, python-format +msgid "Files of these backups are missing from the target: %(backups)s" +msgstr "Şu yedeklerin dosyaları hedefte yok: %(backups)s" + +#: vmbackups/schedule.py:28 +msgid "Not started within 6 hours of its time" +msgstr "Zamanından sonraki 6 saat içinde başlatılmadı" + +#: vmbackups/schedule.py:29 +msgid "The host was in maintenance" +msgstr "Sunucu bakımdaydı" + +#: vmbackups/schedule.py:30 +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/templates/vmbackups/consistency.html:1 msgid "Shut off" msgstr "Kapalı" diff --git a/locale/zh/LC_MESSAGES/django.mo b/locale/zh/LC_MESSAGES/django.mo index 859c7bfa..68d96aa1 100644 Binary files a/locale/zh/LC_MESSAGES/django.mo and b/locale/zh/LC_MESSAGES/django.mo differ diff --git a/locale/zh/LC_MESSAGES/django.po b/locale/zh/LC_MESSAGES/django.po index 316318a3..bf688f3c 100644 --- a/locale/zh/LC_MESSAGES/django.po +++ b/locale/zh/LC_MESSAGES/django.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: \n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2026-11-17 06:14+0000\n" +"POT-Creation-Date: 2026-11-17 08:38+0000\n" "PO-Revision-Date: \n" "Last-Translator: \n" "Language-Team: \n" @@ -3132,17 +3132,17 @@ msgstr "请从可用名称列表中选择克隆的名称" msgid "%(quota)s: cannot create '%(clone_name)s'." msgstr "%(quota)s:无法创建“%(clone_name)s”。" -#: instances/jobs.py:206 instances/jobs.py:646 vmbackups/jobs.py:502 +#: instances/jobs.py:206 instances/jobs.py:646 vmbackups/jobs.py:539 #, python-format msgid "Instance '%(clone_name)s' already exists!" msgstr "虚拟机 '%(clone_name)s' 已存在!" -#: instances/jobs.py:208 vmbackups/jobs.py:504 +#: instances/jobs.py:208 vmbackups/jobs.py:541 #, python-format msgid "Instance name '%(clone_name)s' is longer than 64 characters" msgstr "虚拟机名称“%(clone_name)s”超过 64 个字符" -#: instances/jobs.py:211 vmbackups/jobs.py:506 +#: instances/jobs.py:211 vmbackups/jobs.py:543 #, python-format msgid "Instance name '%(clone_name)s' contains invalid characters!" msgstr "虚拟机名称 '%(clone_name)s' 包含无效字符!" @@ -3284,11 +3284,11 @@ msgid "Clone VM" msgstr "克隆虚拟机" #: instances/jobs.py:656 instances/jobs.py:663 instances/jobs.py:1005 -#: vmbackups/jobs.py:221 vmbackups/jobs.py:606 +#: vmbackups/jobs.py:234 vmbackups/jobs.py:643 msgid "Copying disks" msgstr "正在复制磁盘" -#: instances/jobs.py:715 vmbackups/jobs.py:297 +#: instances/jobs.py:715 vmbackups/jobs.py:310 msgid "libvirt has no result of the copy" msgstr "libvirt 没有复制的结果" @@ -3299,7 +3299,7 @@ msgid "" "(%(thaw)s); thaw them with: virsh domfsthaw %(vm)s" msgstr "复制失败:%(error)s。无法解冻客户机的文件系统(%(thaw)s);请用以下命令解冻:virsh domfsthaw %(vm)s" -#: instances/jobs.py:729 instances/jobs.py:821 vmbackups/jobs.py:303 +#: instances/jobs.py:729 instances/jobs.py:821 vmbackups/jobs.py:316 msgid "The copy failed" msgstr "复制失败" @@ -3317,11 +3317,11 @@ msgid "" "this job: %(volumes)s" msgstr "克隆的一个卷正在创建中;请检查这些卷,然后处理此任务:%(volumes)s" -#: instances/jobs.py:801 vmbackups/jobs.py:340 +#: instances/jobs.py:801 vmbackups/jobs.py:353 msgid "The job stopped before the copy started" msgstr "任务在复制开始前停止" -#: instances/jobs.py:808 vmbackups/jobs.py:388 +#: instances/jobs.py:808 vmbackups/jobs.py:401 msgid "libvirt is still copying the disks" msgstr "libvirt 仍在复制磁盘" @@ -8015,31 +8015,31 @@ msgstr "字母、数字、点、短横线和下划线。副本包含该过滤器 msgid "%(phase)s (over its time limit)" msgstr "%(phase)s(已超出时间限制)" -#: operations/jobs.py:153 +#: operations/jobs.py:163 msgid "This form was already submitted for another request; reload the page" msgstr "此表单已为另一个请求提交过;请重新加载页面" -#: operations/jobs.py:159 +#: operations/jobs.py:169 msgid "The form has no valid submission key; reload the page" msgstr "表单没有有效的提交密钥;请重新加载页面" -#: operations/jobs.py:205 +#: operations/jobs.py:215 msgid "This job cannot be cancelled once it has started" msgstr "此任务开始后无法取消" -#: operations/jobs.py:211 +#: operations/jobs.py:221 msgid "The job has already ended" msgstr "任务已经结束" -#: operations/jobs.py:265 +#: operations/jobs.py:275 msgid "Choose succeeded or failed" msgstr "请选择成功或失败" -#: operations/jobs.py:268 +#: operations/jobs.py:278 msgid "Write a note on what was checked" msgstr "请写下检查了哪些内容" -#: operations/jobs.py:272 +#: operations/jobs.py:282 msgid "Only an uncertain job can be resolved" msgstr "只能处理状态不确定的任务" @@ -8269,29 +8269,29 @@ msgstr "此资源上的%(label)s%(state)s(由 %(user)s 于 %(since)s前发起 msgid "%(label)s is %(state)s on this resource (since %(since)s)." msgstr "此资源上的%(label)s%(state)s(自 %(since)s起)。" -#: operations/worker.py:43 +#: operations/worker.py:44 msgid "" "libvirt's merge finished copying but never completed (for example after a " "libvirtd restart); check the VM before resolving" msgstr "libvirt 的合并已完成复制但从未结束(例如 libvirtd 重启后);处理前请检查虚拟机" -#: operations/worker.py:45 +#: operations/worker.py:46 msgid "" "The worker that ran this job stopped responding; an administrator must make " "sure it is no longer running, then resolve this job" msgstr "运行此任务的工作进程已停止响应;管理员必须确认它已不再运行,然后处理此任务" -#: operations/worker.py:47 +#: operations/worker.py:48 msgid "Waiting for recovery" msgstr "等待恢复" -#: operations/worker.py:49 +#: operations/worker.py:50 msgid "" "Recovery could not read the job's state for an hour; check the VM, then " "resolve this job" msgstr "恢复在一小时内无法读取任务状态;请检查虚拟机,然后处理此任务" -#: operations/worker.py:489 +#: operations/worker.py:503 msgid "The worker stopped before the job changed anything" msgstr "工作进程在任务做出任何更改之前停止" @@ -9227,131 +9227,166 @@ msgstr "虚拟机的 NVRAM 文件在备份期间发生了变化;请重新备 msgid "Back up VM" msgstr "备份虚拟机" -#: vmbackups/jobs.py:237 vmbackups/jobs.py:304 +#: vmbackups/jobs.py:221 +msgid "The schedule's window ended before the backup could start" +msgstr "备份开始前计划的时间窗口已结束" + +#: vmbackups/jobs.py:223 +#, python-format +msgid "" +"%(compute)s went into maintenance before the scheduled backup could start" +msgstr "计划的备份开始前 %(compute)s 已进入维护" + +#: vmbackups/jobs.py:250 vmbackups/jobs.py:317 msgid "Writing the backup's files" msgstr "正在写入备份文件" -#: vmbackups/jobs.py:316 +#: vmbackups/jobs.py:329 msgid "The guest's file systems could not be thawed; trying again" msgstr "无法解冻客户机的文件系统;正在重试" -#: vmbackups/jobs.py:365 +#: vmbackups/jobs.py:378 #, python-format msgid "" "The VM is no longer on the compute the job ran on; check these volumes of the" " backup target, then resolve this job: %(volumes)s" msgstr "虚拟机已不在作业运行的计算节点上;请检查备份目标中的这些卷,然后解决此作业:%(volumes)s" -#: vmbackups/jobs.py:382 +#: vmbackups/jobs.py:395 #, python-format msgid "" "A disk was being copied when the job stopped; check these volumes of the " "backup target, then resolve this job: %(volumes)s" msgstr "作业停止时正在复制磁盘;请检查备份目标中的这些卷,然后解决此作业:%(volumes)s" -#: vmbackups/jobs.py:392 +#: vmbackups/jobs.py:405 #, python-format msgid "" "Another backup runs on the VM; check these volumes of the backup target, then" " resolve this job: %(volumes)s" msgstr "虚拟机上正在运行另一个备份;请检查备份目标中的这些卷,然后解决此作业:%(volumes)s" -#: vmbackups/jobs.py:398 +#: vmbackups/jobs.py:411 #, python-format msgid "" "libvirt has no result of the copy; check these volumes of the backup target, " "then resolve this job: %(volumes)s" msgstr "libvirt 没有复制的结果;请检查备份目标中的这些卷,然后解决此作业:%(volumes)s" -#: vmbackups/jobs.py:406 +#: vmbackups/jobs.py:419 msgid "The job stopped before the copy ended" msgstr "作业在复制结束前停止" -#: vmbackups/jobs.py:413 +#: vmbackups/jobs.py:426 #, python-format msgid "The backup's files could not be written: %(error)s" msgstr "无法写入备份文件:%(error)s" -#: vmbackups/jobs.py:433 +#: vmbackups/jobs.py:446 #, python-format msgid "No compute of backup target %(target)s reaches its storage pool" msgstr "备份目标 %(target)s 的计算节点都无法访问其存储池" -#: vmbackups/jobs.py:446 +#: vmbackups/jobs.py:480 msgid "Delete backup" msgstr "删除备份" -#: vmbackups/jobs.py:455 +#: vmbackups/jobs.py:491 msgid "This backup is being made; cancel its job to stop it" msgstr "此备份正在创建;要停止它,请取消其作业" -#: vmbackups/jobs.py:519 +#: vmbackups/jobs.py:504 +msgid "The backup is no longer beyond what its schedule keeps; it is kept" +msgstr "该备份已不再超出其计划保留的数量;予以保留" + +#: vmbackups/jobs.py:556 #, python-format msgid "The backup's file %(name)s is missing from the target" msgstr "目标中缺少备份文件 %(name)s" -#: vmbackups/jobs.py:522 vmbackups/jobs.py:524 +#: vmbackups/jobs.py:559 vmbackups/jobs.py:561 #, python-format msgid "The backup's file %(name)s differs from the one written" msgstr "备份文件 %(name)s 与写入的不同" -#: vmbackups/jobs.py:534 vmbackups/templates/vmbackups/restore.html:7 +#: vmbackups/jobs.py:571 vmbackups/templates/vmbackups/restore.html:7 msgid "Restore backup" msgstr "恢复备份" -#: vmbackups/jobs.py:547 +#: vmbackups/jobs.py:584 msgid "Only a ready backup is restored" msgstr "只能恢复就绪的备份" -#: vmbackups/jobs.py:577 +#: vmbackups/jobs.py:614 #, python-format msgid "A VM named %(name)s exists on %(compute)s" msgstr "%(compute)s 上已存在名为 %(name)s 的虚拟机" -#: vmbackups/jobs.py:585 +#: vmbackups/jobs.py:622 #, python-format msgid "This host has no active directory storage pool %(pool)s" msgstr "此主机没有名为 %(pool)s 的活动目录存储池" -#: vmbackups/jobs.py:602 +#: vmbackups/jobs.py:639 #, python-format msgid "The NVRAM file %(path)s exists already" msgstr "NVRAM 文件 %(path)s 已存在" -#: vmbackups/jobs.py:633 +#: vmbackups/jobs.py:670 #, python-format msgid "The VM was restored; it did not start: %(error)s" msgstr "虚拟机已恢复;但未能启动:%(error)s" -#: vmbackups/jobs.py:655 +#: vmbackups/jobs.py:692 #, python-format msgid "" "A disk was being copied when the job stopped; check this volume, then resolve" " this job: %(volumes)s" msgstr "作业停止时正在复制磁盘;请检查此卷,然后解决此作业:%(volumes)s" -#: vmbackups/jobs.py:660 +#: vmbackups/jobs.py:697 #, python-format msgid "" "Storage pool %(pool)s is not active; the restore's copies in it are removed " "when it is" msgstr "存储池 %(pool)s 未激活;其中恢复的副本将在其激活后删除" -#: vmbackups/jobs.py:669 +#: vmbackups/jobs.py:706 msgid "The VM was not defined; its copies were removed" msgstr "虚拟机未定义;其副本已删除" -#: vmbackups/jobs.py:688 vmbackups/templates/vmbackups/target.html:18 +#: vmbackups/jobs.py:725 vmbackups/templates/vmbackups/target.html:18 msgid "Read backups from target" msgstr "从目标读取备份" -#: vmbackups/jobs.py:736 +#: vmbackups/jobs.py:773 #, python-format msgid "" "Not read, as a file of the backup is missing, changed or unreadable: " "%(names)s" msgstr "由于备份的某个文件缺失、已更改或无法读取,未读取:%(names)s" +#: vmbackups/jobs.py:789 +msgid "Check backup target" +msgstr "检查备份目标" + +#: vmbackups/jobs.py:816 +#, python-format +msgid "Files of these backups are missing from the target: %(backups)s" +msgstr "以下备份的文件在目标中缺失:%(backups)s" + +#: vmbackups/schedule.py:28 +msgid "Not started within 6 hours of its time" +msgstr "未在计划时间后的 6 小时内启动" + +#: vmbackups/schedule.py:29 +msgid "The host was in maintenance" +msgstr "主机处于维护中" + +#: vmbackups/schedule.py:30 +msgid "The schedule's owner is no longer an active superuser" +msgstr "该计划的所有者已不再是活动的超级用户" + #: vmbackups/templates/vmbackups/consistency.html:1 msgid "Shut off" msgstr "已关闭" diff --git a/vmbackups/jobs.py b/vmbackups/jobs.py index 840f0c18..0b20b047 100644 --- a/vmbackups/jobs.py +++ b/vmbackups/jobs.py @@ -22,7 +22,7 @@ from instances.jobs import PAUSED_FROZEN, THAW_FAILED, _instance, _log, _snapsho from instances.utils import get_random_mac_address from instances.models import Instance from operations import claims -from operations.jobs import Cancelled, Kind, Outcome, Plan, register +from operations.jobs import Cancelled, Kind, Outcome, Plan, register, register_periodic from operations.models import Claim, Operation from operations.utils import safe_text, say from vrtManager import util @@ -190,8 +190,9 @@ class CreateBackup(Kind): def normalize(self, raw): return {"instance": int(raw["instance"]), "target": int(raw["target"]), "frozen": str(raw.get("frozen", "")).lower() in ("1", "true", "on"), - # the schedule that asked for it, if one did - "policy": int(raw["policy"]) if raw.get("policy") else None} + # the schedule that asked for it, if one did, and the end of its window + "policy": int(raw["policy"]) if raw.get("policy") else None, + "deadline": parse_datetime(raw["deadline"]).isoformat() if raw.get("deadline") else None} def plan(self, user, params): _superuser(user) @@ -213,6 +214,14 @@ class CreateBackup(Kind): def run(self, op, ctx): instance, target, row, proxy, pool, plan = _checked(op) + if op.params.get("policy"): + # after the host's checks, which may have waited for it: a schedule's backup starts in its window, + # and on no host gone into maintenance (one by hand may) + if op.params.get("deadline") and timezone.now() > parse_datetime(op.params["deadline"]): + raise util.OperationError(_("The schedule's window ended before the backup could start")) + if instance.compute._in_maintenance_now(): + raise util.OperationError(_("%(compute)s went into maintenance before the scheduled backup could " + "start"), compute=instance.compute.name) status = proxy.get_status() live = status != VIR_DOMAIN_SHUTOFF names = backup_file_names(op.intent["backup"], plan["disks"], bool(plan["nvram"])) @@ -437,10 +446,31 @@ def _target_pool(target): raise util.OperationError(_("No compute of backup target %(target)s reaches its storage pool"), target=target.name) +def _target_claims(target): + """A job on a target alone: the target, and its computes shared, which + the worker counts so a hung host takes no more than its share of slots.""" + keys = {claims.compute_key(compute_id): Claim.SHARED + for compute_id in target.pools.values_list("compute_id", flat=True)} + keys[claims.backup_target_key(target.pk)] = Claim.EXCLUSIVE + return keys + + def _backup(params): return Backup.objects.select_related("target").get(uuid=params["backup"]) +def _beyond_keep(backup, policy_id): + """Whether the schedule still exists and the backup is still one of its + VM's ready backups beyond what it keeps (keep raised, or a newer one gone, + since the deletion was queued).""" + policy = BackupPolicy.objects.filter(pk=policy_id).first() + if policy is None or backup.policy_id != policy.pk or backup.instance_id is None: + return False + ready = list(Backup.objects.filter(policy=policy, instance_id=backup.instance_id, state=Backup.READY) + .order_by("-created_at").values_list("pk", flat=True)) + return backup.pk in ready[policy.keep:] + + @register class DeleteBackup(Kind): """The manifest goes first, so the target no longer holds a complete @@ -450,7 +480,9 @@ class DeleteBackup(Kind): label = _("Delete backup") def normalize(self, raw): - return {"backup": str(UUID(str(raw["backup"])))} + # retention: the schedule whose keep the backup is beyond, when the schedule asks + return {"backup": str(UUID(str(raw["backup"]))), + "retention": int(raw["retention"]) if raw.get("retention") else None} def plan(self, user, params): _superuser(user) @@ -458,8 +490,7 @@ class DeleteBackup(Kind): if backup.state == Backup.CREATING: raise util.OperationError(_("This backup is being made; cancel its job to stop it")) return Plan( - claims={claims.backup_key(backup.uuid): Claim.EXCLUSIVE, - claims.backup_target_key(backup.target_id): Claim.EXCLUSIVE}, + claims={claims.backup_key(backup.uuid): Claim.EXCLUSIVE, **_target_claims(backup.target)}, resource=claims.backup_key(backup.uuid), label=f"{backup.target.name}/{backup.vm_name}", intent={"compute": backup.compute_name, "vm": backup.vm_name, "uuid": backup.vm_uuid, @@ -469,6 +500,8 @@ class DeleteBackup(Kind): def run(self, op, ctx): _superuser(op.user) backup = _backup(op.params) + if op.params.get("retention") and not _beyond_keep(backup, op.params["retention"]): + raise util.OperationError(_("The backup is no longer beyond what its schedule keeps; it is kept")) _conn, pool = _target_pool(backup.target) ctx.record_intent(deleting=True) return self._delete(backup, pool) @@ -697,7 +730,7 @@ class ImportBackups(Kind): def plan(self, user, params): _superuser(user) target = BackupTarget.objects.get(pk=params["target"]) - return Plan(claims={claims.backup_target_key(target.pk): Claim.EXCLUSIVE}, + return Plan(claims=_target_claims(target), resource=claims.backup_target_key(target.pk), label=target.name, intent={"target": target.name}) def run(self, op, ctx): @@ -744,3 +777,51 @@ class ImportBackups(Kind): def log_entry(self, op, state): message = f"Backup target {op.intent['target']}: backups read" return "-", "", "", message if state == Operation.SUCCEEDED else f"{message} ({state})" + + +@register +class CheckTarget(Kind): + """A target's backups checked against its pool: a ready backup with a + file gone (its manifest too) becomes missing, a missing one whose files + are all there ready again. A pool no compute reaches marks nothing.""" + + name = "backup.check" + label = _("Check backup target") + + def normalize(self, raw): + return {"target": int(raw["target"])} + + def plan(self, user, params): + _superuser(user) + target = BackupTarget.objects.get(pk=params["target"]) + return Plan(claims=_target_claims(target), + resource=claims.backup_target_key(target.pk), label=target.name, intent={"target": target.name}) + + def run(self, op, ctx): + _superuser(op.user) + target = BackupTarget.objects.get(pk=op.params["target"]) + _conn, pool = _target_pool(target) + pool.refresh(0) + present = set(pool.listVolumes()) + 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"} + state = Backup.READY if needed <= present else Backup.MISSING + 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()) + if missing: + return {"warning": say(_("Files of these backups are missing from the target: %(backups)s"), + backups=", ".join(missing))} + return {} + + def log_entry(self, op, state): + message = f"Backup target {op.intent['target']}: checked" + return "-", "", "", message if state == Operation.SUCCEEDED else f"{message} ({state})" + + +from .schedule import run_schedules # noqa: E402 (it submits this module's kinds) + +register_periodic(run_schedules) diff --git a/vmbackups/schedule.py b/vmbackups/schedule.py new file mode 100644 index 00000000..1fba4e8e --- /dev/null +++ b/vmbackups/schedule.py @@ -0,0 +1,183 @@ +"""Backup schedules, run by the worker about once a minute (its periodic +tasks): each schedule's VMs backed up once a local day within WINDOW of its +time, each VM's backups of the schedule beyond keep deleted, and each target +checked once a day. The jobs run as the schedule's owner.""" + +import datetime +import logging +from concurrent.futures import ThreadPoolExecutor + +from django.contrib.auth import get_user_model +from django.db import close_old_connections +from django.core.exceptions import PermissionDenied +from django.utils import timezone +from django.utils.translation import gettext_noop as _ +from libvirt import libvirtError + +from computes.models import Compute +from operations import claims, jobs +from operations.models import Operation +from operations.utils import safe_text +from vrtManager.util import ConnectionFailed + +from .models import Backup, BackupPolicy, BackupRun, BackupTarget + +logger = logging.getLogger(__name__) + +WINDOW = datetime.timedelta(hours=6) # a run is admitted this long after its time, else skipped +NOT_STARTED = _("Not started within 6 hours of its time") +IN_MAINTENANCE = _("The host was in maintenance") +NO_OWNER = _("The schedule's owner is no longer an active superuser") +RETRY_AFTER = datetime.timedelta(hours=1) # a deletion or check that failed is tried again after this + +# each compute's submissions in a task of their own, at most one a compute: with a thread for every +# compute, hung hosts take no thread a healthy host's task needs (threads start only when needed) +THREADS = 64 +_pool = ThreadPoolExecutor(THREADS, thread_name_prefix="wvc-schedule") +_tasks = {} # compute id -> the future of its last task + + +def run_schedules(now=None): + now = now or timezone.now() + due = {} # compute id -> [(policy, vm, day)] + for policy in BackupPolicy.objects.filter(enabled=True).select_related("owner"): + for day, start in occurrences(policy, now): + open_ = now < start + WINDOW + done = set(BackupRun.objects.filter(policy=policy, day=day).values_list("instance_id", flat=True)) + for vm in policy.vms(): + if vm.pk in done: + continue + in_maintenance = Compute.objects.filter(pk=vm.compute_id, maintenance_since__isnull=False).exists() + if not open_: + _record(policy, vm, day, BackupRun.SKIPPED, IN_MAINTENANCE if in_maintenance else NOT_STARTED) + elif not in_maintenance: # deferred while the window lasts + due.setdefault(vm.compute_id, []).append((policy.pk, vm.pk, day, start)) + for compute_id, items in due.items(): + task = _tasks.get(compute_id) + if task is None or task.done(): + _tasks[compute_id] = _pool.submit(_submit_all, compute_id, items) + retain() + check_targets(now) + + +def occurrences(policy, now): + """(local day, instant) of the schedule's times yesterday and today that + have come and are not older than the schedule: a late time's window goes + on after midnight. A time a spring-forward gap skips falls an hour later + (zoneinfo, fold 0); a time repeated in autumn is its first.""" + zone = timezone.get_default_timezone() + today = timezone.localtime(now, zone).date() + for day in (today - datetime.timedelta(days=1), today): + # in UTC: the window is real hours, also on a day the clocks change + start = datetime.datetime.combine(day, policy.time, tzinfo=zone).astimezone(datetime.timezone.utc) + if policy.created_at <= start <= 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": note[:255], "operation": operation}) + + +def _active_superuser(user): + return user is not None and user.is_active and user.is_superuser + + +def _submit_all(compute_id, items): + """One compute's due backups, one after another, each checked again as + it comes: the task may have waited for a thread. A busy target or an + unreachable host is tried again at the next pass.""" + try: + for policy_id, vm_id, day, start in items: + _submit(policy_id, vm_id, day, start) + finally: + close_old_connections() # a thread of the pool: its connection is its own + + +def _submit(policy_id, vm_id, day, start): + policy = BackupPolicy.objects.select_related("owner").filter(pk=policy_id, enabled=True).first() + now = timezone.now() + if policy is None or now >= start + WINDOW or (day, start) not in set(occurrences(policy, now)): + return # disabled, deleted or its time moved meanwhile, or its window ended: the next pass decides + vm = policy.vms().filter(pk=vm_id).first() + if vm is None or BackupRun.objects.filter(policy=policy, instance=vm, day=day).exists(): + return + if Compute.objects.filter(pk=vm.compute_id, maintenance_since__isnull=False).exists(): + return + if not _active_superuser(policy.owner): + _record(policy, vm, day, BackupRun.FAILED, NO_OWNER) + return + # the same key for the same run: a worker stopped before the row was written gets the same job back + key = f"bk-{policy.pk}-{vm.pk}-{day:%Y%m%d}" + raw = {"instance": vm.pk, "target": policy.target_id, "frozen": policy.frozen, "policy": policy.pk, + "deadline": (start + WINDOW).isoformat()} # a job that waited past it for a worker slot does not start + try: + op = jobs.submit("backup.create", policy.owner, raw, key) + except (claims.Busy, ConnectionFailed): + return + except (libvirtError, PermissionDenied, jobs.SubmissionConflict) as err: # it would be refused again + _record(policy, vm, day, BackupRun.FAILED, safe_text(str(err) or type(err).__name__)) + return + except Exception as err: + logger.error("schedule %s: backup of %s not submitted: %s", policy.name, vm.name, safe_text(err)) + return + _record(policy, vm, day, BackupRun.SUBMITTED, operation=op) + + +def _attempt_key(base): + """The submission key of the next attempt of a job named base: the + running or ended one's own, so it is not submitted twice; a new one an + hour after a failed or cancelled one; None before that.""" + attempts = Operation.objects.filter(submission_key__startswith=f"{base}-") + last = attempts.order_by("-created_at").first() + if last is None: + return f"{base}-0" + if last.state not in (Operation.FAILED, Operation.CANCELLED): + return last.submission_key + if last.finished_at and timezone.now() - last.finished_at < RETRY_AFTER: + return None + return f"{base}-{attempts.count()}" + + +def retain(): + """Each schedule's ready backups of a VM beyond keep, oldest first: one + deletion a target at a time (its claim admits one), the rest at the next + passes. Backups by hand and those of removed VMs are left alone.""" + tried = set() + for policy in BackupPolicy.objects.select_related("owner"): + if policy.target_id in tried or not _active_superuser(policy.owner): + continue + ready = (Backup.objects.filter(policy=policy, state=Backup.READY, instance__isnull=False) + .order_by("instance_id", "-created_at")) + groups = {} + for backup in ready: + groups.setdefault(backup.instance_id, []).append(backup) + for rows in groups.values(): + if len(rows) > policy.keep: + tried.add(policy.target_id) + if (key := _attempt_key(f"rt-{rows[-1].uuid.hex}")) is None: + break + try: + jobs.submit("backup.delete", policy.owner, {"backup": str(rows[-1].uuid), "retention": policy.pk}, + key) + except Exception as err: # busy, or refused: the next pass looks again + logger.info("schedule %s: retention waits: %s", policy.name, safe_text(err)) + break + + +def check_targets(now): + """A backup.check job for each target not checked today, as the first + active superuser; a busy target is checked at a later pass.""" + today = timezone.localtime(now).date() + user = get_user_model().objects.filter(is_superuser=True, is_active=True).order_by("pk").first() + if user is None: + return + for target in BackupTarget.objects.filter(pools__isnull=False).distinct(): + if target.checked_at and timezone.localtime(target.checked_at).date() >= today: + continue + if (key := _attempt_key(f"ck-{target.pk}-{today:%Y%m%d}")) is None: + continue + try: + jobs.submit("backup.check", user, {"target": target.pk}, key) + except Exception as err: + logger.info("target %s: check waits: %s", target.name, safe_text(err)) diff --git a/vmbackups/tests/test_schedule.py b/vmbackups/tests/test_schedule.py new file mode 100644 index 00000000..a0127eb5 --- /dev/null +++ b/vmbackups/tests/test_schedule.py @@ -0,0 +1,463 @@ +"""Backup schedules: the worker's periodic pass submits each VM's backup once +a day within its window, deletes what is beyond keep, checks targets.""" + +import datetime +from concurrent.futures import Future +from types import SimpleNamespace +from unittest.mock import MagicMock, patch + +import libvirt +from django.contrib.auth import get_user_model +from django.test import TransactionTestCase, override_settings + +from appsettings.settings import get_settings +from computes.models import Compute +from instances.models import Instance +from operations import jobs +from operations.jobs import Context +from operations.models import Operation, acquire +from vmbackups import schedule +from vmbackups.jobs import CheckTarget, DeleteBackup +from vmbackups.models import Backup, BackupFile, BackupPolicy, BackupRun, BackupTarget, BackupTargetPool +from vrtManager.util import OperationError + +UTC = datetime.timezone.utc +WORKER = "wvc-test:1:a" + + +def at(*args): + return datetime.datetime(*args, tzinfo=UTC) + + +class Inline: + """The pool of per-compute tasks, run at once; pending: computes whose task still runs; + queued: tasks held until run_queued (busy threads).""" + + def __init__(self): + self.pending = set() + self.hold = False + self.queued = [] + + def submit(self, fn, compute_id, items): + future = Future() + if compute_id in self.pending: + return future # never done: a hung host + if self.hold: + self.queued.append((fn, compute_id, items, future)) + return future + fn(compute_id, items) + future.set_result(None) + return future + + def run_queued(self, now): + with patch("django.utils.timezone.now", return_value=now): + for fn, compute_id, items, future in self.queued: + fn(compute_id, items) + future.set_result(None) + + +def proxy(): + p = MagicMock() + p.get_status.return_value = libvirt.VIR_DOMAIN_SHUTOFF + p.backup_plan.return_value = {"definition": "", "disks": [], "nvram": None, "left_out": []} + return p + + +@override_settings(TIME_ZONE="UTC") +class ScheduleTests(TransactionTestCase): + def setUp(self): + get_settings() + self.admin = get_user_model().objects.create_superuser("sc_admin", "a@example.com", "pw") + self.c1 = Compute.objects.create(name="h1", hostname="192.0.2.71", login="u", password="p", type=1) + self.c2 = Compute.objects.create(name="h2", hostname="192.0.2.72", login="u", password="p", type=1) + self.vm1 = Instance.objects.create(compute=self.c1, name="vm1", uuid="71717171-0000-4000-8000-000000000001") + self.vm2 = Instance.objects.create(compute=self.c1, name="vm2", uuid="71717171-0000-4000-8000-000000000002") + self.target = BackupTarget.objects.create(name="nfs1", checked_at=at(2026, 11, 17, 0, 0)) + BackupTargetPool.objects.create(target=self.target, compute=self.c1, pool="b1", pool_uuid="u") + BackupTargetPool.objects.create(target=self.target, compute=self.c2, pool="b1", pool_uuid="u") + self.policy = BackupPolicy.objects.create(name="nightly", target=self.target, time=datetime.time(2, 0), keep=2, + owner=self.admin) + BackupPolicy.objects.filter(pk=self.policy.pk).update(created_at=at(2026, 11, 17)) + self.policy.refresh_from_db() + self.policy.instances.add(self.vm1) + self.pool = Inline() + self.proxy = proxy() + target_pool = MagicMock() + target_pool.info.return_value = [2, 1 << 40, 0, 1 << 40] + for name, value in (("vmbackups.schedule._pool", self.pool), + ("vmbackups.schedule._tasks", {}), + ("vmbackups.jobs.wvmBackup", MagicMock(return_value=self.proxy)), + ("vmbackups.jobs.target_pool", MagicMock(return_value=target_pool))): + patcher = patch(name, value) + patcher.start() + self.addCleanup(patcher.stop) + + def pass_at(self, now): + """A pass of the worker at now, its tasks run then too.""" + with patch("django.utils.timezone.now", return_value=now): + schedule.run_schedules(now) + + def creates(self): + return list(Operation.objects.filter(kind="backup.create").order_by("created_at")) + + def finish_all(self): + for op in Operation.objects.filter(state__in=Operation.ACTIVE): + jobs.finish(op, jobs.Outcome(Operation.SUCCEEDED)) + + def test_due_at_its_time_not_before(self): + self.pass_at(at(2026, 11, 17, 1, 59)) + self.assertEqual(self.creates(), []) + self.pass_at(at(2026, 11, 17, 2, 0)) + op = self.creates()[0] + self.assertEqual(op.params, {"instance": self.vm1.pk, "target": self.target.pk, "frozen": False, + "policy": self.policy.pk, "deadline": "2026-11-17T08:00:00+00:00"}) + self.assertEqual(op.username, "sc_admin") + run = BackupRun.objects.get() + self.assertEqual((run.instance, run.day, run.state, run.operation), (self.vm1, datetime.date(2026, 11, 17), + BackupRun.SUBMITTED, op)) + + def test_a_backup_that_waited_past_its_window_does_not_start(self): + from operations.jobs import Context + from vmbackups.jobs import CreateBackup + + self.pass_at(at(2026, 11, 17, 7, 59)) + op = self.creates()[0] + acquire(WORKER, "wvc-test") + Operation.objects.filter(pk=op.pk).update(state=Operation.RUNNING, worker=WORKER) + op.refresh_from_db() + with patch("django.utils.timezone.now", return_value=at(2026, 11, 17, 8, 1)): # it waited for a slot + with self.assertRaisesMessage(OperationError, "window ended"): + CreateBackup().run(op, Context(op, SimpleNamespace(identity=WORKER))) + self.assertFalse(Backup.objects.exists()) + self.proxy.copy_disk_offline.assert_not_called() + + def started(self, now, op): + from operations.jobs import Context + from vmbackups.jobs import CreateBackup + + acquire(WORKER, "wvc-test") + Operation.objects.filter(pk=op.pk).update(state=Operation.RUNNING, worker=WORKER) + op.refresh_from_db() + with patch("django.utils.timezone.now", return_value=now): + CreateBackup().run(op, Context(op, SimpleNamespace(identity=WORKER))) + + def test_a_scheduled_backup_whose_host_went_into_maintenance_does_not_start(self): + self.pass_at(at(2026, 11, 17, 2, 0)) + Compute.objects.filter(pk=self.c1.pk).update(maintenance_since=at(2026, 11, 17, 2, 1)) + with self.assertRaisesMessage(OperationError, "maintenance"): + self.started(at(2026, 11, 17, 2, 2), self.creates()[0]) + self.assertFalse(Backup.objects.exists()) + + def test_the_window_is_checked_again_after_the_host_answered(self): + self.pass_at(at(2026, 11, 17, 7, 59)) + # the host answers the checks only after the window ended + self.proxy.backup_plan.side_effect = lambda: patch_now.start() or { + "definition": "", "disks": [], "nvram": None, "left_out": []} + patch_now = patch("django.utils.timezone.now", return_value=at(2026, 11, 17, 8, 30)) + self.addCleanup(patch.stopall) + with self.assertRaisesMessage(OperationError, "window ended"): + self.started(at(2026, 11, 17, 7, 59, 30), self.creates()[0]) + self.assertFalse(Backup.objects.exists()) + + def test_once_a_day(self): + self.pass_at(at(2026, 11, 17, 2, 0)) + self.finish_all() + self.pass_at(at(2026, 11, 17, 3, 0)) + self.assertEqual(len(self.creates()), 1) + self.pass_at(at(2026, 11, 18, 2, 1)) + self.assertEqual(len(self.creates()), 2) + + def test_a_worker_stopped_between_the_job_and_its_run_row_submits_no_second_job(self): + self.pass_at(at(2026, 11, 17, 2, 0)) + BackupRun.objects.all().delete() # the row was never written + self.pass_at(at(2026, 11, 17, 2, 1)) + self.assertEqual(len(self.creates()), 1) + self.assertEqual(BackupRun.objects.get().operation, self.creates()[0]) + + def test_a_busy_target_is_tried_again_and_the_vms_go_one_after_another(self): + self.policy.instances.add(self.vm2) + self.pass_at(at(2026, 11, 17, 2, 0)) + self.assertEqual(BackupRun.objects.count(), 1) # the target admits one copy + self.pass_at(at(2026, 11, 17, 2, 1)) + self.assertEqual(BackupRun.objects.count(), 1) # still busy + self.finish_all() + self.pass_at(at(2026, 11, 17, 2, 30)) + self.assertEqual(BackupRun.objects.count(), 2) + + def test_a_host_in_maintenance_is_deferred_then_skipped(self): + Compute.objects.filter(pk=self.c1.pk).update(maintenance_since=at(2026, 11, 16)) + self.pass_at(at(2026, 11, 17, 2, 0)) + self.assertEqual(BackupRun.objects.count(), 0) + self.pass_at(at(2026, 11, 17, 8, 1)) + run = BackupRun.objects.get() + self.assertEqual(run.state, BackupRun.SKIPPED) + self.assertIn("maintenance", run.note) + self.assertEqual(self.creates(), []) + + def test_maintenance_ended_inside_the_window(self): + Compute.objects.filter(pk=self.c1.pk).update(maintenance_since=at(2026, 11, 16)) + self.pass_at(at(2026, 11, 17, 2, 0)) + Compute.objects.filter(pk=self.c1.pk).update(maintenance_since=None) + self.pass_at(at(2026, 11, 17, 4, 0)) + self.assertEqual(BackupRun.objects.get().state, BackupRun.SUBMITTED) + + def test_a_day_the_worker_was_down_is_skipped_not_caught_up(self): + self.pass_at(at(2026, 11, 18, 9, 0)) # down from before 02:00 on the 17th + self.assertEqual(sorted(BackupRun.objects.values_list("day", "state")), + [(datetime.date(2026, 11, 17), BackupRun.SKIPPED), (datetime.date(2026, 11, 18), BackupRun.SKIPPED)]) + self.assertEqual(self.creates(), []) + + def test_a_run_not_started_in_its_window_is_skipped(self): + 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", run.note) + self.assertEqual(self.creates(), []) + + 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)) + self.pass_at(at(2026, 11, 17, 10, 1)) + self.assertEqual(BackupRun.objects.count(), 0) + self.pass_at(at(2026, 11, 18, 2, 0)) + self.assertEqual(BackupRun.objects.get().day, datetime.date(2026, 11, 18)) + + def test_a_late_schedule_still_runs_after_midnight(self): + BackupPolicy.objects.filter(pk=self.policy.pk).update(time=datetime.time(23, 0)) + self.pass_at(at(2026, 11, 18, 1, 0)) # the worker came back after midnight + self.assertEqual(BackupRun.objects.get().day, datetime.date(2026, 11, 17)) + self.assertEqual(len(self.creates()), 1) + + def test_a_task_that_waited_for_a_thread_checks_again_before_it_submits(self): + self.pool.hold = True + self.pass_at(at(2026, 11, 17, 2, 0)) + BackupPolicy.objects.filter(pk=self.policy.pk).update(enabled=False) + self.pool.run_queued(at(2026, 11, 17, 2, 5)) + self.assertEqual(self.creates(), []) + BackupPolicy.objects.filter(pk=self.policy.pk).update(enabled=True) + self.pool.queued.clear() + self.pass_at(at(2026, 11, 17, 7, 59)) + self.pool.run_queued(at(2026, 11, 17, 8, 1)) # its window ended while it waited + self.assertEqual(self.creates(), []) + + def test_a_task_that_waited_while_the_time_was_moved_does_not_submit(self): + self.pool.hold = True + self.pass_at(at(2026, 11, 17, 2, 0)) + BackupPolicy.objects.filter(pk=self.policy.pk).update(time=datetime.time(5, 0)) + self.pool.run_queued(at(2026, 11, 17, 2, 1)) + self.assertEqual(self.creates(), []) + self.assertEqual(BackupRun.objects.count(), 0) + + def test_the_target_jobs_hold_the_targets_computes(self): + from operations.models import Claim + + BackupTarget.objects.filter(pk=self.target.pk).update(checked_at=at(2026, 11, 16)) + schedule.check_targets(at(2026, 11, 17, 9)) + op = Operation.objects.get(kind="backup.check") + # the worker counts a job's hosts by these: a hung host takes no more than its share of the slots + self.assertEqual(set(Claim.objects.filter(operation=op, resource__startswith="compute:") + .values_list("resource", "mode")), + {(f"compute:{self.c1.pk}", Claim.SHARED), (f"compute:{self.c2.pk}", Claim.SHARED)}) + for backup in self.backups(*[Backup.READY] * 3): + pass + jobs.finish(op, jobs.Outcome(Operation.SUCCEEDED)) + schedule.retain() + delete = Operation.objects.get(kind="backup.delete") + self.assertTrue(Claim.objects.filter(operation=delete, resource=f"compute:{self.c1.pk}").exists()) + + def test_an_owner_who_is_no_superuser_fails_the_run(self): + get_user_model().objects.filter(pk=self.admin.pk).update(is_superuser=False) + self.pass_at(at(2026, 11, 17, 2, 0)) + run = BackupRun.objects.get() + self.assertEqual(run.state, BackupRun.FAILED) + self.assertIn("owner", run.note) + + def test_a_vm_that_cannot_be_backed_up_fails_once_with_the_reason(self): + self.proxy.backup_plan.side_effect = OperationError("%(vm)s has TPM state; TPM backups come later", vm="vm1") + self.pass_at(at(2026, 11, 17, 2, 0)) + self.pass_at(at(2026, 11, 17, 2, 1)) + run = BackupRun.objects.get() + self.assertEqual((run.state, run.note), (BackupRun.FAILED, "vm1 has TPM state; TPM backups come later")) + + def test_an_unreachable_host_is_tried_again(self): + from vrtManager.util import ConnectionFailed + + with patch("vmbackups.jobs.wvmBackup", side_effect=ConnectionFailed("Cannot connect to %(host)s", host="h1")): + self.pass_at(at(2026, 11, 17, 2, 0)) + self.assertEqual(BackupRun.objects.count(), 0) + self.pass_at(at(2026, 11, 17, 2, 1)) + self.assertEqual(BackupRun.objects.get().state, BackupRun.SUBMITTED) + + def test_a_compute_schedule_takes_its_vms_now(self): + whole = BackupPolicy.objects.create(name="host", target=self.target, compute=self.c1, time=datetime.time(3), + keep=1, owner=self.admin) + BackupPolicy.objects.filter(pk=whole.pk).update(created_at=at(2026, 11, 17)) + BackupPolicy.objects.filter(pk=self.policy.pk).update(enabled=False) + self.pass_at(at(2026, 11, 17, 3, 0)) + self.finish_all() + self.pass_at(at(2026, 11, 17, 3, 1)) + self.assertEqual(sorted(BackupRun.objects.values_list("instance__name", flat=True)), ["vm1", "vm2"]) + + def test_a_hung_host_stops_no_other_hosts_schedule(self): + vm3 = Instance.objects.create(compute=self.c2, name="vm3", uuid="71717171-0000-4000-8000-000000000003") + other = BackupTarget.objects.create(name="nfs2", checked_at=at(2026, 11, 17)) + BackupTargetPool.objects.create(target=other, compute=self.c2, pool="b2", pool_uuid="u2") + policy = BackupPolicy.objects.create(name="other", target=other, time=datetime.time(2), keep=1, owner=self.admin) + BackupPolicy.objects.filter(pk=policy.pk).update(created_at=at(2026, 11, 17)) + policy.instances.add(vm3) + self.pool.pending.add(self.c1.pk) # its first task never ends + self.pass_at(at(2026, 11, 17, 2, 0)) + self.pass_at(at(2026, 11, 17, 2, 1)) + self.assertEqual(list(BackupRun.objects.values_list("instance__name", flat=True)), ["vm3"]) + + @override_settings(TIME_ZONE="Europe/Berlin") + def test_a_time_in_the_spring_forward_gap_runs_an_hour_later_once(self): + BackupPolicy.objects.filter(pk=self.policy.pk).update(time=datetime.time(2, 30), created_at=at(2026, 3, 29)) + # 2026-03-29 02:30 does not exist in Berlin: 03:30 local, 01:30 UTC + self.pass_at(at(2026, 3, 29, 1, 29)) + self.assertEqual(BackupRun.objects.count(), 0) + self.pass_at(at(2026, 3, 29, 1, 31)) + self.assertEqual(BackupRun.objects.get().day, datetime.date(2026, 3, 29)) + + @override_settings(TIME_ZONE="Europe/Berlin") + def test_the_window_is_six_real_hours_on_a_clock_change_day(self): + BackupPolicy.objects.filter(pk=self.policy.pk).update(time=datetime.time(2, 30), created_at=at(2026, 3, 29)) + self.pass_at(at(2026, 3, 29, 7, 0)) # 5.5 h after 01:30 UTC + self.assertEqual(BackupRun.objects.get().state, BackupRun.SUBMITTED) + + def test_the_schedule_pool_has_a_thread_for_each_compute(self): + self.assertGreaterEqual(schedule.THREADS, 32) + + @override_settings(TIME_ZONE="Europe/Berlin") + def test_a_time_repeated_in_autumn_runs_once(self): + BackupPolicy.objects.filter(pk=self.policy.pk).update(time=datetime.time(2, 30), created_at=at(2026, 10, 25)) + # 2026-10-25 02:30 is 00:30 and 01:30 UTC; the first is the schedule's + self.pass_at(at(2026, 10, 25, 0, 31)) + self.finish_all() + self.pass_at(at(2026, 10, 25, 1, 31)) + self.assertEqual(len(self.creates()), 1) + + # -- retention ------------------------------------------------------- + + def backups(self, *states, policy=True, instance=None): + made = [] + for number, state in enumerate(states): + b = Backup.objects.create(target=self.target, instance=instance or self.vm1, vm_uuid=self.vm1.uuid, + vm_name="vm1", compute_name="h1", state=state, + policy=self.policy if policy else None) + Backup.objects.filter(pk=b.pk).update(created_at=at(2026, 11, 10 + number)) + made.append(b) + return made + + def deletes(self): + return list(Operation.objects.filter(kind="backup.delete").order_by("created_at")) + + def test_retention_deletes_the_oldest_beyond_keep_one_at_a_time(self): + oldest, older, _new, _newest = self.backups(*[Backup.READY] * 4) + schedule.retain() + (op,) = self.deletes() + self.assertEqual(op.params, {"backup": str(oldest.uuid), "retention": self.policy.pk}) + schedule.retain() # the target is busy with that deletion + self.assertEqual(len(self.deletes()), 1) + self.finish_all() + Backup.objects.filter(pk=oldest.pk).delete() + schedule.retain() + self.assertEqual(self.deletes()[-1].params["backup"], str(older.uuid)) + + def test_a_failed_deletion_is_tried_again_an_hour_later(self): + oldest, *_rest = self.backups(*[Backup.READY] * 3) + schedule.retain() + (op,) = self.deletes() + jobs.finish(op, jobs.Outcome(Operation.FAILED)) + schedule.retain() + self.assertEqual(len(self.deletes()), 1) # not every minute + Operation.objects.filter(pk=op.pk).update(finished_at=op.finished_at - datetime.timedelta(minutes=61)) + schedule.retain() + self.assertEqual(len(self.deletes()), 2) + self.assertEqual(self.deletes()[-1].params["backup"], str(oldest.uuid)) + + def test_retention_keeps_keep_ready_backups_when_the_newest_failed(self): + self.backups(Backup.READY, Backup.READY, Backup.FAILED) + schedule.retain() + self.assertEqual(self.deletes(), []) + + def test_retention_leaves_backups_by_hand_and_of_removed_vms(self): + self.backups(Backup.READY, Backup.READY, policy=False) + self.backups(Backup.READY, Backup.READY, Backup.READY) + Backup.objects.filter(policy=self.policy).update(instance=None) # the VM row is gone + schedule.retain() + self.assertEqual(self.deletes(), []) + + def run_delete(self, backup): + op = jobs.submit("backup.delete", self.admin, {"backup": str(backup.uuid), "retention": self.policy.pk}, + "key-retain-0001") + acquire(WORKER, "wvc-test") + Operation.objects.filter(pk=op.pk).update(state=Operation.RUNNING, worker=WORKER) + op.refresh_from_db() + return op, Context(op, SimpleNamespace(identity=WORKER)) + + @patch("vmbackups.jobs._target_pool") + def test_a_retention_deletion_checks_again_before_it_deletes(self, target_pool): + oldest, *_rest = self.backups(*[Backup.READY] * 3) + op, ctx = self.run_delete(oldest) + BackupPolicy.objects.filter(pk=self.policy.pk).update(keep=5) # raised meanwhile + with self.assertRaisesMessage(OperationError, "no longer beyond"): + DeleteBackup().run(op, ctx) + target_pool.assert_not_called() + self.assertTrue(Backup.objects.filter(pk=oldest.pk, state=Backup.READY).exists()) + op.refresh_from_db() + self.assertFalse(op.effects_started) + + # -- target check ------------------------------------------------------ + + def test_a_target_is_checked_once_a_day(self): + BackupTarget.objects.filter(pk=self.target.pk).update(checked_at=at(2026, 11, 16, 9)) + schedule.check_targets(at(2026, 11, 17, 9)) + schedule.check_targets(at(2026, 11, 17, 9, 1)) + (op,) = Operation.objects.filter(kind="backup.check") + self.assertEqual(op.params, {"target": self.target.pk}) + + def test_a_failed_check_is_tried_again_an_hour_later(self): + BackupTarget.objects.filter(pk=self.target.pk).update(checked_at=at(2026, 11, 16, 9)) + schedule.check_targets(at(2026, 11, 17, 9)) + (op,) = Operation.objects.filter(kind="backup.check") + jobs.finish(op, jobs.Outcome(Operation.FAILED)) + schedule.check_targets(at(2026, 11, 17, 9, 1)) + self.assertEqual(Operation.objects.filter(kind="backup.check").count(), 1) + Operation.objects.filter(pk=op.pk).update(finished_at=op.finished_at - datetime.timedelta(minutes=61)) + schedule.check_targets(at(2026, 11, 17, 10, 5)) + self.assertEqual(Operation.objects.filter(kind="backup.check").count(), 2) + + def run_check(self, names): + op = jobs.submit("backup.check", self.admin, {"target": self.target.pk}, "key-check-0001") + acquire(WORKER, "wvc-test") + Operation.objects.filter(pk=op.pk).update(state=Operation.RUNNING, worker=WORKER) + op.refresh_from_db() + pool = MagicMock() + pool.listVolumes.return_value = names + with patch("vmbackups.jobs._target_pool", return_value=(MagicMock(), pool)): + return CheckTarget().run(op, Context(op, SimpleNamespace(identity=WORKER))) + + def test_the_check_marks_missing_files_and_files_back(self): + whole, gone = self.backups(Backup.READY, Backup.READY) + for b in (whole, gone): + BackupFile.objects.create(backup=b, role=BackupFile.DISK, dev="vda", volume=f"{b.prefix}-vda.qcow2") + present = [f"{whole.prefix}-vda.qcow2", f"{whole.prefix}-manifest.json", f"{gone.prefix}-vda.qcow2"] + result = self.run_check(present) # gone's manifest is not there + self.assertEqual(Backup.objects.get(pk=gone.pk).state, Backup.MISSING) + self.assertEqual(Backup.objects.get(pk=whole.pk).state, Backup.READY) + self.assertIn("vm1", result["warning"][0]["values"]["backups"]) + self.assertIsNotNone(BackupTarget.objects.get(pk=self.target.pk).checked_at) + Operation.objects.all().delete() + self.run_check([*present, f"{gone.prefix}-manifest.json"]) + self.assertEqual(Backup.objects.get(pk=gone.pk).state, Backup.READY) + + def test_a_check_that_reaches_no_pool_marks_nothing(self): + (backup,) = self.backups(Backup.READY) + op = jobs.submit("backup.check", self.admin, {"target": self.target.pk}, "key-check-0002") + with patch("vmbackups.jobs._target_pool", side_effect=OperationError("No compute reaches %(t)s", t="nfs1")): + with self.assertRaises(OperationError): + CheckTarget().run(op, Context(op, SimpleNamespace(identity=WORKER))) + self.assertEqual(Backup.objects.get(pk=backup.pk).state, Backup.READY) + + def test_the_pass_runs_from_the_worker(self): + self.assertIn(schedule.run_schedules, jobs.PERIODIC)