1
0
Fork 0
mirror of https://github.com/retspen/webvirtcloud synced 2026-12-02 08:56:07 +00:00

feat(storages): a pool's volume downloaded from a URL

An ISO or a disk image on a web server had to be downloaded by hand and
uploaded, or copied onto the host. A pool of files (dir, fs, netfs) now has
"Download from a URL" for superusers: a volume.fetch job streams the file
(http or https, its size told by the server and within the pool's free
space) into a new volume through libvirt, as an upload is written, on any
connection type; the job panel shows its progress and it can be cancelled.
libvirt reads the file's format (qcow2, raw) when the pool is refreshed. A
cancel, a failure or a crash deletes what it wrote; an address that fails
says why.
This commit is contained in:
catborise 2026-11-20 14:16:01 +03:00
parent e802fa07e2
commit 7c8f5b3150
9 changed files with 775 additions and 106 deletions

Binary file not shown.

View file

@ -11,7 +11,7 @@ msgid ""
msgstr ""
"Project-Id-Version: PACKAGE VERSION\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2026-11-20 11:15+0000\n"
"POT-Creation-Date: 2026-11-20 11:28+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"
@ -324,8 +324,9 @@ msgstr "Burada oturumunuz açık kalır; diğer oturumlarınız kapanır."
#: operations/templates/operations/job.html:31
#: operations/templatetags/operations.py:90
#: storages/templates/create_stg_block.html:183
#: storages/templates/create_stg_vol_block.html:35
#: storages/templates/create_stg_vol_block.html:68
#: storages/templates/create_stg_vol_block.html:36
#: storages/templates/create_stg_vol_block.html:69
#: storages/templates/create_stg_vol_block.html:102
#: storages/templates/storage.html:229 templates/base.html:65
#: templates/common/confirm_delete.html:25 templates/common/form.html:27
#: virtsecrets/templates/create_secret_block.html:48
@ -574,7 +575,7 @@ msgstr ""
"artık kullanmadığınız ya da sızmış olabilecek bir anahtarı silin."
#: accounts/templates/profile.html:73
#: storages/templates/create_stg_vol_block.html:69
#: storages/templates/create_stg_vol_block.html:70
msgid "Create"
msgstr "Oluştur"
@ -3453,8 +3454,9 @@ msgstr "Bağlan"
#: nwfilters/templates/create_nwfilter_block.html:17
#: nwfilters/templates/nwfilter.html:169 nwfilters/templates/nwfilters.html:85
#: storages/templates/create_stg_block.html:21
#: storages/templates/create_stg_vol_block.html:16
#: storages/templates/create_stg_vol_block.html:54
#: storages/templates/create_stg_vol_block.html:17
#: storages/templates/create_stg_vol_block.html:55
#: storages/templates/create_stg_vol_block.html:86
#: storages/templates/storage.html:202 templates/base.html:61
#: virtsecrets/templates/create_secret_block.html:16
#: virtsecrets/templates/secrets.html:97
@ -4603,6 +4605,7 @@ msgstr "Bul"
#: interfaces/templates/interface.html:101 networks/templates/network.html:143
#: networks/templates/network.html:199 networks/templates/network.html:364
#: nodedevs/templates/nodedevs.html:32
#: storages/templates/create_stg_vol_block.html:91
msgid "Address"
msgstr "Adres"
@ -9552,58 +9555,118 @@ msgstr "İmaj adı herhangi bir özel karakter içeremez"
msgid "The image name must not exceed 120 characters"
msgstr "İmaj adı 120 karakterden fazla olamaz"
#: storages/jobs.py:42
#: storages/jobs.py:48
msgid "Clone volume"
msgstr "Birimi klonla"
#: storages/jobs.py:60 storages/jobs.py:73
#: storages/jobs.py:66 storages/jobs.py:79
msgid "Name of volume already in use"
msgstr "Birim adı zaten kullanılıyor"
#: storages/jobs.py:67
#: storages/jobs.py:73
#, python-format
msgid "The pool has no volume named %(name)s"
msgstr "Havuzda %(name)s adında birim yok"
#: storages/jobs.py:69
#: storages/jobs.py:75
msgid "An ISO image is not cloned"
msgstr "ISO imajı klonlanmaz"
#: storages/jobs.py:82
#: storages/jobs.py:88
msgid "Copying the volume"
msgstr "Birim kopyalanıyor"
#: storages/jobs.py:94
#: storages/jobs.py:100
msgid ""
"The copy exists, but the job did not see it finish; check it, then resolve "
"this job."
msgstr ""
"Kopya var, ancak iş bittiğini görmedi; kontrol edin, sonra bu işi çözün."
#: storages/jobs.py:95
#: storages/jobs.py:101
msgid "The copy was not made"
msgstr "Kopya oluşturulmadı"
#: storages/jobs.py:106
#: storages/jobs.py:112
msgid "Upload ISO image"
msgstr "ISO imajı yükle"
#: storages/jobs.py:121
#: storages/jobs.py:127
msgid "Invalid file name"
msgstr "Geçersiz dosya adı"
#: storages/jobs.py:123
#: storages/jobs.py:129
msgid "Only .iso files can be uploaded"
msgstr "Yalnızca .iso dosyaları yüklenebilir"
#: storages/jobs.py:125
#: storages/jobs.py:131
msgid "Invalid file size"
msgstr "Geçersiz dosya boyutu"
#: storages/jobs.py:127
#: storages/jobs.py:133
msgid "Invalid chunk index or total chunks"
msgstr "Geçersiz parça dizini veya toplam parça sayısı"
#: storages/jobs.py:164
msgid "Give an http or https address"
msgstr "Bir http ya da https adresi verin"
#: storages/jobs.py:186
#, python-format
msgid "The file could not be downloaded: %(error)s"
msgstr "Dosya indirilemedi: %(error)s"
#: storages/jobs.py:213
#, python-format
msgid "The server answered %(status)s, not the whole file"
msgstr "Sunucu dosyanın tamamı yerine %(status)s yanıtı verdi"
#: storages/jobs.py:216
#, python-format
msgid "The address is redirected more than %(count)s times"
msgstr "Adres %(count)s defadan fazla yönlendiriliyor"
#: storages/jobs.py:226
msgid "Download volume"
msgstr "Birim indir"
#: storages/jobs.py:241
msgid "A volume's name is letters, digits, '.', '_' and '-'"
msgstr "Birim adı harf, rakam, '.', '_' ve '-' olur"
#: storages/jobs.py:246
msgid "Files are downloaded into a pool of files (dir, fs, netfs)"
msgstr "Dosyalar, dosya tabanlı bir havuza (dir, fs, netfs) indirilir"
#: storages/jobs.py:250
#, python-format
msgid "The pool has a volume named %(name)s"
msgstr "Havuzda %(name)s adında bir birim var"
#: storages/jobs.py:272
msgid "The server does not tell the file's size"
msgstr "Sunucu dosyanın boyutunu bildirmiyor"
#: storages/jobs.py:275
msgid "The file is larger than the pool's free space"
msgstr "Dosya, havuzun boş alanından büyük"
#: storages/jobs.py:285
msgid "The server sent more than the file's size"
msgstr "Sunucu dosyanın boyutundan fazlasını gönderdi"
#: storages/jobs.py:298
msgid "The download ended early"
msgstr "İndirme erken bitti"
#: storages/jobs.py:304
msgid "The download stopped and its volume was not deleted"
msgstr "İndirme durdu ve birimi silinemedi"
#: storages/jobs.py:321
msgid "The download stopped; what it wrote was deleted"
msgstr "İndirme durdu; yazdıkları silindi"
#: storages/templates/create_stg_block.html:7
msgid "New pool"
msgstr "Yeni havuz"
@ -9728,70 +9791,100 @@ msgstr "Havuz hemen ve bundan sonra sunucuyla birlikte başlar."
msgid "Create pool"
msgstr "Havuz oluştur"
#: storages/templates/create_stg_vol_block.html:8
#: storages/templates/create_stg_vol_block.html:9
msgid "Upload ISO"
msgstr "ISO yükle"
#: storages/templates/create_stg_vol_block.html:15
#: storages/templates/create_stg_vol_block.html:16
msgid "Upload ISO Image"
msgstr "ISO İmajı Yükle"
#: storages/templates/create_stg_vol_block.html:18
#: storages/templates/create_stg_vol_block.html:19
msgid "Upload iso form"
msgstr "ISO yükleme formu"
#: storages/templates/create_stg_vol_block.html:19
#: storages/templates/create_stg_vol_block.html:20
msgid "Please select a file to upload."
msgstr "Lütfen yüklenecek bir dosya seçin."
#: storages/templates/create_stg_vol_block.html:19
#: storages/templates/create_stg_vol_block.html:20
msgid "Only .iso files can be uploaded."
msgstr "Yalnızca .iso dosyaları yüklenebilir."
#: storages/templates/create_stg_vol_block.html:20
#: storages/templates/create_stg_vol_block.html:21
msgid "The selected file is empty."
msgstr "Seçilen dosya boş."
#: storages/templates/create_stg_vol_block.html:20
#: storages/templates/create_stg_vol_block.html:29
#: storages/templates/create_stg_vol_block.html:21
#: storages/templates/create_stg_vol_block.html:30
msgid "Starting upload..."
msgstr "Yükleme başlıyor..."
#: storages/templates/create_stg_vol_block.html:21
#: storages/templates/create_stg_vol_block.html:22
msgid ""
"Uploading; the job panel shows its progress. Stay on this page until it ends."
msgstr ""
"Yükleniyor; ilerlemesi iş panelinde görünür. Bitene kadar bu sayfada kalın."
#: storages/templates/create_stg_vol_block.html:22
#: storages/templates/create_stg_vol_block.html:23
msgid "Retrying upload..."
msgstr "Yükleme yeniden deneniyor..."
#: storages/templates/create_stg_vol_block.html:22
#: storages/templates/create_stg_vol_block.html:23
msgid "An error occurred during upload."
msgstr "Yükleme sırasında bir hata oluştu."
#: storages/templates/create_stg_vol_block.html:24
#: storages/templates/create_stg_vol_block.html:25
msgid "ISO file"
msgstr "ISO dosyası"
#: storages/templates/create_stg_vol_block.html:26
#: storages/templates/create_stg_vol_block.html:27
msgid "The browser sends it: keep the page open until the upload ends."
msgstr "Dosyayı tarayıcı gönderir: yükleme bitene kadar sayfayı açık tutun."
#: storages/templates/create_stg_vol_block.html:36
#: storages/templates/create_stg_vol_block.html:37
msgid "Upload"
msgstr "Yükle"
#: storages/templates/create_stg_vol_block.html:45
#: storages/templates/create_stg_vol_block.html:53
#: storages/templates/create_stg_vol_block.html:46
#: storages/templates/create_stg_vol_block.html:54
msgid "New volume"
msgstr "Yeni birim"
#: storages/templates/create_stg_vol_block.html:57
#: storages/templates/create_stg_vol_block.html:58
msgid "Create volume to storage form"
msgstr "Depolamaya birim oluşturma formu"
#: storages/templates/create_stg_vol_block.html:79
#: storages/templates/create_stg_vol_block.html:85
msgid "Download from a URL"
msgstr "Adresten indir"
#: storages/templates/create_stg_vol_block.html:93
msgid ""
"An ISO or a disk image (qcow2, raw) at an http or https address that tells "
"its size. The panel's host downloads it."
msgstr ""
"Boyutunu bildiren bir http ya da https adresindeki ISO ya da disk imajı "
"(qcow2, raw). Paneli çalıştıran sunucu indirir."
#: storages/templates/create_stg_vol_block.html:96 vmbackups/forms.py:60
msgid "Volume name"
msgstr "Birim adı"
#: storages/templates/create_stg_vol_block.html:98
msgid ""
"Empty: the file's name in the address. An ISO keeps its .iso ending, or VMs "
"do not list it as media."
msgstr ""
"Boş bırakılırsa: adresteki dosyanın adı. ISO dosyasının adı .iso ile bitmeli;"
" yoksa VM'ler onu ortam olarak listelemez."
#: storages/templates/create_stg_vol_block.html:103
#: storages/templates/storage.html:176
msgid "Download"
msgstr "İndir"
#: storages/templates/storage.html:14
#, python-format
msgid "Actions for pool %(pool)s"
@ -9920,10 +10013,6 @@ msgstr "Başka bir disk bunun üzerine kurulu"
msgid "%(allocated)s allocated"
msgstr "%(allocated)s ayrılmış"
#: storages/templates/storage.html:176
msgid "Download"
msgstr "İndir"
#: storages/templates/storage.html:180
#, python-format
msgid ""
@ -10057,36 +10146,36 @@ msgstr "Son parça bildirilen dosya boyutuyla eşleşmiyor"
msgid "The partial upload is missing"
msgstr "Kısmi yükleme bulunamadı"
#: storages/views.py:33
#: storages/views.py:34
msgid "No file chunk was submitted."
msgstr "Dosya parçası gönderilmedi."
#: storages/views.py:39
#: storages/views.py:40
msgid "Invalid chunk parameters."
msgstr "Geçersiz parça parametreleri."
#: storages/views.py:41
#: storages/views.py:42
msgid "Invalid chunk index or total chunks."
msgstr "Geçersiz parça dizini veya toplam parça sayısı."
#: storages/views.py:46
#: storages/views.py:47
msgid "Invalid file size."
msgstr "Geçersiz dosya boyutu."
#: storages/views.py:55
#: storages/views.py:56
msgid "Upload session is busy. Please retry."
msgstr "Yükleme oturumu meşgul. Lütfen yeniden deneyin."
#: storages/views.py:57
#: storages/views.py:58
msgid "ISO image already exists"
msgstr "ISO imajı zaten mevcut"
#: storages/views.py:187
#: storages/views.py:188
#, python-format
msgid "Volume: %(vol)s is deleted."
msgstr "Birim: %(vol)s silindi."
#: storages/views.py:204
#: storages/views.py:205
#, python-format
msgid "Image file %(name)s is created successfully"
msgstr "İmaj dosyası %(name)s başarıyla oluşturuldu"
@ -10458,10 +10547,6 @@ msgstr ""
msgid "Start after restore"
msgstr "Geri yüklendikten sonra başlat"
#: vmbackups/forms.py:60
msgid "Volume name"
msgstr "Birim adı"
#: vmbackups/forms.py:82 vmbackups/templates/vmbackups/vm_tab.html:14
msgid "Backup target"
msgstr "Yedek hedefi"
@ -12883,7 +12968,7 @@ msgstr ""
"%(name)s birimi kullanımda: bir sanal makinenin diski, bir temel (backing) "
"dosya ya da bir anlık görüntünün dosyası"
#: vrtManager/storage.py:381
#: vrtManager/storage.py:413
#, python-format
msgid "The running VMs %(vms)s use volume %(name)s; shut them down to copy it"
msgstr ""

