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

feat(storages): a volume downloads from its pool page

The volume menu of a pool page gets Download: the host reads the volume
with libvirt's download stream and the panel passes it on in chunks, so
a disk image never sits in the panel's memory. The file is the volume as
stored: a qcow2 volume comes as its qcow2 file. A volume a running VM
uses is refused, as for a copy; the refusal is a message on the pool
page. Each download is a row in the audit log.

gunicorn's worker exits when a request runs past its timeout (600 s), to
end requests stuck on a host. A download of a large disk runs longer, so
each chunk sent starts the request's timeout again: a download that stops
sending is still ended. nginx passes the chunks on as they come
(X-Accel-Buffering: no) instead of spooling them to a file.
This commit is contained in:
catborise 2026-11-15 00:31:42 +03:00
parent 44b6e42f8f
commit c9fef349d5
13 changed files with 239 additions and 52 deletions

View file

@ -37,7 +37,7 @@ WebVirtCloud and `virt-manager`/`virsh` can manage the same libvirt host **concu
* External snapshots (memory optional; without memory, guest file systems can be frozen through the agent)
* **External change detection:** VMs created, deleted or renamed via `virt-manager` or `virsh` are reconciled into the database automatically
* Real-time hypervisor and VM statistics (CPU, RAM, disk, network)
* Storage pool and volume management
* Storage pool and volume management; a volume downloads from its pool page (not one a running VM uses)
* Network (with DHCP leases), interface, network filter and secret management
* PCI and USB devices of the host given to VMs
* UEFI Secure Boot and TPM 2.0 for new VMs, as Windows 11 needs

View file