Binary file not shown.

View file

@ -7,7 +7,7 @@ msgid ""
msgstr ""
"Project-Id-Version: \n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2026-11-20 11:15+0000\n"
"POT-Creation-Date: 2026-11-20 11:28+0000\n"
"PO-Revision-Date: \n"
"Last-Translator: \n"
"Language-Team: \n"
@ -319,8 +319,9 @@ msgstr "您在此处保持登录;您的其他会话将结束。"
#: operations/templates/operations/job.html:31
#: operations/templatetags/operations.py:90
#: storages/templates/create_stg_block.html:183
#: storages/templates/create_stg_vol_block.html:35
#: storages/templates/create_stg_vol_block.html:68
#: storages/templates/create_stg_vol_block.html:36
#: storages/templates/create_stg_vol_block.html:69
#: storages/templates/create_stg_vol_block.html:102
#: storages/templates/storage.html:229 templates/base.html:65
#: templates/common/confirm_delete.html:25 templates/common/form.html:27
#: virtsecrets/templates/create_secret_block.html:48
@ -564,7 +565,7 @@ msgstr ""
"&lt;token&gt;</code> 的形式发送。修改密码不会删除令牌:请删除不再使用或可能已泄露的令牌。"
#: accounts/templates/profile.html:73
#: storages/templates/create_stg_vol_block.html:69
#: storages/templates/create_stg_vol_block.html:70
msgid "Create"
msgstr "创建"
@ -3283,8 +3284,9 @@ msgstr "连接"
#: nwfilters/templates/create_nwfilter_block.html:17
#: nwfilters/templates/nwfilter.html:169 nwfilters/templates/nwfilters.html:85
#: storages/templates/create_stg_block.html:21
#: storages/templates/create_stg_vol_block.html:16
#: storages/templates/create_stg_vol_block.html:54
#: storages/templates/create_stg_vol_block.html:17
#: storages/templates/create_stg_vol_block.html:55
#: storages/templates/create_stg_vol_block.html:86
#: storages/templates/storage.html:202 templates/base.html:61
#: virtsecrets/templates/create_secret_block.html:16
#: virtsecrets/templates/secrets.html:97
@ -4355,6 +4357,7 @@ msgstr "查找"
#: interfaces/templates/interface.html:101 networks/templates/network.html:143
#: networks/templates/network.html:199 networks/templates/network.html:364
#: nodedevs/templates/nodedevs.html:32
#: storages/templates/create_stg_vol_block.html:91
msgid "Address"
msgstr "地址"
@ -8980,57 +8983,117 @@ msgstr "镜像名称不能包含特殊字符"
msgid "The image name must not exceed 120 characters"
msgstr "镜像名称不能超过 120 个字符"
#: storages/jobs.py:42
#: storages/jobs.py:48
msgid "Clone volume"
msgstr "克隆卷"
#: storages/jobs.py:60 storages/jobs.py:73
#: storages/jobs.py:66 storages/jobs.py:79
msgid "Name of volume already in use"
msgstr "卷名已被使用"
#: storages/jobs.py:67
#: storages/jobs.py:73
#, python-format
msgid "The pool has no volume named %(name)s"
msgstr "存储池中没有名为 %(name)s 的卷"
#: storages/jobs.py:69
#: storages/jobs.py:75
msgid "An ISO image is not cloned"
msgstr "ISO 镜像不会被克隆"
#: storages/jobs.py:82
#: storages/jobs.py:88
msgid "Copying the volume"
msgstr "正在复制卷"
#: storages/jobs.py:94
#: storages/jobs.py:100
msgid ""
"The copy exists, but the job did not see it finish; check it, then resolve "
"this job."
msgstr "副本已存在,但任务未看到其完成;请检查后处理此任务。"
#: storages/jobs.py:95
#: storages/jobs.py:101
msgid "The copy was not made"
msgstr "未创建副本"
#: storages/jobs.py:106
#: storages/jobs.py:112
msgid "Upload ISO image"
msgstr "上传 ISO 镜像"
#: storages/jobs.py:121
#: storages/jobs.py:127
msgid "Invalid file name"
msgstr "文件名无效"
#: storages/jobs.py:123
#: storages/jobs.py:129
msgid "Only .iso files can be uploaded"
msgstr "只能上传 .iso 文件"
#: storages/jobs.py:125
#: storages/jobs.py:131
msgid "Invalid file size"
msgstr "文件大小无效"
#: storages/jobs.py:127
#: storages/jobs.py:133
msgid "Invalid chunk index or total chunks"
msgstr "分块索引或分块总数无效"
#: storages/jobs.py:164
msgid "Give an http or https address"
msgstr "请提供 http 或 https 地址"
#: storages/jobs.py:186
#, python-format
msgid "The file could not be downloaded: %(error)s"
msgstr "无法下载文件:%(error)s"
#: storages/jobs.py:213
#, python-format
msgid "The server answered %(status)s, not the whole file"
msgstr "服务器返回了 %(status)s,而不是完整文件"
#: storages/jobs.py:216
#, python-format
msgid "The address is redirected more than %(count)s times"
msgstr "该地址重定向超过 %(count)s 次"
#: storages/jobs.py:226
msgid "Download volume"
msgstr "下载卷"
#: storages/jobs.py:241
msgid "A volume's name is letters, digits, '.', '_' and '-'"
msgstr "卷名只能包含字母、数字、'.'、'_' 和 '-'"
#: storages/jobs.py:246
msgid "Files are downloaded into a pool of files (dir, fs, netfs)"
msgstr "文件只能下载到文件型存储池(dir、fs、netfs)"
#: storages/jobs.py:250
#, python-format
msgid "The pool has a volume named %(name)s"
msgstr "存储池中已有名为 %(name)s 的卷"
#: storages/jobs.py:272
msgid "The server does not tell the file's size"
msgstr "服务器未告知文件大小"
#: storages/jobs.py:275
msgid "The file is larger than the pool's free space"
msgstr "文件大于存储池的可用空间"
#: storages/jobs.py:285
msgid "The server sent more than the file's size"
msgstr "服务器发送的数据超过了文件大小"
#: storages/jobs.py:298
msgid "The download ended early"
msgstr "下载提前结束"
#: storages/jobs.py:304
msgid "The download stopped and its volume was not deleted"
msgstr "下载已停止,但其卷未被删除"
#: storages/jobs.py:321
msgid "The download stopped; what it wrote was deleted"
msgstr "下载已停止;已写入的内容已删除"
#: storages/templates/create_stg_block.html:7
msgid "New pool"
msgstr "新建存储池"
@ -9153,69 +9216,95 @@ msgstr "存储池立即启动,此后随主机一同启动。"
msgid "Create pool"
msgstr "创建存储池"
#: storages/templates/create_stg_vol_block.html:8
#: storages/templates/create_stg_vol_block.html:9
msgid "Upload ISO"
msgstr "上传 ISO"
#: storages/templates/create_stg_vol_block.html:15
#: storages/templates/create_stg_vol_block.html:16
msgid "Upload ISO Image"
msgstr "上传 ISO 镜像"
#: storages/templates/create_stg_vol_block.html:18
#: storages/templates/create_stg_vol_block.html:19
msgid "Upload iso form"
msgstr "上传 ISO 表单"
#: storages/templates/create_stg_vol_block.html:19
#: storages/templates/create_stg_vol_block.html:20
msgid "Please select a file to upload."
msgstr "请选择要上传的文件。"
#: storages/templates/create_stg_vol_block.html:19
#: storages/templates/create_stg_vol_block.html:20
msgid "Only .iso files can be uploaded."
msgstr "只能上传 .iso 文件。"
#: storages/templates/create_stg_vol_block.html:20
#: storages/templates/create_stg_vol_block.html:21
msgid "The selected file is empty."
msgstr "所选文件为空。"
#: storages/templates/create_stg_vol_block.html:20
#: storages/templates/create_stg_vol_block.html:29
#: storages/templates/create_stg_vol_block.html:21
#: storages/templates/create_stg_vol_block.html:30
msgid "Starting upload..."
msgstr "正在开始上传..."
#: storages/templates/create_stg_vol_block.html:21
#: storages/templates/create_stg_vol_block.html:22
msgid ""
"Uploading; the job panel shows its progress. Stay on this page until it ends."
msgstr "正在上传,任务面板会显示进度。上传结束前请勿离开此页面。"
#: storages/templates/create_stg_vol_block.html:22
#: storages/templates/create_stg_vol_block.html:23
msgid "Retrying upload..."
msgstr "正在重试上传..."
#: storages/templates/create_stg_vol_block.html:22
#: storages/templates/create_stg_vol_block.html:23
msgid "An error occurred during upload."
msgstr "上传时发生错误。"
#: storages/templates/create_stg_vol_block.html:24
#: storages/templates/create_stg_vol_block.html:25
msgid "ISO file"
msgstr "ISO 文件"
#: storages/templates/create_stg_vol_block.html:26
#: storages/templates/create_stg_vol_block.html:27
msgid "The browser sends it: keep the page open until the upload ends."
msgstr "文件由浏览器发送:上传结束前请保持页面打开。"
#: storages/templates/create_stg_vol_block.html:36
#: storages/templates/create_stg_vol_block.html:37
msgid "Upload"
msgstr "上传"
#: storages/templates/create_stg_vol_block.html:45
#: storages/templates/create_stg_vol_block.html:53
#: storages/templates/create_stg_vol_block.html:46
#: storages/templates/create_stg_vol_block.html:54
msgid "New volume"
msgstr "新建卷"
#: storages/templates/create_stg_vol_block.html:57
#: storages/templates/create_stg_vol_block.html:58
msgid "Create volume to storage form"
msgstr "在存储中创建卷的表单"
#: storages/templates/create_stg_vol_block.html:79
#: storages/templates/create_stg_vol_block.html:85
msgid "Download from a URL"
msgstr "从 URL 下载"
#: storages/templates/create_stg_vol_block.html:93
msgid ""
"An ISO or a disk image (qcow2, raw) at an http or https address that tells "
"its size. The panel's host downloads it."
msgstr "位于 http 或 https 地址、且会告知大小的 ISO 或磁盘镜像(qcow2、raw)。由面板所在主机下载。"
#: storages/templates/create_stg_vol_block.html:96 vmbackups/forms.py:60
msgid "Volume name"
msgstr "卷名"
#: storages/templates/create_stg_vol_block.html:98
msgid ""
"Empty: the file's name in the address. An ISO keeps its .iso ending, or VMs "
"do not list it as media."
msgstr "留空:使用地址中的文件名。ISO 须保留 .iso 后缀,否则虚拟机不会将其列为介质。"
#: storages/templates/create_stg_vol_block.html:103
#: storages/templates/storage.html:176
msgid "Download"
msgstr "下载"
#: storages/templates/storage.html:14
#, python-format
msgid "Actions for pool %(pool)s"
@ -9335,10 +9424,6 @@ msgstr "另一个卷基于它"
msgid "%(allocated)s allocated"
msgstr "已分配 %(allocated)s"
#: storages/templates/storage.html:176
msgid "Download"
msgstr "下载"
#: storages/templates/storage.html:180
#, python-format
msgid ""
@ -9469,36 +9554,36 @@ msgstr "最后一个分块与声明的文件大小不符"
msgid "The partial upload is missing"
msgstr "部分上传的文件不存在"
#: storages/views.py:33
#: storages/views.py:34
msgid "No file chunk was submitted."
msgstr "未提交文件分块。"
#: storages/views.py:39
#: storages/views.py:40
msgid "Invalid chunk parameters."
msgstr "分块参数无效。"
#: storages/views.py:41
#: storages/views.py:42
msgid "Invalid chunk index or total chunks."
msgstr "分块索引或分块总数无效。"
#: storages/views.py:46
#: storages/views.py:47
msgid "Invalid file size."
msgstr "文件大小无效。"
#: storages/views.py:55
#: storages/views.py:56
msgid "Upload session is busy. Please retry."
msgstr "上传会话繁忙,请重试。"
#: storages/views.py:57
#: storages/views.py:58
msgid "ISO image already exists"
msgstr "ISO 镜像已存在"
#: storages/views.py:187
#: storages/views.py:188
#, python-format
msgid "Volume: %(vol)s is deleted."
msgstr "卷 %(vol)s 已删除。"
#: storages/views.py:204
#: storages/views.py:205
#, python-format
msgid "Image file %(name)s is created successfully"
msgstr "镜像文件 %(name)s 创建成功"
@ -9844,10 +9929,6 @@ msgstr "恢复的客户机保留虚拟机的地址和主机名:与原虚拟机
msgid "Start after restore"
msgstr "恢复后启动"
#: vmbackups/forms.py:60
msgid "Volume name"
msgstr "卷名"
#: vmbackups/forms.py:82 vmbackups/templates/vmbackups/vm_tab.html:14
msgid "Backup target"
msgstr "备份目标"
@ -12064,7 +12145,7 @@ msgid ""
"Volume %(name)s is in use: a VM's disk, a backing file or a snapshot's file"
msgstr "卷 %(name)s 正在使用中:它是虚拟机的磁盘、后备文件或快照文件"
#: vrtManager/storage.py:381
#: vrtManager/storage.py:413
#, python-format
msgid "The running VMs %(vms)s use volume %(name)s; shut them down to copy it"
msgstr "正在运行的虚拟机 %(vms)s 使用卷 %(name)s;请先将其关闭再复制"

View file

@ -3,16 +3,22 @@
import contextlib
import logging
import os
import posixpath
import re
import time
from urllib.parse import unquote, urljoin, urlsplit
import urllib3
from django.core.exceptions import PermissionDenied
from django.utils.translation import gettext, gettext_noop
from libvirt import libvirtError
from vrtManager import util
from vrtManager.storage import wvmStorage
from vrtManager.storage import FILE_POOL_TYPES, wvmStorage
from computes.models import Compute
from operations import claims, utils
from operations.jobs import Kind, Outcome, Plan, register
from operations.jobs import Cancelled, Kind, Outcome, Plan, register
from operations.models import Claim, Operation
from storages import upload
@ -148,3 +154,180 @@ class UploadVolume(Kind):
def log_entry(self, op, state):
return _log(op, state, f"upload volume {op.params['name']}")
# a volume's name as the pool page's forms take it
VOLUME_NAME = re.compile(r"[A-Za-z0-9._-]{1,120}")
FETCH_PROGRESS_EVERY = 16 * 2**20 # bytes between two progress records
FETCH_REDIRECTS = 5
FETCH_TIMEOUT = urllib3.Timeout(connect=10, read=60)
BAD_ADDRESS = gettext_noop("Give an http or https address")
def url_file_name(url):
"""The file name a URL ends in, or "" (also for an address it cannot read)."""
try:
return posixpath.basename(unquote(urlsplit(url).path))
except ValueError:
return ""
def url_scheme(url):
"""The scheme of a URL with a host, or "" (also for an address it cannot read: an unmatched bracket)."""
try:
parts = urlsplit(url)
return parts.scheme if parts.hostname else ""
except ValueError:
return ""
def _download_error(err):
"""A failed request as the job tells it: what went wrong, not the address (a signed one would show)."""
return util.OperationError(gettext_noop("The file could not be downloaded: %(error)s"),
error=str(getattr(err, "reason", None) or type(err).__name__))
def open_download(url):
"""The final answer to a GET of url, its body not read: up to FETCH_REDIRECTS redirects followed
by hand, each to http or https and none of their bodies read (requests reads them); the file
asked uncompressed. Refused unless it is a 200 of an uncompressed body."""
http = urllib3.PoolManager(timeout=FETCH_TIMEOUT, retries=False)
for _hop in range(FETCH_REDIRECTS + 1):
if url_scheme(url) not in ("http", "https"):
raise util.OperationError(BAD_ADDRESS)
try:
answer = http.request("GET", url, headers={"Accept-Encoding": "identity"}, preload_content=False,
redirect=False, decode_content=False)
except urllib3.exceptions.HTTPError as err:
raise _download_error(err) from None
location = answer.headers.get("Location")
if answer.status in (301, 302, 303, 307, 308) and location:
answer.close()
try:
url = urljoin(url, location)
except ValueError: # a Location it cannot read
raise util.OperationError(BAD_ADDRESS) from None
continue
if answer.status != 200 or answer.headers.get("Content-Encoding", "identity") != "identity":
answer.close()
raise util.OperationError(gettext_noop("The server answered %(status)s, not the whole file"),
status=f"{answer.status} {answer.reason or ''}".strip())
return answer
raise util.OperationError(gettext_noop("The address is redirected more than %(count)s times"), count=FETCH_REDIRECTS)
@register
class FetchVolume(Kind):
"""A volume of a pool of files made from a file at a URL (an ISO or a disk image), streamed by
the worker into the pool through libvirt; the server must tell the file's size. A cancel or a
failure deletes what it wrote."""
name = "volume.fetch"
label = gettext_noop("Download volume")
cancellable = True
progress_bytes = True
def normalize(self, raw):
url = str(raw["url"]).strip()
return {"compute": int(raw["compute"]), "pool": str(raw["pool"]), "url": url,
"name": str(raw.get("name") or "").strip() or url_file_name(url)}
def validate(self, user, params):
if not user.is_superuser:
raise PermissionDenied
if url_scheme(params["url"]) not in ("http", "https"):
raise util.OperationError(BAD_ADDRESS)
if not VOLUME_NAME.fullmatch(params["name"]) or params["name"] in (".", ".."):
raise util.OperationError(gettext_noop("A volume's name is letters, digits, '.', '_' and '-'"))
def plan(self, user, params):
compute, stg = _storage(params)
if stg.get_type() not in FILE_POOL_TYPES:
raise util.OperationError(gettext_noop("Files are downloaded into a pool of files (dir, fs, netfs)"))
with contextlib.suppress(libvirtError): # refused while a volume is cloned in the pool
stg.refresh()
if params["name"] in stg.get_volumes():
raise util.OperationError(gettext_noop("The pool has a volume named %(name)s"), name=params["name"])
pool = claims.pool_key(compute.pk, params["pool"])
return Plan(claims={claims.compute_key(compute.pk): Claim.SHARED, pool: Claim.SHARED,
claims.volume_key(compute.pk, params["pool"], params["name"]): Claim.EXCLUSIVE},
resource=pool, label=f"{compute.name}/{params['pool']}", intent={"created": False})
def precheck(self, op, ctx):
if op.user is None or not op.user.is_active:
raise PermissionDenied
self.validate(op.user, op.params)
@staticmethod
def _stop_if_cancelled(op):
op.refresh_from_db(fields=["cancel_requested"])
if op.cancel_requested:
raise Cancelled
def run(self, op, ctx):
_compute, stg = _storage(op.params)
name = op.params["name"]
self._stop_if_cancelled(op)
with contextlib.closing(open_download(op.params["url"])) as answer:
size = answer.headers.get("Content-Length", "").strip(" \t")
if not size.isdigit():
raise util.OperationError(gettext_noop("The server does not tell the file's size"))
size = int(size)
if size > stg.get_size()[1]:
raise util.OperationError(gettext_noop("The file is larger than the pool's free space"))
# the volume is this job's from before it exists: a crash while libvirt makes it leaves it to recovery
ctx.record_intent(created=True, done=0, total=size)
try:
stg.new_raw_volume(name, size)
except BaseException: # a name taken meanwhile: libvirt refused, nothing of another's is deleted
ctx.record_intent(created=False)
raise
def chunks():
done, recorded, checked = 0, 0, time.monotonic()
try:
for data in answer.stream(2**20, decode_content=False):
done += len(data)
if done > size:
raise util.OperationError(gettext_noop("The server sent more than the file's size"))
if time.monotonic() - checked >= 1:
self._stop_if_cancelled(op)
checked = time.monotonic()
if done - recorded >= FETCH_PROGRESS_EVERY:
ctx.record_intent(done=done)
recorded = done
yield data
except urllib3.exceptions.HTTPError as err: # the connection lost, a read timeout
raise _download_error(err) from None
try:
if stg.write_volume(name, size, chunks()) != size:
raise util.OperationError(gettext_noop("The download ended early"))
self._stop_if_cancelled(op) # asked during its last second
except BaseException as err:
try:
stg.delete_volume_if_present(name)
except Exception: # recovery deletes it: a cancel that left the volume is not told done
raise util.OperationError(gettext_noop("The download stopped and its volume was not deleted")) from err
raise
ctx.record_intent(done=size)
with contextlib.suppress(libvirtError): # libvirt reads the file's format (qcow2, ...) again
stg.refresh()
return {}
def progress(self, op):
return (op.intent["done"], op.intent["total"]) if "total" in op.intent else None
def cancel(self, op):
"""run sees the cancel within a second, between two reads."""
def reconcile(self, op):
if op.intent.get("created"):
_compute, stg = _storage(op.params)
stg.delete_volume_if_present(op.params["name"])
return Outcome(Operation.FAILED, error=utils.say(gettext_noop("The download stopped; what it wrote was deleted")))
def log_entry(self, op, state):
# the address's host only: a signed address's query would show in the log
return _log(op, state, f"download volume {op.params['name']} from {urlsplit(op.params['url']).hostname}")