@ -6,7 +6,7 @@ from interfaces.views import interface, interfaces
from networks.views import network, networks
from nodedevs.views import nodedevs
from nwfilters.views import nwfilter, nwfilters
from storages.views import get_volumes, storage, storages
from storages.views import download_volume, get_volumes, storage, storages
from . import forms, views
@ -66,6 +66,7 @@ urlpatterns = [
path("storages/", storages, name="storages"),
path("storage/<str:pool>/volumes/", get_volumes, name="volumes"),
path("storage/<str:pool>/", storage, name="storage"),
path("storage/<str:pool>/download/<str:vol>", download_volume, name="download_volume"),
path("networks/", networks, name="networks"),
path("network/<str:pool>/", network, name="network"),
path("interfaces/", interfaces, name="interfaces"),

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-14 20:20+0000\n"
"POT-Creation-Date: 2026-11-14 21:31+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"
@ -314,7 +314,7 @@ msgstr "Burada oturumunuz açık kalır; diğer oturumlarınız kapanır."
#: 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/storage.html:201 templates/base.html:65
#: storages/templates/storage.html:202 templates/base.html:65
#: templates/common/confirm_delete.html:25 templates/common/form.html:27
#: virtsecrets/templates/create_secret_block.html:48
#: virtsecrets/templates/secrets.html:106
@ -463,7 +463,7 @@ msgstr "%(name)s API anahtarı için işlemler"
#: instances/templates/instances/settings_tab.html:315
#: instances/templates/instances/snapshots_tab.html:103
#: instances/templates/instances/snapshots_tab.html:117
#: networks/templates/network.html:168 storages/templates/storage.html:152
#: networks/templates/network.html:168 storages/templates/storage.html:153
#: templates/common/confirm_delete.html:5
#: templates/common/confirm_delete.html:9
#: templates/common/confirm_delete.html:26
@ -2702,7 +2702,7 @@ msgstr "Bağlan"
#: 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/storage.html:174 templates/base.html:61
#: storages/templates/storage.html:175 templates/base.html:61
#: virtsecrets/templates/create_secret_block.html:16
#: virtsecrets/templates/secrets.html:97
msgid "Close"
@ -3573,7 +3573,7 @@ msgstr "Depolama havuzu"
#: instances/templates/add_instance_volume.html:41
#: instances/templates/create_instance_w2.html:46 storages/forms.py:119
#: storages/templates/storage.html:182
#: storages/templates/storage.html:183
msgid "Letters, digits, dot, dash and underscore."
msgstr "Harf, rakam, nokta, tire ve alt çizgi."
@ -3584,14 +3584,14 @@ msgstr "Boyut"
#: instances/templates/add_instance_volume.html:51
#: instances/templates/instances/edit_instance_volume.html:82
#: storages/templates/storage.html:124 storages/templates/storage.html:189
#: storages/templates/storage.html:124 storages/templates/storage.html:190
msgid "Format"
msgstr "Biçem"
#: instances/templates/add_instance_volume.html:61
#: instances/templates/create_instance_w2.html:154
#: instances/templates/create_instance_w2.html:220 storages/forms.py:125
#: storages/forms.py:145 storages/templates/storage.html:197
#: storages/forms.py:145 storages/templates/storage.html:198
msgid "Preallocate metadata (qcow2)"
msgstr "Meta veriyi önceden ayır (qcow2)"
@ -4074,7 +4074,7 @@ msgstr "Ayrıntılar"
#: instances/templates/instances/settings_tab.html:882
#: instances/templates/instances/settings_tab.html:884
#: nwfilters/templates/nwfilters.html:57 nwfilters/templates/nwfilters.html:94
#: storages/templates/storage.html:143 storages/templates/storage.html:202
#: storages/templates/storage.html:143 storages/templates/storage.html:203
msgid "Clone"
msgstr "Klonla"
@ -8093,7 +8093,7 @@ msgstr "Aramayla eşleşen filtre yok."
msgid "Clone filter"
msgstr "Filtreyi klonla"
#: nwfilters/templates/nwfilters.html:88 storages/templates/storage.html:180
#: nwfilters/templates/nwfilters.html:88 storages/templates/storage.html:181
msgid "Name of the copy"
msgstr "Kopyanın adı"
@ -8832,7 +8832,11 @@ msgstr "Birimlerde ara"
msgid "%(allocated)s allocated"
msgstr "%(allocated)s ayrılmış"
#: storages/templates/storage.html:152
#: storages/templates/storage.html:149
msgid "Download"
msgstr "İndir"
#: storages/templates/storage.html:153
#, python-format
msgid ""
"Delete volume %(name)s? Its file and data are removed; a volume a VM uses is "
@ -8841,27 +8845,27 @@ msgstr ""
"%(name)s birimi silinsin mi? Dosyası ve verisi kaldırılır; bir sanal "
"makinenin kullandığı birim silinmez."
#: storages/templates/storage.html:165
#: storages/templates/storage.html:166
msgid "No volume matches the search."
msgstr "Aramayla eşleşen birim yok."
#: storages/templates/storage.html:173
#: storages/templates/storage.html:174
msgid "Clone image"
msgstr "İmaj Klonla"
#: storages/templates/storage.html:186
#: storages/templates/storage.html:187
msgid "Convert it to another format"
msgstr "Başka bir biçime dönüştür"
#: storages/templates/storage.html:191
#: storages/templates/storage.html:192
msgid "raw"
msgstr "raw"
#: storages/templates/storage.html:192
#: storages/templates/storage.html:193
msgid "qcow2"
msgstr "qcow2"
#: storages/templates/storage.html:209
#: storages/templates/storage.html:210
msgid "This pool has no volumes."
msgstr "Bu havuzda birim yok."
@ -8965,36 +8969,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:30
#: storages/views.py:32
msgid "No file chunk was submitted."
msgstr "Dosya parçası gönderilmedi."
#: storages/views.py:36
#: storages/views.py:38
msgid "Invalid chunk parameters."
msgstr "Geçersiz parça parametreleri."
#: storages/views.py:38
#: storages/views.py:40
msgid "Invalid chunk index or total chunks."
msgstr "Geçersiz parça dizini veya toplam parça sayısı."
#: storages/views.py:43
#: storages/views.py:45
msgid "Invalid file size."
msgstr "Geçersiz dosya boyutu."
#: storages/views.py:52
#: storages/views.py:54
msgid "Upload session is busy. Please retry."
msgstr "Yükleme oturumu meşgul. Lütfen yeniden deneyin."
#: storages/views.py:54
#: storages/views.py:56
msgid "ISO image already exists"
msgstr "ISO imajı zaten mevcut"
#: storages/views.py:182
#: storages/views.py:184
#, python-format
msgid "Volume: %(vol)s is deleted."
msgstr "Birim: %(vol)s silindi."
#: storages/views.py:199
#: storages/views.py:201
#, python-format
msgid "Image file %(name)s is created successfully"
msgstr "İmaj dosyası %(name)s başarıyla oluşturuldu"

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-14 20:20+0000\n"
"POT-Creation-Date: 2026-11-14 21:31+0000\n"
"PO-Revision-Date: \n"
"Last-Translator: \n"
"Language-Team: \n"
@ -309,7 +309,7 @@ msgstr "您在此处保持登录;您的其他会话将结束。"
#: 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/storage.html:201 templates/base.html:65
#: storages/templates/storage.html:202 templates/base.html:65
#: templates/common/confirm_delete.html:25 templates/common/form.html:27
#: virtsecrets/templates/create_secret_block.html:48
#: virtsecrets/templates/secrets.html:106
@ -456,7 +456,7 @@ msgstr "API 令牌 %(name)s 的操作"
#: instances/templates/instances/settings_tab.html:315
#: instances/templates/instances/snapshots_tab.html:103
#: instances/templates/instances/snapshots_tab.html:117
#: networks/templates/network.html:168 storages/templates/storage.html:152
#: networks/templates/network.html:168 storages/templates/storage.html:153
#: templates/common/confirm_delete.html:5
#: templates/common/confirm_delete.html:9
#: templates/common/confirm_delete.html:26
@ -2605,7 +2605,7 @@ msgstr "连接"
#: 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/storage.html:174 templates/base.html:61
#: storages/templates/storage.html:175 templates/base.html:61
#: virtsecrets/templates/create_secret_block.html:16
#: virtsecrets/templates/secrets.html:97
msgid "Close"
@ -3413,7 +3413,7 @@ msgstr "存储池"
#: instances/templates/add_instance_volume.html:41
#: instances/templates/create_instance_w2.html:46 storages/forms.py:119
#: storages/templates/storage.html:182
#: storages/templates/storage.html:183
msgid "Letters, digits, dot, dash and underscore."
msgstr "字母、数字、点、短横线和下划线。"
@ -3424,14 +3424,14 @@ msgstr "大小"
#: instances/templates/add_instance_volume.html:51
#: instances/templates/instances/edit_instance_volume.html:82
#: storages/templates/storage.html:124 storages/templates/storage.html:189
#: storages/templates/storage.html:124 storages/templates/storage.html:190
msgid "Format"
msgstr "格式"
#: instances/templates/add_instance_volume.html:61
#: instances/templates/create_instance_w2.html:154
#: instances/templates/create_instance_w2.html:220 storages/forms.py:125
#: storages/forms.py:145 storages/templates/storage.html:197
#: storages/forms.py:145 storages/templates/storage.html:198
msgid "Preallocate metadata (qcow2)"
msgstr "预分配元数据(qcow2)"
@ -3900,7 +3900,7 @@ msgstr "详情"
#: instances/templates/instances/settings_tab.html:882
#: instances/templates/instances/settings_tab.html:884
#: nwfilters/templates/nwfilters.html:57 nwfilters/templates/nwfilters.html:94
#: storages/templates/storage.html:143 storages/templates/storage.html:202
#: storages/templates/storage.html:143 storages/templates/storage.html:203
msgid "Clone"
msgstr "克隆"
@ -7639,7 +7639,7 @@ msgstr "没有与搜索匹配的过滤器。"
msgid "Clone filter"
msgstr "克隆过滤器"
#: nwfilters/templates/nwfilters.html:88 storages/templates/storage.html:180
#: nwfilters/templates/nwfilters.html:88 storages/templates/storage.html:181
msgid "Name of the copy"
msgstr "副本名称"
@ -8343,34 +8343,38 @@ msgstr "搜索卷"
msgid "%(allocated)s allocated"
msgstr "已分配 %(allocated)s"
#: storages/templates/storage.html:152
#: storages/templates/storage.html:149
msgid "Download"
msgstr "下载"
#: storages/templates/storage.html:153
#, python-format
msgid ""
"Delete volume %(name)s? Its file and data are removed; a volume a VM uses is "
"not deleted."
msgstr "删除卷 %(name)s?其文件和数据将被删除;虚拟机正在使用的卷不会被删除。"
#: storages/templates/storage.html:165
#: storages/templates/storage.html:166
msgid "No volume matches the search."
msgstr "没有与搜索匹配的卷。"
#: storages/templates/storage.html:173
#: storages/templates/storage.html:174
msgid "Clone image"
msgstr "克隆镜像"
#: storages/templates/storage.html:186
#: storages/templates/storage.html:187
msgid "Convert it to another format"
msgstr "转换为其他格式"
#: storages/templates/storage.html:191
#: storages/templates/storage.html:192
msgid "raw"
msgstr "raw"
#: storages/templates/storage.html:192
#: storages/templates/storage.html:193
msgid "qcow2"
msgstr "qcow2"
#: storages/templates/storage.html:209
#: storages/templates/storage.html:210
msgid "This pool has no volumes."
msgstr "此存储池中没有卷。"
@ -8473,36 +8477,36 @@ msgstr "最后一个分块与声明的文件大小不符"
msgid "The partial upload is missing"
msgstr "部分上传的文件不存在"
#: storages/views.py:30
#: storages/views.py:32
msgid "No file chunk was submitted."
msgstr "未提交文件分块。"
#: storages/views.py:36
#: storages/views.py:38
msgid "Invalid chunk parameters."
msgstr "分块参数无效。"
#: storages/views.py:38
#: storages/views.py:40
msgid "Invalid chunk index or total chunks."
msgstr "分块索引或分块总数无效。"
#: storages/views.py:43
#: storages/views.py:45
msgid "Invalid file size."
msgstr "文件大小无效。"
#: storages/views.py:52
#: storages/views.py:54
msgid "Upload session is busy. Please retry."
msgstr "上传会话繁忙,请重试。"
#: storages/views.py:54
#: storages/views.py:56
msgid "ISO image already exists"
msgstr "ISO 镜像已存在"
#: storages/views.py:182
#: storages/views.py:184
#, python-format
msgid "Volume: %(vol)s is deleted."
msgstr "卷 %(vol)s 已删除。"
#: storages/views.py:199
#: storages/views.py:201
#, python-format
msgid "Image file %(name)s is created successfully"
msgstr "镜像文件 %(name)s 创建成功"

View file

@ -146,6 +146,7 @@
<button type="button" class="btn btn-sm btn-outline-secondary" data-bs-toggle="dropdown" aria-expanded="false"
data-bs-popper-config='{"strategy": "fixed"}' aria-label="{% trans "More actions" %}">{% bs_icon 'three-dots' %}</button>
<ul class="dropdown-menu dropdown-menu-end shadow">
<li><a class="dropdown-item" href="{% url 'download_volume' compute.id pool volume.name %}">{% bs_icon 'download' %} {% trans "Download" %}</a></li>
<li><form method="post">{% csrf_token %}
<input type="hidden" name="volname" value="{{ volume.name }}">
<button type="submit" class="dropdown-item text-danger" name="del_volume"

View file

@ -0,0 +1,44 @@
"""A volume download streams what the host reads, as a file; a refusal is a
message on the storage page; only a superuser downloads."""
from unittest.mock import patch
from django.contrib.auth import get_user_model
from django.contrib.messages import get_messages
from django.test import TestCase
from django.urls import reverse
from computes.models import Compute
from vrtManager.util import OperationError
class DownloadTestCase(TestCase):
def setUp(self):
self.compute = Compute.objects.create(name="dl", hostname="192.0.2.30", login="root", password="", type=1)
self.url = reverse("download_volume", args=[self.compute.id, "pool-a", "disk.qcow2"])
patcher = patch("storages.views.wvmStorage")
self.stg = patcher.start().return_value
self.addCleanup(patcher.stop)
self.client.force_login(get_user_model().objects.create_superuser("dl_admin", "a@example.com", "pw"))
def test_the_volume_comes_as_a_file(self):
self.stg.read_volume.return_value = (3, iter([b"ab", b"c"]))
with patch("storages.views.request_progressed") as progressed:
response = self.client.get(self.url)
self.assertEqual(b"".join(response.streaming_content), b"abc")
self.assertEqual(progressed.call_count, 2)
self.assertEqual((response["Content-Length"], response["Content-Disposition"], response["X-Accel-Buffering"]),
("3", 'attachment; filename="disk.qcow2"', "no"))
self.stg.read_volume.assert_called_once_with("disk.qcow2")
def test_a_refusal_is_a_message_on_the_storage_page(self):
self.stg.read_volume.side_effect = OperationError("The running VMs %(vms)s use volume %(name)s; shut them down to copy it",
vms="vm1", name="disk.qcow2")
response = self.client.get(self.url)
self.assertRedirects(response, reverse("storage", args=[self.compute.id, "pool-a"]), fetch_redirect_response=False)
self.assertIn("shut them down", str(list(get_messages(response.wsgi_request))[0]))
def test_only_a_superuser_downloads(self):
self.client.force_login(get_user_model().objects.create_user("dl_user", password="pw"))
self.assertNotEqual(self.client.get(self.url).status_code, 200)
self.stg.read_volume.assert_not_called()

View file

@ -0,0 +1,62 @@
"""Live check of a volume download from the storage page: the bytes are the
volume file's, and a volume a running VM uses is refused. Runs only with
TEST_LIBVIRT_HOST set."""
import os
import unittest
from computes.models import Compute
from django.contrib.auth import get_user_model
from django.contrib.messages import get_messages
from django.test import TestCase
from django.urls import reverse
from vrtManager.connection import connection_manager
from vrtManager.tests import livetest
P = livetest.PREFIX
@unittest.skipUnless(livetest.enabled(), "Set TEST_LIBVIRT_HOST to run the live libvirt tests")
class LiveDownloadTestCase(TestCase):
def setUp(self):
args = dict(
hostname=os.environ["TEST_LIBVIRT_HOST"],
login=os.environ.get("TEST_LIBVIRT_LOGIN", ""),
password=os.environ.get("TEST_LIBVIRT_PASSWORD", ""),
type=int(os.environ.get("TEST_LIBVIRT_TYPE", 1)),
)
self.conn = connection_manager.get_connection(*args.values())
livetest.ensure_pool(self.conn)
self.addCleanup(livetest.cleanup, self.conn)
self.compute = Compute.objects.create(name="live-download", **args)
self.client.force_login(get_user_model().objects.create_superuser("live-dl", "ld@example.com", "x"))
def download(self, name):
return self.client.get(reverse("download_volume", args=[self.compute.id, livetest.POOL, name]))
def test_the_download_is_the_volume_file(self):
vol = self.conn.storageVolLookupByPath(livetest.create_volume(self.conn, P + "dl", 1, "raw"))
data = os.urandom(1 << 20)
stream = self.conn.newStream(0)
vol.upload(stream, 0, len(data), 0)
stream.send(data)
stream.finish()
response = self.download(P + "dl.raw")
self.assertEqual(response["Content-Length"], str(len(data)))
self.assertEqual(response["Content-Disposition"], f'attachment; filename="{P}dl.raw"')
self.assertEqual(b"".join(response.streaming_content), data)
def test_a_qcow2_volume_comes_as_its_file(self):
vol = self.conn.storageVolLookupByPath(livetest.create_volume(self.conn, P + "dl", 64, "qcow2"))
content = b"".join(self.download(P + "dl.qcow2").streaming_content)
self.assertEqual(content[:4], b"QFI\xfb")
self.assertEqual(len(content), vol.infoFlags(1)[2]) # the file, not the 64 MiB the guest sees
def test_a_running_vm_s_volume_is_refused(self):
path = livetest.create_volume(self.conn, P + "dl", 64, "qcow2")
livetest.define_vm(self.conn, P + "dl-vm", [path]).create()
response = self.download(P + "dl.qcow2")
self.assertRedirects(response, reverse("storage", args=[self.compute.id, livetest.POOL]),
fetch_redirect_response=False)
self.assertIn("shut them down", str(list(get_messages(response.wsgi_request))[0]))

View file

@ -7,9 +7,10 @@ from computes.models import Compute
from computes.utils import libvirt_compute_lock
from instances.utils import paths_used_on_other_computes
from django.contrib import messages
from django.http import HttpResponseRedirect, JsonResponse
from django.http import HttpResponseRedirect, JsonResponse, StreamingHttpResponse
from django.shortcuts import get_object_or_404, redirect, render
from django.urls import reverse
from django.utils.http import content_disposition_header
from django.utils.translation import gettext_lazy as _
from libvirt import libvirtError
from operations import claims, jobs
@ -22,6 +23,7 @@ from vrtManager.storage import wvmStorage, wvmStorages
from storages.forms import AddStgPool, CloneImage, CreateVolumeForm
from storages.jobs import is_iso
from storages.upload import write_chunk
from webvirtcloud.gunicorn_worker import request_progressed
def _handle_iso_upload(request, conn, compute, pool):
@ -279,3 +281,27 @@ def get_volumes(request, compute_id, pool):
# caller cannot tell "no volumes" from "could not read the pool"
return JsonResponse({"error": str(err)}, status=400)
return JsonResponse(data)
@superuser_only
def download_volume(request, compute_id, pool, vol):
"""Volume vol of the pool as a file, streamed from the host."""
compute = get_object_or_404(Compute, pk=compute_id)
try:
with audit(request, compute, f"Storage pool {pool}", f"download volume {vol}"):
conn = wvmStorage(compute.hostname, compute.login, compute.password, compute.type, pool)
size, chunks = conn.read_volume(vol)
except libvirtError as err: # a running VM's disk, no such volume, the host does not answer
messages.error(request, str(err))
return redirect(reverse("storage", args=[compute_id, pool]))
def sent():
for data in chunks:
yield data
request_progressed()
response = StreamingHttpResponse(sent(), content_type="application/octet-stream")
response["Content-Length"] = size
response["Content-Disposition"] = content_disposition_header(True, vol)
response["X-Accel-Buffering"] = "no" # nginx passes it on as it comes, not through a temporary file
return response

View file

@ -375,6 +375,27 @@ class wvmStorage(wvmConnect):
raise util.OperationError(gettext_noop("The running VMs %(vms)s use volume %(name)s; shut them down to copy it"),
vms=", ".join(vms), name=name)
def read_volume(self, name):
"""The size of volume name and its bytes, read in chunks: a running
guest's volume is refused, as for a copy."""
self.refuse_running_copy(name)
vol = self.get_volume(name)
size = vol.infoFlags(libvirt.VIR_STORAGE_VOL_GET_PHYSICAL)[2] # a file's length, not its capacity
stream = self.wvm.newStream(0)
vol.download(stream, 0, 0, 0)
def chunks():
try:
while data := stream.recv(1 << 20):
yield data
stream.finish()
except BaseException: # also a download the browser left (GeneratorExit)
with contextlib.suppress(libvirt.libvirtError):
stream.abort()
raise
return size, chunks()
def clone_volume(self, vol, target_file, vol_fmt=None, metadata=False, mode="0644", disk_owner_uid=0, disk_owner_gid=0):
"""A copy named target_file in this pool of vol, a volume of this pool
or another; its path. clone_name gives a dir pool's name its suffix."""

View file

@ -7,6 +7,18 @@ import time
from gunicorn.workers.gthread import ThreadWorker
_worker = None # this process's worker; None outside gunicorn
def request_progressed():
"""The calling request is still sending, not stuck: its timeout starts
again (a download streams for longer than the timeout)."""
if _worker is not None:
with _worker.started_lock:
if threading.get_ident() in _worker.started:
_worker.started[threading.get_ident()] = time.monotonic()
class Worker(ThreadWorker):
"""gunicorn kills a sync worker whose request runs past its timeout; a
threaded worker keeps reporting in while one of its threads waits on a
@ -18,6 +30,8 @@ class Worker(ThreadWorker):
super().__init__(*args, **kwargs)
self.started = {} # thread: when its request started
self.started_lock = threading.Lock()
global _worker
_worker = self
def handle(self, conn):
thread = threading.get_ident()

View file

@ -8,7 +8,7 @@ from unittest.mock import MagicMock, patch
from gunicorn.workers.gthread import ThreadWorker
from webvirtcloud.gunicorn_worker import Worker
from webvirtcloud.gunicorn_worker import Worker, request_progressed
def worker():
@ -42,6 +42,16 @@ class WorkerTestCase(unittest.TestCase):
notify.assert_called_once_with()
exit_.assert_not_called()
def test_a_request_that_still_sends_is_timed_from_its_last_progress(self):
w = worker()
w.started[threading.get_ident()] = time.monotonic() - 601
with patch("webvirtcloud.gunicorn_worker._worker", w):
request_progressed()
with patch.object(ThreadWorker, "notify") as notify, patch("os._exit") as exit_:
w.notify()
notify.assert_called_once_with()
exit_.assert_not_called()
def test_the_worker_exits_when_a_request_runs_past_the_timeout(self):
w = worker()
w.started.update({1: time.monotonic(), 2: time.monotonic() - 601})