View file

@ -1,4 +1,5 @@
{% load i18n %}
{% load operations %}
{% load django_bootstrap5 %}
{% load bootstrap_icons %}
{% if request.user.is_superuser %}
@ -72,5 +73,39 @@
</div> <!-- /.modal-dialog -->
</div> <!-- /.modal -->
{% endif %}
{% if type == "dir" or type == "fs" or type == "netfs" %}
{# the worker downloads it into the pool; the job panel shows its progress #}
<button type="button" class="btn btn-outline-primary" data-bs-toggle="modal" data-bs-target="#FetchVolume">
<span aria-hidden="true">{% bs_icon 'download' %}</span> {% trans "Download from a URL" %}
</button>
<div class="modal fade" id="FetchVolume" tabindex="-1" aria-labelledby="FetchVolumeLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="FetchVolumeLabel">{% trans "Download from a URL" %}</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="{% trans "Close" %}"></button>
</div>
<form method="post" aria-labelledby="FetchVolumeLabel">{% csrf_token %}{% submission_key %}
<div class="modal-body">
<div class="mb-3">
<label class="form-label" for="fetch-url">{% trans "Address" %}</label>
<input type="url" class="form-control" name="url" id="fetch-url" required placeholder="https://" aria-describedby="fetch-url-help">
<div class="form-text" id="fetch-url-help">{% trans "An ISO or a disk image (qcow2, raw) at an http or https address that tells its size. The panel's host downloads it." %}</div>
</div>
<div>
<label class="form-label" for="fetch-name">{% trans "Volume name" %}</label>
<input type="text" class="form-control" name="name" id="fetch-name" pattern="[a-zA-Z0-9\.\-_]+" aria-describedby="fetch-name-help">
<div class="form-text" id="fetch-name-help">{% trans "Empty: the file's name in the address. An ISO keeps its .iso ending, or VMs do not list it as media." %}</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">{% trans "Cancel" %}</button>
<button type="submit" class="btn btn-primary" name="fetch_volume" value="1">{% trans "Download" %}</button>
</div>
</form>
</div>
</div>
</div>
{% endif %}
{% endif %}
{% endif %}

View file

@ -0,0 +1,240 @@
"""A volume made from a URL (an ISO or a disk image) by a job: the pool page
queues it, the worker streams the file into a new volume of the pool through
libvirt, telling its progress; a cancel or a failure deletes what it wrote."""
from types import SimpleNamespace
from unittest.mock import MagicMock, patch
from django.contrib.auth import get_user_model
from django.core.exceptions import PermissionDenied
from django.test import TestCase, TransactionTestCase
from django.urls import reverse
from computes.models import Compute
from operations.jobs import Cancelled, Context
from operations.models import Operation, acquire
from storages.jobs import FetchVolume, open_download
from vrtManager import util
from vrtManager.storage import wvmStorage
URL = "https://images.example.com/rocky-10.qcow2"
def answer(chunks, size=None, status=200, headers=None):
body = MagicMock(status=status, reason="OK")
body.headers = {"Content-Length": str(size if size is not None else sum(map(len, chunks))), **(headers or {})}
if size == -1:
del body.headers["Content-Length"]
body.stream.return_value = iter(chunks)
return body
class FetchJobTestCase(TransactionTestCase):
def setUp(self):
self.compute = Compute.objects.create(name="fe-c", hostname="192.0.2.21", login="root", password="", type=1)
self.client.force_login(get_user_model().objects.create_superuser("fe_admin", "f@example.com", "pw"))
patcher = patch("storages.jobs.wvmStorage")
self.stg = patcher.start().return_value
self.addCleanup(patcher.stop)
self.stg.get_volumes.return_value = []
self.stg.get_type.return_value = "dir"
self.stg.get_size.return_value = [10 * 2**30, 5 * 2**30]
self.stg.write_volume.side_effect = lambda name, size, chunks: sum(len(c) for c in chunks)
self.stg.new_raw_volume.return_value = None
page = patch("storages.views.wvmStorage").start().return_value # the pool page's own connection
page.is_active.return_value = False
page.get_size.return_value = (1, 1)
self.addCleanup(patch.stopall)
def queue(self, url=URL, name=""):
self.client.post(reverse("storage", args=[self.compute.pk, "images"]),
{"fetch_volume": "1", "url": url, "name": name, "submission_key": "key-fetch001"})
return Operation.objects.filter(kind="volume.fetch").first()
def run_job(self, op, chunks, size=None):
acquire("wvc-test:1:a", "wvc-test")
Operation.objects.filter(pk=op.pk).update(state=Operation.RUNNING, worker="wvc-test:1:a")
op.refresh_from_db()
ctx = Context(op, SimpleNamespace(identity="wvc-test:1:a"))
with patch("storages.jobs.open_download", return_value=answer(chunks, size)) as get:
FetchVolume().precheck(op, ctx)
result = FetchVolume().run(op, ctx)
self.assertEqual(get.call_args.args[0], URL)
return result
def test_the_page_queues_it_and_the_worker_streams_it(self):
op = self.queue()
self.assertEqual((op.params["url"], op.params["name"]), (URL, "rocky-10.qcow2")) # named by the URL
self.run_job(op, [b"ab", b"cd"])
self.stg.new_raw_volume.assert_called_once_with("rocky-10.qcow2", 4)
name, size, _chunks = self.stg.write_volume.call_args.args
self.assertEqual((name, size), ("rocky-10.qcow2", 4))
op.refresh_from_db()
self.assertEqual((op.intent["done"], op.intent["total"]), (4, 4))
def test_the_pool_page_offers_it_for_a_pool_of_files(self):
page = patch("storages.views.wvmStorage").start().return_value
page.is_active.return_value = True
page.get_size.return_value = (10, 4)
page.update_volumes.return_value = []
for kind, offered in (("dir", True), ("logical", False)):
with self.subTest(kind=kind):
page.get_type.return_value = kind
response = self.client.get(reverse("storage", args=[self.compute.pk, "images"]))
self.assertEqual('name="fetch_volume"' in response.content.decode(), offered)
def test_what_is_refused_when_asked(self):
for url, name, why in (("ftp://example.com/a.iso", "", "http"), (URL, "../x", "name"),
("https://example.com/", "", "name"), ("http://[::1/a.iso", "", "unreadable")):
with self.subTest(url=url, name=name):
Operation.objects.all().delete()
self.assertIsNone(self.queue(url, name), why)
self.stg.get_volumes.return_value = ["rocky-10.qcow2"] # taken
self.assertIsNone(self.queue())
self.stg.get_volumes.return_value = []
self.stg.get_type.return_value = "logical" # not a pool of files
self.assertIsNone(self.queue())
def test_a_file_without_a_size_or_too_big_is_refused_before_writing(self):
op = self.queue()
with self.assertRaisesRegex(util.OperationError, "does not tell the file's size"):
self.run_job(op, [b"ab"], size=-1)
with self.assertRaisesRegex(util.OperationError, "free"):
self.run_job(op, [b"ab"], size=6 * 2**30)
self.stg.write_volume.assert_not_called()
def test_an_address_that_fails_says_why(self):
op = self.queue()
acquire("wvc-test:1:a", "wvc-test")
Operation.objects.filter(pk=op.pk).update(state=Operation.RUNNING, worker="wvc-test:1:a")
op.refresh_from_db()
failing = util.OperationError("The server answered 404 Not Found, not the whole file")
with patch("storages.jobs.open_download", side_effect=failing), \
self.assertRaisesRegex(util.OperationError, "404 Not Found"):
FetchVolume().run(op, Context(op, SimpleNamespace(identity="wvc-test:1:a")))
self.stg.new_raw_volume.assert_not_called()
def test_a_name_taken_meanwhile_deletes_nothing(self):
# another made a volume of that name after the job was queued: libvirt refuses, it stays
op = self.queue()
self.stg.new_raw_volume.side_effect = util.OperationError("storage volume 'rocky-10.qcow2' exists already")
with self.assertRaises(util.OperationError):
self.run_job(op, [b"ab"])
op.refresh_from_db()
self.assertFalse(op.intent["created"])
self.stg.delete_volume_if_present.assert_not_called()
FetchVolume().reconcile(op)
self.stg.delete_volume_if_present.assert_not_called()
def test_a_size_with_spaces_after_it_is_read(self):
op = self.queue()
self.run_job(op, [b"abcd"], size="4 \t")
self.stg.new_raw_volume.assert_called_once_with("rocky-10.qcow2", 4)
def test_a_crash_while_libvirt_makes_the_volume_leaves_it_to_recovery(self):
op = self.queue()
recorded = []
self.stg.new_raw_volume.side_effect = lambda name, size: recorded.append(
Operation.objects.get(pk=op.pk).intent["created"])
self.run_job(op, [b"ab"])
self.assertEqual(recorded, [True])
def test_a_deactivated_superuser_s_job_does_not_run(self):
op = self.queue()
op.user.is_active = False
op.user.save()
op.refresh_from_db()
with self.assertRaises(PermissionDenied):
FetchVolume().precheck(op, None)
def test_more_than_the_size_told_is_not_written(self):
op = self.queue()
self.stg.write_volume.side_effect = lambda name, size, chunks: sum(len(c) for c in chunks)
with self.assertRaisesRegex(util.OperationError, "more than the file's size"):
self.run_job(op, [b"abcd", b"ef"], size=4)
self.stg.delete_volume_if_present.assert_called_once_with("rocky-10.qcow2")
def test_a_cancel_stops_it_and_recovery_deletes_what_it_wrote(self):
op = self.queue()
def write(name, size, chunks):
Operation.objects.filter(pk=op.pk).update(cancel_requested=True)
return sum(len(c) for c in chunks)
self.stg.write_volume.side_effect = write
with self.assertRaises(Cancelled):
self.run_job(op, [b"x" * 2**20] * 20)
self.stg.delete_volume_if_present.assert_called_once_with("rocky-10.qcow2")
# its delete failing: no "cancelled" while the volume may stay; recovery deletes it
self.stg.delete_volume_if_present.side_effect = OSError("connection lost")
Operation.objects.filter(pk=op.pk).update(cancel_requested=False)
with self.assertRaisesRegex(util.OperationError, "was not deleted"):
self.run_job(op, [b"x" * 2**20] * 20)
op.refresh_from_db()
self.assertTrue(op.intent["created"])
stg = MagicMock()
with patch("storages.jobs._storage", return_value=(self.compute, stg)):
self.assertEqual(FetchVolume().reconcile(op).state, Operation.FAILED)
stg.delete_volume_if_present.assert_called_once_with("rocky-10.qcow2")
class OpenDownloadTestCase(TestCase):
"""The request: redirects followed by hand without reading their bodies, a 200 of an uncompressed body only."""
def request(self, answers):
manager = MagicMock()
manager.request.side_effect = answers
return patch("storages.jobs.urllib3.PoolManager", return_value=manager), manager
def test_redirects_are_followed_without_reading_them(self):
moved = answer([], status=302, headers={"Location": "/mirror/a.iso"})
final = answer([b"ab"])
patcher, manager = self.request([moved, final])
with patcher:
self.assertIs(open_download("https://images.example.com/a.iso"), final)
self.assertEqual([c.args[1] for c in manager.request.call_args_list],
["https://images.example.com/a.iso", "https://images.example.com/mirror/a.iso"])
self.assertEqual(manager.request.call_args.kwargs["headers"], {"Accept-Encoding": "identity"})
moved.close.assert_called_once_with()
moved.read.assert_not_called()
def test_what_is_refused(self):
for answers, text in (
([answer([], status=302, headers={"Location": "file:///etc/passwd"})], "http or https"),
([answer([], status=302, headers={"Location": "http://[::1/a.iso"})], "http or https"),
([answer([], status=302, headers={"Location": "/again"})] * 7, "redirected more than 5 times"),
([answer([], status=206)], "answered 206"),
([answer([b"x"], headers={"Content-Encoding": "gzip"})], "not the whole file"),
):
with self.subTest(text=text):
patcher, _manager = self.request(answers)
with patcher, self.assertRaisesRegex(util.OperationError, text):
open_download("https://images.example.com/a.iso")
class WriteVolumeTestCase(TestCase):
def test_the_chunks_go_into_a_new_volume_through_one_stream(self):
stg = wvmStorage.__new__(wvmStorage)
stg.pool, stg.wvm = MagicMock(), MagicMock()
stream = stg.wvm.newStream.return_value
stream.send.side_effect = lambda data: len(data)
stg.new_raw_volume("a.iso", 4)
self.assertIn("<name>a.iso</name><capacity unit='bytes'>4</capacity>", stg.pool.createXML.call_args.args[0])
self.assertEqual(stg.write_volume("a.iso", 4, iter([b"ab", b"cd"])), 4)
stg.pool.storageVolLookupByName.return_value.upload.assert_called_once_with(stream, 0, 4, 0)
stream.finish.assert_called_once_with()
def test_a_failure_aborts_the_stream(self):
stg = wvmStorage.__new__(wvmStorage)
stg.pool, stg.wvm = MagicMock(), MagicMock()
stream = stg.wvm.newStream.return_value
def chunks():
yield b"ab"
raise OSError("connection reset")
stream.send.side_effect = lambda data: len(data)
with self.assertRaises(OSError):
stg.write_volume("a.iso", 4, chunks())
stream.abort.assert_called_once_with()
stream.finish.assert_not_called()

View file

@ -16,6 +16,7 @@ from libvirt import libvirtError
from operations import claims, jobs
from operations.utils import busy_message
from logs.audit import audit, failed
from webvirtcloud.middleware import error_text
from vrtManager.util import OperationError
from vrtManager.storage import wvmStorage, wvmStorages
@ -208,6 +209,18 @@ def storage(request, compute_id, pool):
if not state:
for msg_err in form.errors.values():
messages.error(request, msg_err.as_text())
if "fetch_volume" in request.POST:
raw = {"compute": compute.id, "pool": pool, "url": request.POST.get("url", ""),
"name": request.POST.get("name", "")}
try: # the job writes its row when it ends
op = jobs.submit("volume.fetch", request.user, raw, request.POST.get("submission_key", ""))
except claims.Busy as busy:
messages.error(request, busy_message(busy, request.user))
except (jobs.SubmissionConflict, OperationError, libvirtError) as err:
messages.error(request, error_text(request, err))
else:
jobs.remember_job(request, op)
return redirect(reverse("storage", args=[compute.id, pool]))
if "cln_volume" in request.POST:
form = CloneImage(request.POST)
if form.is_valid():

View file

@ -305,6 +305,38 @@ class wvmStorage(wvmConnect):
self.refresh()
return volume_details(self.get_volume(volname))
def new_raw_volume(self, name, size):
"""A new volume of name and size bytes to write (write_volume); libvirt refuses a name taken."""
self.pool.createXML(f"<volume><name>{util.xml_escape(name)}</name><capacity unit='bytes'>{int(size)}</capacity>"
"<target><format type='raw'/></target></volume>", 0)
def write_volume(self, name, size, chunks):
"""chunks (bytes, size of them in all) into the volume of name, from its start, through one
libvirt stream as an upload is written, whatever the connection; the bytes written. A
failure, or chunks raising, aborts the stream."""
stream = self.wvm.newStream(0)
written = 0
try:
self.pool.storageVolLookupByName(name).upload(stream, 0, size, 0)
for data in chunks:
while data:
sent = stream.send(data)
if sent <= 0:
raise OSError("the libvirt stream stopped")
written += sent
data = data[sent:]
stream.finish()
except BaseException:
stream.abort()
raise
return written
def delete_volume_if_present(self, name):
with contextlib.suppress(libvirt.libvirtError): # gone, or never made
self.pool.refresh(0)
if name in self.pool.listVolumes():
self.pool.storageVolLookupByName(name).delete(0)
def update_volumes(self):
"""Every volume's details (volume_details) by name, the pool refreshed
first: two calls and one per volume, where a lookup, info() and the