diff --git a/accounts/templates/profile.html b/accounts/templates/profile.html index dcf23106..e26fd231 100644 --- a/accounts/templates/profile.html +++ b/accounts/templates/profile.html @@ -20,7 +20,7 @@ {% trans "Template editor" %} {% endif %} -
{{ user.username }}
+ {% if user.get_full_name %}
{{ user.username }}
{% endif %} {% if user.email %}
{{ user.email }}
{% endif %}
{% trans "Last login" %} {{ user.last_login|date:"Y-m-d H:i"|default:_("never") }}
diff --git a/computes/templates/computes/balance.html b/computes/templates/computes/balance.html index 90f92e41..7afb6e99 100644 --- a/computes/templates/computes/balance.html +++ b/computes/templates/computes/balance.html @@ -1,5 +1,6 @@ {% extends "base.html" %} {% load i18n %} +{% load common_tags %} {% load static %} {% load operations %} {% load bootstrap_icons %} @@ -28,14 +29,14 @@
{{ host.name }} - {% widthratio host.size.0 1 1024 as bytes %}{{ bytes|filesizeformat }}
+ {% widthratio host.size.0 1 1024 as bytes %}{{ bytes|binary_size }}
{% for bar in host.bars %}{% if forloop.first or moves %} {% if forloop.first %}{% with memory=host.before.0 vcpus=host.before.1 %}
{% if moves %}{% trans "Now" %}{% else %}{% trans "Running VMs" %}{% endif %} - {% widthratio memory 1 1024 as bytes %}{{ bytes|filesizeformat }}, {% blocktrans count counter=vcpus %}{{ counter }} vCPU{% plural %}{{ counter }} vCPUs{% endblocktrans %} {% blocktrans count counter=host.size.1 %}on {{ counter }} CPU{% plural %}on {{ counter }} CPUs{% endblocktrans %}
+ {% widthratio memory 1 1024 as bytes %}{{ bytes|binary_size }}, {% blocktrans count counter=vcpus %}{{ counter }} vCPU{% plural %}{{ counter }} vCPUs{% endblocktrans %} {% blocktrans count counter=host.size.1 %}on {{ counter }} CPU{% plural %}on {{ counter }} CPUs{% endblocktrans %}
{% endwith %}{% else %}{% with memory=host.after.0 vcpus=host.after.1 %}
{% trans "After" %} - {% widthratio memory 1 1024 as bytes %}{{ bytes|filesizeformat }}, {% blocktrans count counter=vcpus %}{{ counter }} vCPU{% plural %}{{ counter }} vCPUs{% endblocktrans %} {% blocktrans count counter=host.size.1 %}on {{ counter }} CPU{% plural %}on {{ counter }} CPUs{% endblocktrans %}
+ {% widthratio memory 1 1024 as bytes %}{{ bytes|binary_size }}, {% blocktrans count counter=vcpus %}{{ counter }} vCPU{% plural %}{{ counter }} vCPUs{% endblocktrans %} {% blocktrans count counter=host.size.1 %}on {{ counter }} CPU{% plural %}on {{ counter }} CPUs{% endblocktrans %}
{% endwith %}{% endif %}
@@ -74,7 +75,7 @@ - {% widthratio instance.info.2 1 1024 as bytes %}{{ bytes|filesizeformat }} + {% widthratio instance.info.2 1 1024 as bytes %}{{ bytes|binary_size }} {{ instance.info.3 }} {{ instance.compute.name }} {% bs_icon 'arrow-right' %} {{ instance.target.name }} diff --git a/computes/templates/computes/bulk_migrate.html b/computes/templates/computes/bulk_migrate.html index b4985d4f..438b6085 100644 --- a/computes/templates/computes/bulk_migrate.html +++ b/computes/templates/computes/bulk_migrate.html @@ -1,5 +1,6 @@ {% extends "base.html" %} {% load i18n %} +{% load common_tags %} {% load static %} {% load operations %} {% load bootstrap_icons %} @@ -91,7 +92,7 @@ {% include 'instance_state.html' %} - {% if instance.info %}{% widthratio instance.info.2 1 1024 as bytes %}{{ bytes|filesizeformat }}{% endif %} + {% if instance.info %}{% widthratio instance.info.2 1 1024 as bytes %}{{ bytes|binary_size }}{% endif %} {{ instance.info.3 }} {% if spreading %}{{ instance.target.name|default:"" }}{% endif %} {{ instance.refusal|default:"" }}{{ instance.note|default:"" }} diff --git a/computes/templates/computes/capacity_line.txt b/computes/templates/computes/capacity_line.txt index 06a794be..6000c0be 100644 --- a/computes/templates/computes/capacity_line.txt +++ b/computes/templates/computes/capacity_line.txt @@ -1,5 +1,5 @@ -{% load i18n %}{% autoescape off %}{% if given %} -{% blocktrans count counter=given.vcpus.all with ratio=given.ratio|floatformat:1 assigned=given.assigned.all|filesizeformat %}Given to VMs: {{ counter }} vCPU ({{ ratio }}:1), {{ assigned }} memory.{% plural %}Given to VMs: {{ counter }} vCPUs ({{ ratio }}:1), {{ assigned }} memory.{% endblocktrans %} +{% load i18n common_tags %}{% autoescape off %}{% if given %} +{% blocktrans count counter=given.vcpus.all with ratio=given.ratio|floatformat:1 assigned=given.assigned.all|binary_size %}Given to VMs: {{ counter }} vCPU ({{ ratio }}:1), {{ assigned }} memory.{% plural %}Given to VMs: {{ counter }} vCPUs ({{ ratio }}:1), {{ assigned }} memory.{% endblocktrans %} {% else %} {% trans "The capacity could not be read." %} {% endif %}{% endautoescape %} diff --git a/computes/templates/computes/capacity_memory.html b/computes/templates/computes/capacity_memory.html index 98b57839..cec4f448 100644 --- a/computes/templates/computes/capacity_memory.html +++ b/computes/templates/computes/capacity_memory.html @@ -1,18 +1,19 @@ {% load i18n %} +{% load common_tags %} {# the memory a host has given its VMs: given, from views.shown_capacity #} -
{{ given.memory_percent }} %
-
{{ given.assigned.all|filesizeformat }} / {{ given.memory|filesizeformat }}
+
{{ given.memory_percent|percent }}
+
{{ given.assigned.all|binary_size }} / {{ given.memory|binary_size }}
{# running VMs' memory, then shut-off VMs', on a scale that holds the host's memory or all given, whichever is larger #}
+ aria-valuetext="{% blocktrans with running=given.assigned.running|binary_size memory=given.memory|binary_size %}{{ running }} of the host's {{ memory }}{% endblocktrans %}">
+ aria-valuetext="{% blocktrans with stopped=given.assigned.stopped|binary_size memory=given.memory|binary_size %}{{ stopped }} of the host's {{ memory }}{% endblocktrans %}">
-
{% blocktrans with running=given.assigned.running|filesizeformat %}{{ running }} in running VMs{% endblocktrans %}
+
{% blocktrans with running=given.assigned.running|binary_size %}{{ running }} in running VMs{% endblocktrans %}
diff --git a/computes/templates/computes/list.html b/computes/templates/computes/list.html index 445d41b1..32990905 100644 --- a/computes/templates/computes/list.html +++ b/computes/templates/computes/list.html @@ -1,5 +1,6 @@ {% extends "base.html" %} {% load i18n %} +{% load common_tags %} {% load static %} {% load bootstrap_icons %} {% load operations %} @@ -42,8 +43,8 @@
{% bs_icon 'memory' %} {% trans "Memory given" %}
-
{{ totals.assigned|filesizeformat }}
-
{% blocktrans with memory=totals.memory|filesizeformat %}of {{ memory }}{% endblocktrans %}
+
{{ totals.assigned|binary_size }}
+
{% blocktrans with memory=totals.memory|binary_size %}of {{ memory }}{% endblocktrans %}
diff --git a/computes/templates/computes/pool_bar.html b/computes/templates/computes/pool_bar.html index 1f63458e..5576972d 100644 --- a/computes/templates/computes/pool_bar.html +++ b/computes/templates/computes/pool_bar.html @@ -1,8 +1,9 @@ {% load i18n %} +{% load common_tags %} {# a pool's space; hide_name: the page names the pool next to it #} {% if not hide_name %}
{{ pool.name }}
{% endif %}
-
{% blocktrans with free=pool.free|filesizeformat size=pool.size|filesizeformat %}{{ free }} free of {{ size }}{% endblocktrans %}
+
{% blocktrans with free=pool.free|binary_size size=pool.size|binary_size %}{{ free }} free of {{ size }}{% endblocktrans %}
diff --git a/computes/templates/overview.html b/computes/templates/overview.html index 15223b0e..5c520e5a 100644 --- a/computes/templates/overview.html +++ b/computes/templates/overview.html @@ -1,5 +1,6 @@ {% extends "base.html" %} {% load i18n %} +{% load common_tags %} {% load static %} {% load bootstrap_icons %} {% load operations %} @@ -192,7 +193,7 @@
  • {% trans "Memory" %} - {{ host.memory|filesizeformat }} + {{ host.memory|binary_size }}
  • diff --git a/computes/tests/test_capacity.py b/computes/tests/test_capacity.py index 12c25b47..908ae934 100644 --- a/computes/tests/test_capacity.py +++ b/computes/tests/test_capacity.py @@ -64,12 +64,12 @@ class ComputesPageTests(TestCase): self.assertIn("2.5:1", cells[2]) self.assertIn("40 vCPUs on 16 CPUs", cells[2]) self.assertIn("24 in running VMs", cells[2]) - self.assertIn("75 % 48.0 GB / 64.0 GB", cells[3]) - self.assertIn("32.0 GB in running VMs", cells[3]) + self.assertIn("75% 48 GiB / 64 GiB", cells[3]) + self.assertIn("32 GiB in running VMs", cells[3]) # the totals of the hosts read: host-two's capacity could not be totals = [" ".join(card.text_content().split()) for card in page.xpath("//div[@class='card-body']")] self.assertEqual(totals, ["Hosts 2 / 2 connected", "VMs 3 / 6 running", "vCPUs given 40 on 16 CPUs", - "Memory given 48.0 GB of 64.0 GB"]) + "Memory given 48 GiB of 64 GiB"]) # host-two could not be read: one cell says so self.assertIn("capacity could not be read", " ".join(two.text_content().split())) @@ -86,7 +86,7 @@ class SingularTests(TestCase): line = self.client.get(reverse("compute_capacity", args=[c.id])).content.decode() (cell,) = page.xpath("//tbody/tr/td[3]") self.assertIn("1 vCPU on 1 CPU", " ".join(cell.text_content().split())) - self.assertEqual(" ".join(line.split()), "Given to VMs: 1 vCPU (1.0:1), 1.0 GB memory.") + self.assertEqual(" ".join(line.split()), "Given to VMs: 1 vCPU (1.0:1), 1 GiB memory.") class NewVmDialogLineTests(TestCase): @@ -107,10 +107,10 @@ class NewVmDialogLineTests(TestCase): given = {"cpus": 16, "memory": 64 * GIB, "vcpus": {"all": 24, "running": 8}, "assigned": {"all": 48 * GIB, "running": 32 * GIB}, "ratio": 1.5, } - self.assertEqual(self.line(given), "Given to VMs: 24 vCPUs (1.5:1), 48.0 GB memory.") + self.assertEqual(self.line(given), "Given to VMs: 24 vCPUs (1.5:1), 48 GiB memory.") def test_a_host_without_pools_or_capacity_says_so(self): given = {"cpus": 2, "memory": 4 * GIB, "vcpus": {"all": 0, "running": 0}, "assigned": {"all": 0, "running": 0}, "ratio": 0} - self.assertEqual(self.line(given), "Given to VMs: 0 vCPUs (0.0:1), 0 bytes memory.") + self.assertEqual(self.line(given), "Given to VMs: 0 vCPUs (0.0:1), 0 B memory.") self.assertEqual(self.line(None), "The capacity could not be read.") diff --git a/computes/tests/test_cpu_graph.py b/computes/tests/test_cpu_graph.py index 0e2fd100..caf8b984 100644 --- a/computes/tests/test_cpu_graph.py +++ b/computes/tests/test_cpu_graph.py @@ -143,7 +143,7 @@ class GraphScriptTestCase(TestCase): poll.request(); poll.onData({cpudata: null, memdata: {total: null, usage: null}, timeline: "t"}); poll.request(); - const label = charts[0].options.plugins.tooltip.callbacks.label({dataset: {label: "Usage"}, formattedValue: "3", dataIndex: 0}); + const label = charts[0].options.plugins.tooltip.callbacks.label({dataset: {label: "Usage"}, formattedValue: "3", parsed: {y: 3}, dataIndex: 0}); console.log(JSON.stringify({requests, timeouts, label, shown, state: elements.graph_state.textContent, cpu: charts[0].data.datasets[0].data.map((point) => point.y), mem: charts[1].data.datasets[0].data.map((point) => point.y), memMax: charts[1].options.scales.y.max})); @@ -159,9 +159,9 @@ class GraphScriptTestCase(TestCase): # a host that could not be read leaves a gap and keeps the memory axis self.assertEqual((result["mem"], result["memMax"]), ([1, None], 2)) # the readings in words, and since when they are not updated - self.assertEqual(result["shown"], ["3 %", "1 / 2 GiB", "Updated at t."]) + self.assertEqual(result["shown"], ["3%", "1 / 2 GiB", "Updated at t."]) self.assertEqual(result["state"], "Not updated since t.") - self.assertTrue(result["label"].endswith(": 3 % (average over 5.1 s)"), result["label"]) + self.assertTrue(result["label"].endswith(": 3% (average over 5.1 s)"), result["label"]) @unittest.skipUnless(shutil.which("node"), "node is not installed") diff --git a/computes/tests/test_overview.py b/computes/tests/test_overview.py index 743efec4..88d0b9df 100644 --- a/computes/tests/test_overview.py +++ b/computes/tests/test_overview.py @@ -60,11 +60,11 @@ class OverviewTestCase(TestCase): cards = [" ".join(" ".join(card.itertext()).split()) for card in page.xpath("//div[@class='card h-100']")] self.assertIn("VMs 6 3 running, 2 shut off, 1 paused Instances →", cards) self.assertTrue(any(card.startswith("vCPUs 1.5:1 12 vCPUs on 8 CPUs 6 in running VMs") for card in cards), cards) - self.assertTrue(any(card.startswith("Memory 75 % 24.0 GB / 32.0 GB") for card in cards), cards) - self.assertTrue(any("120.0 GB free of 500.0 GB" in card for card in cards), cards) + self.assertTrue(any(card.startswith("Memory 75% 24 GiB / 32 GiB") for card in cards), cards) + self.assertTrue(any("120 GiB free of 500 GiB" in card for card in cards), cards) hardware = text(page, "//div[@class='card-header'][normalize-space()='Hardware']/..") self.assertIn("Processor Xeon Architecture x86_64 Logical CPUs 8 Physical cores 4 Sockets 2 NUMA nodes 2 " - "Clock 2.4 GHz Memory 32.0 GB", hardware) + "Clock 2.4 GHz Memory 32 GiB", hardware) software = text(page, "//div[@class='card-header'][normalize-space()='Software and connection']/..") self.assertIn("QEMU 10.1.0 libvirt 11.10.0", software) self.assertIn("x86_64 kvm · qemu", software) @@ -78,7 +78,7 @@ class OverviewTestCase(TestCase): pool("backup", 900, 800), pool("iso", 100, 90)] page = self.page(pools=pools) storage = page.xpath("//div[@class='card-header'][normalize-space()='Storage']/..")[0] - self.assertIn("default 120.0 GB free of 500.0 GB", " ".join(" ".join(storage.xpath("./div/div//text()")).split())) + self.assertIn("default 120 GiB free of 500 GiB", " ".join(" ".join(storage.xpath("./div/div//text()")).split())) (more,) = storage.xpath(".//details") self.assertEqual(" ".join(more.xpath("summary")[0].text_content().split()), "3 more pools") # active pools only, by name after the default one diff --git a/instances/templates/allinstances_index_grouped.html b/instances/templates/allinstances_index_grouped.html index 18e14315..e154c7db 100644 --- a/instances/templates/allinstances_index_grouped.html +++ b/instances/templates/allinstances_index_grouped.html @@ -1,4 +1,5 @@ {% load i18n %} +{% load common_tags %} {% load bootstrap_icons %}
    @@ -44,9 +45,9 @@ {% if compute.status is True and compute.ram_usage is not None %} - + - + diff --git a/vmbackups/templates/vmbackups/vm_tab.html b/vmbackups/templates/vmbackups/vm_tab.html index 9294e07b..8770c09b 100644 --- a/vmbackups/templates/vmbackups/vm_tab.html +++ b/vmbackups/templates/vmbackups/vm_tab.html @@ -1,4 +1,5 @@ {% load i18n %} +{% load common_tags %} {% load operations %} {% load bootstrap_icons %} {% load static %} @@ -47,7 +48,7 @@ - + diff --git a/vmbackups/tests/test_create.py b/vmbackups/tests/test_create.py index 0e032948..10682af9 100644 --- a/vmbackups/tests/test_create.py +++ b/vmbackups/tests/test_create.py @@ -609,7 +609,7 @@ class BackupTabTests(PageControls, TransactionTestCase): page = lxml_html.fromstring(self.last_page) self.assertTrue(page.xpath("//div[@id='backups']//form[contains(@action, '/backups/vm/')]")) self.assertIn("nfs1", page.xpath("string(//select[@id='backup-target'])")) - self.assertIn("3.0", page.xpath("string(//div[@id='backups']//table)")) + self.assertIn("3\xa0GiB", page.xpath("string(//div[@id='backups']//table)")) backup_proxy.return_value.backup_plan.side_effect = OperationError("%(vm)s has TPM state", vm="ctl-vm") self.controls(admin) page = lxml_html.fromstring(self.last_page) diff --git a/webvirtcloud/common_tags.py b/webvirtcloud/common_tags.py index 8f30ce60..4a0c7abc 100644 --- a/webvirtcloud/common_tags.py +++ b/webvirtcloud/common_tags.py @@ -1,6 +1,8 @@ import re from django import template +from django.utils import formats +from django.utils.translation import gettext register = template.Library() @@ -24,3 +26,22 @@ def class_active(request, pattern): return "active" if re.search(pattern, request.path) else "" + + +BINARY_UNITS = ("B", "KiB", "MiB", "GiB", "TiB", "PiB") + + +@register.filter +def binary_size(value): + """A size in bytes with the binary unit the forms ask in: 1536 -> 1.5 KiB, 2 GiB -> 2 GiB.""" + size, unit = float(value or 0), 0 + while abs(round(size, 1)) >= 1024 and unit < len(BINARY_UNITS) - 1: + size, unit = size / 1024, unit + 1 + size = round(size, 1) + return f"{formats.number_format(size, 0 if size.is_integer() else 1)}\xa0{BINARY_UNITS[unit]}" + + +@register.filter +def percent(value): + """A percentage as the page's language writes it: 13% in English, %13 in Turkish.""" + return gettext("%(percent)s%%") % {"percent": formats.number_format(value)} diff --git a/webvirtcloud/tests/test_numbers.py b/webvirtcloud/tests/test_numbers.py new file mode 100644 index 00000000..cd953f8c --- /dev/null +++ b/webvirtcloud/tests/test_numbers.py @@ -0,0 +1,29 @@ +"""Sizes and percentages on the pages: sizes in the binary units the forms ask +in, percentages as the page's language writes them.""" + +from django.test import SimpleTestCase +from django.utils import translation + +from webvirtcloud.common_tags import binary_size, percent + + +class BinarySizeTests(SimpleTestCase): + def test_a_size_takes_the_largest_unit_with_one_decimal_at_most(self): + for size, shown in ((0, "0 B"), (None, "0 B"), (512, "512 B"), (1536, "1.5 KiB"), (512 * 2**20, "512 MiB"), + (int(3.8 * 2**30), "3.8 GiB"), (20 * 2**30, "20 GiB"), (1023.96 * 2**20, "1 GiB"), + (3 * 2**40, "3 TiB")): + with self.subTest(size=size): + self.assertEqual(binary_size(size), shown.replace(" ", "\xa0")) + + def test_the_decimal_mark_is_the_languages(self): + with translation.override("tr"): + self.assertEqual(binary_size(int(3.8 * 2**30)), "3,8\xa0GiB") + + +class PercentTests(SimpleTestCase): + def test_each_language_puts_the_sign_where_it_writes_it(self): + for language, shown in (("en", "13%"), ("tr", "%13"), ("zh-hans", "13%")): + with self.subTest(language=language), translation.override(language): + self.assertEqual(percent(13), shown) + with translation.override("tr"): + self.assertEqual(percent(12.5), "%12,5")
    {{ compute.cpu_count }}{{ compute.ram_size|filesizeformat }}{{ compute.ram_size|binary_size }} -
    {% blocktrans with percent=compute.ram_usage %}host memory {{ percent }}% in use{% endblocktrans %}
    +
    {% blocktrans with percent=compute.ram_usage %}Host memory {{ percent }}% in use{% endblocktrans %}
    diff --git a/instances/templates/create_inst_block.html b/instances/templates/create_inst_block.html index 7d7dd977..1b9c8f17 100644 --- a/instances/templates/create_inst_block.html +++ b/instances/templates/create_inst_block.html @@ -1,4 +1,5 @@ {% load i18n %} +{% load common_tags %} {% load bootstrap_icons %}
    -
    {% trans "Memory" %} · {{ compute.ram_size|filesizeformat }}
    +
    {% trans "Memory" %} · {{ compute.ram_size|binary_size }}
    - {{ compute.ram_usage }}% + {{ compute.ram_usage|percent }}
    diff --git a/instances/templates/instance.html b/instances/templates/instance.html index 3b37b586..4c6c47f2 100644 --- a/instances/templates/instance.html +++ b/instances/templates/instance.html @@ -1,5 +1,6 @@ {% extends "base.html" %} {% load static %} +{% load common_tags %} {% load vm_states %} {% load i18n %} {% load operations %} @@ -68,7 +69,7 @@
    {% trans "Disks" %}
    -
    {% for disk in instance.disks %}{{ disk.dev }} {{ disk.size|filesizeformat }}{% if not forloop.last %} · {% endif %}{% empty %}{% trans "None" %}{% endfor %}
    +
    {% for disk in instance.disks %}{{ disk.dev }} {{ disk.size|binary_size }}{% if not forloop.last %} · {% endif %}{% empty %}{% trans "None" %}{% endfor %}
    {% if not instance.is_template %}
    diff --git a/instances/templates/instances/edit_instance_volume.html b/instances/templates/instances/edit_instance_volume.html index 0a849e5c..298bf0a0 100644 --- a/instances/templates/instances/edit_instance_volume.html +++ b/instances/templates/instances/edit_instance_volume.html @@ -1,4 +1,5 @@ {% load i18n %} +{% load common_tags %} {% if request.user.is_superuser %} @@ -8,7 +9,7 @@ diff --git a/instances/templates/instances/migrate_plan.html b/instances/templates/instances/migrate_plan.html index 38d5ddc7..2670c6b9 100644 --- a/instances/templates/instances/migrate_plan.html +++ b/instances/templates/instances/migrate_plan.html @@ -1,4 +1,5 @@ {% load i18n %} +{% load common_tags %} {# the disks of the Migrate tab for the chosen destination: where each goes; data-refused keeps the form from being sent #} {% if error %}
    {% blocktrans %}The disks could not be checked: {{ error }}{% endblocktrans %}
    @@ -7,7 +8,7 @@ {% else %} {% for disk in disks %} -

    {{ disk.target }} {{ disk.capacity|filesizeformat }}

    +

    {{ disk.target }} {{ disk.capacity|binary_size }}

    {{ disk.path }}

    {% if disk.shared or not disk.refusal and disk.free_pools %} @@ -16,7 +17,7 @@ {% if not disk.refusal %} {% for pool in pools %} {% if pool.name in disk.free_pools %} - + {% else %} {% endif %} diff --git a/instances/templates/instances/resize_tab.html b/instances/templates/instances/resize_tab.html index 2086394e..6c5c6646 100644 --- a/instances/templates/instances/resize_tab.html +++ b/instances/templates/instances/resize_tab.html @@ -1,4 +1,5 @@ {% load i18n %} +{% load common_tags %} {% load bootstrap_icons %} {% load vm_states %}
    @@ -83,7 +84,7 @@
    {% blocktrans with cur=instance.cur_memory max=instance.memory %}{{ cur }} MiB of {{ max }} MiB{% endblocktrans %} - {% blocktrans with total=memory_host|filesizeformat %}Host: {{ total }}{% endblocktrans %} + {% blocktrans with total=memory_host|binary_size %}Host: {{ total }}{% endblocktrans %}
    {% csrf_token %}
    @@ -110,7 +111,7 @@ {% if disk.storage is None %}
    {% trans "Error getting disk info" %}
    {% else %} -
    {% blocktrans with size=disk.size|filesizeformat %}Now {{ size }}{% endblocktrans %}
    +
    {% blocktrans with size=disk.size|binary_size %}Now {{ size }}{% endblocktrans %}
    diff --git a/instances/templates/instances/settings_tab.html b/instances/templates/instances/settings_tab.html index 5946feb7..43a0c395 100644 --- a/instances/templates/instances/settings_tab.html +++ b/instances/templates/instances/settings_tab.html @@ -1,4 +1,5 @@ {% load i18n %} +{% load common_tags %} {% load django_bootstrap5 %} {% load bootstrap_icons %} {% load vm_states %} @@ -215,8 +216,8 @@ {# a qcow2 file's metadata can take it past its capacity: the bar stops full #} {% if used_percent|add:0 > 100 %}{% widthratio 100 1 1 as used_percent %}{% endif %}
    - {% trans "Capacity" %} {{ disk.size|filesizeformat }} - {% blocktrans with used=disk.used|filesizeformat %}{{ used }} used{% endblocktrans %} + {% trans "Capacity" %} {{ disk.size|binary_size }} + {% blocktrans with used=disk.used|binary_size %}{{ used }} used{% endblocktrans %}
    diff --git a/instances/tests/test_create_dialog_cpu.py b/instances/tests/test_create_dialog_cpu.py index 528b8128..bd9fc6c5 100644 --- a/instances/tests/test_create_dialog_cpu.py +++ b/instances/tests/test_create_dialog_cpu.py @@ -36,7 +36,7 @@ const handlers = {}, requests = []; const dialog = {addEventListener: (name, fn) => { handlers[name] = fn; }, querySelectorAll: (sel) => sel === ".cpu-usage" ? cells : cells.flatMap((c, i) => [c, lines[i]])}; const page = { - document: {getElementById: () => dialog}, + document: {documentElement: {lang: "en"}, getElementById: () => dialog}, $: {get: (url) => { const r = {url, done: (f) => { r.ok = f; return r; }, fail: (f) => { r.err = f; return r; }, always: (f) => { r.end = f; return r; }}; diff --git a/instances/tests/test_drbd_target.py b/instances/tests/test_drbd_target.py index d607fe60..2d279668 100644 --- a/instances/tests/test_drbd_target.py +++ b/instances/tests/test_drbd_target.py @@ -83,7 +83,7 @@ class DrbdListTestCase(TestCase): patch.object(Compute, "status", new_callable=PropertyMock, return_value=True), \ patch.object(Instance, "info", new_callable=PropertyMock, return_value=None), \ patch.object(Compute, "proxy", new_callable=PropertyMock, - return_value=MagicMock(**{"get_domain_rows.return_value": {}})), \ + return_value=MagicMock(**{"get_domain_rows.return_value": {}, "get_memory_usage.return_value": {"percent": 10}})), \ patch("instances.views.subprocess.run", return_value=SimpleNamespace(returncode=0, stdout=STATUS)) as run: self.assertEqual(self.client.get(reverse("instances:index")).status_code, 200) run.assert_called_once() @@ -108,7 +108,7 @@ class DrbdListTestCase(TestCase): patch.object(Compute, "status", new_callable=PropertyMock, return_value=True), \ patch.object(Instance, "info", new_callable=PropertyMock, return_value=None), \ patch.object(Compute, "proxy", new_callable=PropertyMock, - return_value=MagicMock(**{"get_domain_rows.return_value": {}})), \ + return_value=MagicMock(**{"get_domain_rows.return_value": {}, "get_memory_usage.return_value": {"percent": 10}})), \ patch("instances.views.subprocess.run", side_effect=slow) as run: self.client.get(reverse("instances:index")) self.assertEqual(run.call_count, 3) diff --git a/instances/tests/test_find_address_js.py b/instances/tests/test_find_address_js.py index e903b981..0854295f 100644 --- a/instances/tests/test_find_address_js.py +++ b/instances/tests/test_find_address_js.py @@ -23,7 +23,7 @@ const ids = { }; const answer = ANSWER; vm.runInNewContext(SCRIPT, vm.createContext({ - document: {getElementById: (id) => ids[id]}, URLSearchParams, Promise, Date, location: {}, + document: {documentElement: {lang: "en"}, getElementById: (id) => ids[id]}, URLSearchParams, Promise, Date, location: {}, fetch: () => Promise.resolve({redirected: false, json: () => Promise.resolve(answer)}), })); handlers.submit({preventDefault() {}}); diff --git a/instances/tests/test_guest_info.py b/instances/tests/test_guest_info.py index ff1a9e93..d426f703 100644 --- a/instances/tests/test_guest_info.py +++ b/instances/tests/test_guest_info.py @@ -27,7 +27,7 @@ class GuestInfoTestCase(TestCase): {"mountpoint": "/", "type": "xfs", "used": 9 * 2**30, "total": 10 * 2**30}]} data = self.client.get(reverse("instances:osinfo", args=[self.instance.pk])).json() self.assertEqual(data["filesystems"], [{"mountpoint": "/", "type": "xfs", "used": 9 * 2**30, "total": 10 * 2**30, - "used_text": "9.0\xa0GB", "total_text": "10.0\xa0GB", "percent": 90}]) + "used_text": "9\xa0GiB", "total_text": "10\xa0GiB", "percent": 90}]) def test_a_file_system_used_past_its_total_is_full(self): # a BSD guest's total leaves out the space reserved for root, which used counts diff --git a/instances/tests/test_migrate_job.py b/instances/tests/test_migrate_job.py index e5234722..1c532bc9 100644 --- a/instances/tests/test_migrate_job.py +++ b/instances/tests/test_migrate_job.py @@ -204,8 +204,8 @@ class MigrateJobTestCase(TransactionTestCase): self.assertEqual(dest.migration_plan.call_args.args[1:], ("", "")) self.assertEqual(Instance.proxy.instance.XMLDesc.call_args_list[-1].args, (VIR_DOMAIN_XML_INACTIVE,)) # the pool on the disk's directory is chosen; one that has a file of the name cannot be - self.assertIn('', page) - self.assertIn('', page) + self.assertIn('', page) + self.assertIn('', page) self.assertIn('', page) self.assertIn("Cannot be copied: an image is not copied; eject it first", page) self.assertEqual(page.count("Another disk of the VM has this file name: copy them to different pools."), 1) diff --git a/instances/tests/test_page_controls.py b/instances/tests/test_page_controls.py index ab8c8200..09e104ba 100644 --- a/instances/tests/test_page_controls.py +++ b/instances/tests/test_page_controls.py @@ -142,7 +142,7 @@ class PageControlsTestCase(PageControls, TestCase): self.assertEqual([a.text_content().strip() for a in admin_page.xpath(links)], ["ctl-compute", "Instances"]) self.assertEqual([a.text_content().strip() for a in owner_page.xpath(links)], ["Instances"]) self.assertIn("Guest agent not connected", self.last_page) - self.assertIn("vda 2.0\xa0GB · vdb 1.0\xa0GB", self.last_page) + self.assertIn("vda 2\xa0GiB · vdb 1\xa0GiB", self.last_page) # filled by its script once the page has loaded ("—" when it has none) self.assertEqual(owner_page.xpath("//dt[.='IPv4']/following-sibling::dd/@data-empty"), ["—"]) diff --git a/instances/tests/test_resize_input.py b/instances/tests/test_resize_input.py index ce816527..db620226 100644 --- a/instances/tests/test_resize_input.py +++ b/instances/tests/test_resize_input.py @@ -57,7 +57,7 @@ class ResizeInputTests(TestCase): disks = [{"dev": "vda", "size": 10 * GIB}, {"dev": "vdb", "size": 20 * GIB}] messages, proxy = self.post("instances:resize_disk", {"disk_size_vda": "5", "disk_size_vdb": "30"}, disks=disks) proxy.resize_disk.assert_not_called() - self.assertEqual(messages, ["vda is 10.0\xa0GB: a disk cannot shrink"]) + self.assertEqual(messages, ["vda is 10\xa0GiB: a disk cannot shrink"]) def test_vcpus_and_memory_must_be_at_least_one(self): for view, data, setter in (("instances:resizevm_cpu", {"vcpu": "2", "cur_vcpu": "0"}, "resize_cpu"), diff --git a/instances/tests/test_stats_sample.py b/instances/tests/test_stats_sample.py index c33c83e7..295f2d47 100644 --- a/instances/tests/test_stats_sample.py +++ b/instances/tests/test_stats_sample.py @@ -214,7 +214,7 @@ class StatsScriptTestCase(TestDriverVM, TestCase): poll.request(); fail = false; poll.request(); - const label = charts[0].options.plugins.tooltip.callbacks.label({dataset: {label: "Usage"}, formattedValue: "3", dataIndex: 0}); + const label = charts[0].options.plugins.tooltip.callbacks.label({dataset: {label: "Usage"}, formattedValue: "3", parsed: {y: 3}, dataIndex: 0}); console.log(JSON.stringify({requests, label, every: [poll.interval, poll.first], cpu: charts[0].data.datasets[0].data.map((point) => point.y), disk: charts[2].data.datasets[1].data.map((point) => point.y), net: charts[3].data.datasets[0].data.map((point) => point.y), mem: charts[1].data.datasets[0].data.map((point) => point.y), memMax: charts[1].options.scales.y.max})); @@ -231,4 +231,4 @@ class StatsScriptTestCase(TestDriverVM, TestCase): self.assertEqual((result["cpu"], result["disk"], result["net"]), ([3, 4], [None, None], [2, 2])) # memory that could not be read leaves a gap and keeps the axis self.assertEqual((result["mem"], result["memMax"]), ([1, None], 1)) - self.assertTrue(result["label"].endswith(": 3 % (average over 9.9 s)"), result["label"]) + self.assertTrue(result["label"].endswith(": 3% (average over 9.9 s)"), result["label"]) diff --git a/instances/tests/test_vm_states.py b/instances/tests/test_vm_states.py index 2d89725f..f71267f8 100644 --- a/instances/tests/test_vm_states.py +++ b/instances/tests/test_vm_states.py @@ -85,7 +85,7 @@ class VmStatesTestCase(TestCase): with patch.object(Compute, "status", property(lambda c: c.pk == self.up.pk)), \ patch.object(Compute, "connection_error", property(lambda c: None if c.pk == self.up.pk else "unreachable")), \ patch.object(Compute, "proxy", new_callable=PropertyMock, - return_value=MagicMock(**{"get_domain_rows.return_value": {}})), \ + return_value=MagicMock(**{"get_domain_rows.return_value": {}, "get_memory_usage.return_value": {"percent": 10}})), \ patch("instances.views.refresh_instance_database"), patch("computes.views.utils.refresh_instance_database"): for url, states_url in ((reverse("instances:index"), reverse("instances:states")), (reverse("instances", args=[self.up.pk]), diff --git a/instances/views.py b/instances/views.py index f4ceebac..5039ea48 100755 --- a/instances/views.py +++ b/instances/views.py @@ -35,7 +35,7 @@ from django.db import transaction from django.db.models import Prefetch, prefetch_related_objects from django.shortcuts import get_object_or_404, redirect, render from django.urls import reverse -from django.template.defaultfilters import filesizeformat +from webvirtcloud.common_tags import binary_size from django.utils import timezone from django.utils.http import url_has_allowed_host_and_scheme from django.utils.translation import gettext as _ @@ -574,7 +574,7 @@ def osinfo(request, pk): try: info = instance.proxy.osinfo() for fs in info.get("filesystems", []): # sizes in the page's words - fs.update(used_text=filesizeformat(fs["used"]), total_text=filesizeformat(fs["total"]), + fs.update(used_text=binary_size(fs["used"]), total_text=binary_size(fs["total"]), percent=min(100, fs["used"] * 100 // fs["total"])) # used may pass a BSD guest's total return JsonResponse(info) except libvirtError as err: @@ -1475,7 +1475,7 @@ def resize_disk(request, pk): # a disk does not shrink: one smaller size refuses them all if int(size) << 30 < disk["size"]: messages.error(request, _("%(dev)s is %(size)s: a disk cannot shrink") % { - "dev": disk["dev"], "size": filesizeformat(disk["size"])}) + "dev": disk["dev"], "size": binary_size(disk["size"])}) return redirect(reverse("instances:instance", args=[instance.id]) + "#resizevm_disk") if int(size) << 30 > disk["size"]: disk["size_new"] = int(size) << 30 diff --git a/locale/tr/LC_MESSAGES/django.mo b/locale/tr/LC_MESSAGES/django.mo index b807d201..4889b981 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 91682ba8..9bf61bdc 100644 --- a/locale/tr/LC_MESSAGES/django.po +++ b/locale/tr/LC_MESSAGES/django.po @@ -588,7 +588,7 @@ msgstr "" #: accounts/views.py:93 #, python-format msgid "You have a token named %(name)s: choose another name." -msgstr "%(name)s adlı bir token'ınız var: başka bir ad seçin." +msgstr "%(name)s adlı bir API anahtarınız var: başka bir ad seçin." #: accounts/views.py:130 msgid "API token deleted" @@ -1260,7 +1260,7 @@ msgstr "Kullanıcının nasıl oturum açtığı." #: admin/templates/admin/user_password_form.html:19 msgid "Changing it deletes the user's API tokens." -msgstr "Değiştirmek kullanıcının API token'larını siler." +msgstr "Değiştirmek kullanıcının API anahtarlarını siler." #: admin/templates/admin/user_password_form.html:22 msgid "Signs in with the password set here." @@ -2238,7 +2238,7 @@ msgstr "" #: computes/models.py:56 msgid "hostname" -msgstr "sunucuadı" +msgstr "ana bilgisayar adı" #: computes/models.py:57 msgid "login" @@ -2346,8 +2346,8 @@ msgstr "%%%(percent)s dolu" #, python-format msgid "%(counter)s snapshot older than 30 days" msgid_plural "%(counter)s snapshots older than 30 days" -msgstr[0] "30 günden eski %(counter)s snapshot" -msgstr[1] "30 günden eski %(counter)s snapshot" +msgstr[0] "30 günden eski %(counter)s anlık görüntü" +msgstr[1] "30 günden eski %(counter)s anlık görüntü" #: computes/templates/computes/attention.html:17 #, python-format @@ -3130,7 +3130,7 @@ msgstr "Yazılım ve bağlantı" #: computes/templates/overview.html:205 #: instances/templates/instances/info_tab.html:6 msgid "Hostname" -msgstr "Sunucuadı" +msgstr "Ana bilgisayar adı" #: computes/templates/overview.html:217 msgid "Guest architectures" @@ -3721,7 +3721,7 @@ msgstr "%(quota)s: %(name)s anlık görüntüsüne dönülemiyor." #: instances/jobs.py:525 msgid "Revert snapshot" -msgstr "Snapshota dön" +msgstr "Anlık görüntüye dön" #: instances/jobs.py:568 msgid "Reverting the VM" @@ -4575,8 +4575,8 @@ msgstr "daraltıldı" #: instances/templates/allinstances_index_grouped.html:48 #, python-format -msgid "host memory %(percent)s%% in use" -msgstr "sunucu belleği kullanımı %%%(percent)s" +msgid "Host memory %(percent)s%% in use" +msgstr "Sunucu belleği kullanımı %%%(percent)s" #: instances/templates/allinstances_index_grouped.html:49 msgid "Host memory in use" @@ -9199,11 +9199,6 @@ msgstr "Başarılı" msgid "What you checked" msgstr "Neyi kontrol ettiniz" -#: operations/templates/operations/jobs.html:14 -#: operations/templatetags/operations.py:97 -msgid "Worker unavailable, last seen" -msgstr "İşçi kullanılamıyor, son görülme" - #: operations/templates/operations/jobs.html:22 msgid "Filter jobs" msgstr "İşleri filtrele" @@ -9383,7 +9378,7 @@ msgstr "" #: operations/worker.py:505 msgid "The worker stopped before the job changed anything" -msgstr "Worker, iş herhangi bir şeyi değiştirmeden önce durdu" +msgstr "İş işleyicisi, iş herhangi bir şeyi değiştirmeden önce durdu" #: storages/api/viewsets.py:148 storages/api/viewsets.py:164 #: storages/api/viewsets.py:200 storages/api/viewsets.py:223 @@ -13027,3 +13022,20 @@ msgstr "Hangi sanal makineler" #: vmbackups/forms.py msgid "Choose the VMs to back up" msgstr "Yedeklenecek sanal makineleri seçin" + + +#: webvirtcloud/common_tags.py:29 +#, python-format +msgid "%(percent)s%%" +msgstr "%%%(percent)s" + +#: operations/templates/operations/jobs.html:16 +#: operations/templatetags/operations.py:98 +#, python-format +msgid "The job worker is not running; it was last seen %(when)s. Jobs wait until it runs again." +msgstr "İş işleyicisi çalışmıyor; en son %(when)s görüldü. İşler o yeniden çalışana kadar bekler." + +#: operations/templates/operations/jobs.html:16 +#: operations/templatetags/operations.py:99 +msgid "The job worker has not run yet. Jobs wait until it runs." +msgstr "İş işleyicisi henüz hiç çalışmadı. İşler o çalışana kadar bekler." diff --git a/locale/zh/LC_MESSAGES/django.mo b/locale/zh/LC_MESSAGES/django.mo index e98cf2c4..b675b67c 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 100be414..85c68c41 100644 --- a/locale/zh/LC_MESSAGES/django.po +++ b/locale/zh/LC_MESSAGES/django.po @@ -4345,7 +4345,7 @@ msgstr "已折叠" #: instances/templates/allinstances_index_grouped.html:48 #, python-format -msgid "host memory %(percent)s%% in use" +msgid "Host memory %(percent)s%% in use" msgstr "主机内存已用 %(percent)s%%" #: instances/templates/allinstances_index_grouped.html:49 @@ -8671,11 +8671,6 @@ msgstr "成功" msgid "What you checked" msgstr "检查内容" -#: operations/templates/operations/jobs.html:14 -#: operations/templatetags/operations.py:97 -msgid "Worker unavailable, last seen" -msgstr "工作进程不可用,最后在线时间" - #: operations/templates/operations/jobs.html:22 msgid "Filter jobs" msgstr "筛选任务" @@ -12302,3 +12297,20 @@ msgstr "哪些虚拟机" #: vmbackups/forms.py msgid "Choose the VMs to back up" msgstr "请选择要备份的虚拟机" + + +#: webvirtcloud/common_tags.py:29 +#, python-format +msgid "%(percent)s%%" +msgstr "%(percent)s%%" + +#: operations/templates/operations/jobs.html:16 +#: operations/templatetags/operations.py:98 +#, python-format +msgid "The job worker is not running; it was last seen %(when)s. Jobs wait until it runs again." +msgstr "工作进程未在运行;最后在线时间 %(when)s。任务将等待它重新运行。" + +#: operations/templates/operations/jobs.html:16 +#: operations/templatetags/operations.py:99 +msgid "The job worker has not run yet. Jobs wait until it runs." +msgstr "工作进程尚未运行过。任务将等待它运行。" diff --git a/operations/static/operations/job_panel.js b/operations/static/operations/job_panel.js index 2093eab4..9e8c57d4 100644 --- a/operations/static/operations/job_panel.js +++ b/operations/static/operations/job_panel.js @@ -25,6 +25,8 @@ function jobPanel(element, urls, csrfToken, initialIds, states, text) { var last = { jobs: [], others: [], short_operation: false, worker_last_seen: null, worker_gone: false }; var rendered = null; // the panel's last html: an unchanged one is not rebuilt (focus stays) var holding = false; // the panel set backgroundJobRunning (no other script holds it) + // a percentage as the page's language writes it: 38% in English, %38 in Turkish + var percentFormat = new Intl.NumberFormat(document.documentElement.lang || undefined, {style: "percent"}); if (initialIds && initialIds.length) { // a remembered job must not be lost to a status reload before the first poll answers window.backgroundJobRunning = true; @@ -44,13 +46,13 @@ function jobPanel(element, urls, csrfToken, initialIds, states, text) { return '
    ' + (finishing ? esc(text.finishing) : pct + "%") + "
    "; + + (finishing ? 100 : pct) + '%">' + (finishing ? esc(text.finishing) : percentFormat.format(pct / 100)) + "
    "; } // label, state badge and muted phase on one line, the buttons on its right function header(label, state, phase, buttons) { return '
    ' + esc(label) + "" - + '' + esc(states[state] || state) + "" + (phase ? '' + esc(phase) + "" : "") @@ -104,8 +106,8 @@ function jobPanel(element, urls, csrfToken, initialIds, states, text) { // the server tells: the browser's clock may be off var seen = last.worker_last_seen ? new Date(last.worker_last_seen) : null; if (waiting && last.worker_gone) { - html += '
    ' + esc(text.worker_unavailable) + " " - + esc(seen ? seen.toLocaleString() : text.never) + ".
    "; + html += '
    ' + + esc(seen ? text.worker_gone.replace("%(when)s", seen.toLocaleString(document.documentElement.lang || undefined)) : text.worker_never) + "
    "; } if (html !== rendered) { element.innerHTML = html; diff --git a/operations/templates/operations/job.html b/operations/templates/operations/job.html index 8e435e46..08774ad2 100644 --- a/operations/templates/operations/job.html +++ b/operations/templates/operations/job.html @@ -1,5 +1,6 @@ {% extends "base.html" %} {% load i18n %} +{% load common_tags %} {% load bootstrap_icons %} {% load operations %} @@ -38,9 +39,9 @@ {% widthratio op.progress_done|default:0 op.progress_total 100 as percent %}
    - {% if progress_bytes %}{{ op.progress_done|default:0|filesizeformat }} / {{ op.progress_total|filesizeformat }}{% else %}{{ op.progress_done|default:0 }} / {{ op.progress_total }}{% endif %} + {% if progress_bytes %}{{ op.progress_done|default:0|binary_size }} / {{ op.progress_total|binary_size }}{% else %}{{ op.progress_done|default:0 }} / {{ op.progress_total }}{% endif %} - {{ percent }}% + {{ percent|percent }}
    diff --git a/operations/templates/operations/jobs.html b/operations/templates/operations/jobs.html index c3799261..ac0fc166 100644 --- a/operations/templates/operations/jobs.html +++ b/operations/templates/operations/jobs.html @@ -1,5 +1,6 @@ {% extends "base.html" %} {% load i18n %} +{% load common_tags %} {% load django_bootstrap5 %} {% load static %} {% load bootstrap_icons %} @@ -12,8 +13,8 @@ {% block content %} {% if worker_unavailable %}
    - {% bs_icon 'exclamation-triangle' %} {% trans "Worker unavailable, last seen" %} - {% if worker_last_seen %}{{ worker_last_seen|date:"Y-m-d H:i:s T" }}{% else %}{% trans "never" %}{% endif %} + {% bs_icon 'exclamation-triangle' %} + {% if worker_last_seen %}{% blocktrans with when=worker_last_seen|date:"Y-m-d H:i:s T" %}The job worker is not running; it was last seen {{ when }}. Jobs wait until it runs again.{% endblocktrans %}{% else %}{% trans "The job worker has not run yet. Jobs wait until it runs." %}{% endif %}
    {% endif %}
    @@ -73,7 +74,7 @@ {{ row.phase }} {% if op.progress_total %} {% if row.phase %}·{% endif %} - {% if op.kind in bytes_kinds %}{{ op.progress_done|default:0|filesizeformat }} / {{ op.progress_total|filesizeformat }}{% else %}{{ op.progress_done|default:0 }} / {{ op.progress_total }}{% endif %} + {% if op.kind in bytes_kinds %}{{ op.progress_done|default:0|binary_size }} / {{ op.progress_total|binary_size }}{% else %}{{ op.progress_done|default:0 }} / {{ op.progress_total }}{% endif %} {% endif %}
    {% endif %} diff --git a/operations/templates/operations/state_badge.html b/operations/templates/operations/state_badge.html index 553ffebb..57d40ff0 100644 --- a/operations/templates/operations/state_badge.html +++ b/operations/templates/operations/state_badge.html @@ -1 +1 @@ -{% load operations %}{% with color=state|state_color %}{{ state|state_label }}{% endwith %} +{% load operations %}{% with color=state|state_color %}{{ state|state_label }}{% endwith %} diff --git a/operations/templatetags/operations.py b/operations/templatetags/operations.py index ea0a161d..5950749d 100644 --- a/operations/templatetags/operations.py +++ b/operations/templatetags/operations.py @@ -95,8 +95,8 @@ def job_panel_script(context, resource): "finishing": gettext("Finishing…"), "not_removed": gettext("Files not removed:"), "short_operation": gettext("A short operation is in progress."), - "worker_unavailable": gettext("Worker unavailable, last seen"), - "never": gettext("never"), + "worker_gone": gettext("The job worker is not running; it was last seen %(when)s. Jobs wait until it runs again."), + "worker_never": gettext("The job worker has not run yet. Jobs wait until it runs."), "cancel_failed": gettext("Cancel failed (HTTP %(status)s)."), "cancel_unreachable": gettext("Cancel failed: the server could not be reached."), }, diff --git a/operations/tests/js/job_panel.test.js b/operations/tests/js/job_panel.test.js index 1f5bcc1c..d36dbeb7 100644 --- a/operations/tests/js/job_panel.test.js +++ b/operations/tests/js/job_panel.test.js @@ -18,7 +18,7 @@ function advance(ms) { } const realNow = Date.now; Date.now = () => 1700000000000 + now; -global.document = { hidden: false, addEventListener() {}, activeElement: null, querySelector: () => null }; +global.document = { documentElement: { lang: "en" }, hidden: false, addEventListener() {}, activeElement: null, querySelector: () => null }; global.window = { backgroundJobRunning: false, location: { reload() { window.reloaded = true; }, assign(url) { window.opened = url; } } }; @@ -55,7 +55,7 @@ const STATES = { queued: "queued", running: "running", cancelling: "cancelling", failed: "failed", cancelled: "cancelled", uncertain: "uncertain" }; const TEXT = { cancel: "Cancel", cancel_confirm: "Cancel %(job)s?", open: "Open", refresh: "Refresh", dismiss: "Dismiss", finishing: "Finishing\u2026", not_removed: "Files not removed:", short_operation: "A short operation is in progress.", - worker_unavailable: "Worker unavailable, last seen", never: "never", + worker_gone: "The job worker is not running; it was last seen %(when)s.", worker_never: "The job worker has not run yet.", cancel_failed: "Cancel failed (HTTP %(status)s).", cancel_unreachable: "Cancel failed: the server could not be reached." }; const seen = new Date(1700000000000).toISOString(); @@ -71,7 +71,7 @@ assert.ok(el.innerHTML.includes("Delete snapshot") && el.innerHTML.includes("25% // one colour per state (operations/tests/test_views.py checks the same map in the template filter) assert.deepStrictEqual(JOB_STATE_COLORS, { queued: "secondary", running: "primary", cancelling: "info", succeeded: "success", failed: "danger", cancelled: "secondary", uncertain: "warning" }); -assert.ok(el.innerHTML.includes('class="alert alert-primary') && el.innerHTML.includes('running') +assert.ok(el.innerHTML.includes('class="alert alert-primary') && el.innerHTML.includes('running') && el.innerHTML.includes('Merging'), "state badge and muted phase"); assert.strictEqual(window.backgroundJobRunning, true); @@ -104,7 +104,7 @@ answer("/r", empty); answer("/j/a", { ...running, state: "succeeded", result: { left_behind: ["/pool/a.one"], warning: "not " } }); assert.ok(el.innerHTML.includes('
  • /pool/a.one
  • '), "shows the warning from the result"); assert.ok(el.innerHTML.includes('
    not <thawed>
    '), "shows the result's warning escaped"); -assert.ok(el.innerHTML.includes('class="alert alert-success') && el.innerHTML.includes('succeeded') +assert.ok(el.innerHTML.includes('class="alert alert-success') && el.innerHTML.includes('succeeded') && el.innerHTML.includes('
    "), "labels and texts of the page's language"); } diff --git a/operations/tests/test_views.py b/operations/tests/test_views.py index 5bc9051b..4c1b1989 100644 --- a/operations/tests/test_views.py +++ b/operations/tests/test_views.py @@ -240,7 +240,7 @@ class JobsPageTestCase(TransactionTestCase): self.client.force_login(self.admin) for response in (self.client.get(reverse("operations:jobs")), self.client.get(reverse("operations:job", args=[self.op.pk]))): - self.assertContains(response, 'failed') + self.assertContains(response, 'failed') detail = self.client.get(reverse("operations:job", args=[self.op.pk])) self.assertContains(detail, 'class="alert alert-danger"') @@ -272,7 +272,7 @@ class JobsPageTestCase(TransactionTestCase): (Operation.UNCERTAIN, False), (Operation.SUCCEEDED, False)): Operation.objects.filter(pk=self.op.pk).update(state=state, worker="" if state == Operation.QUEUED else "h:1:a") response = self.client.get(reverse("operations:jobs")) - (self.assertContains if warned else self.assertNotContains)(response, "Worker unavailable", msg_prefix=state) + (self.assertContains if warned else self.assertNotContains)(response, "The job worker", msg_prefix=state) # a job a request runs does not wait for the worker for state in (Operation.RUNNING, Operation.CANCELLING): Operation.objects.filter(pk=self.op.pk).update(state=state, worker=Operation.REQUEST) @@ -291,7 +291,7 @@ class JobsPageTestCase(TransactionTestCase): self.client.force_login(self.admin) # the app's theme draws white text on bg-warning self.assertContains(self.client.get(reverse("operations:jobs")), - 'uncertain') + 'uncertain') def test_a_narrow_list_shows_resource_and_user_under_the_job(self): Operation.objects.filter(pk=self.op.pk).update(resource_label="wvc-test-host/wvc-test-vm") @@ -325,7 +325,7 @@ class JobsPageTestCase(TransactionTestCase): listed = self.client.get(reverse("operations:jobs")) detail = self.client.get(reverse("operations:job", args=[self.op.pk])) for response in (listed, detail): - self.assertContains(response, 'T[running]') + self.assertContains(response, 'T[running]') self.assertContains(response, "T[Merging the snapshot]") self.assertContains(listed, '') @@ -337,4 +337,4 @@ class JobsPageTestCase(TransactionTestCase): self.assertContains(response, 'aria-valuenow="50"') self.assertContains(response, str(3 * 1024 ** 3)) with patch.object(fakes.NoopKind, "progress_bytes", True): - self.assertContains(self.client.get(url), "3.0\xa0GB / 6.0\xa0GB") + self.assertContains(self.client.get(url), "3\xa0GiB / 6\xa0GiB") diff --git a/static/css/webvirtcloud.css b/static/css/webvirtcloud.css index c960d723..9a315000 100644 --- a/static/css/webvirtcloud.css +++ b/static/css/webvirtcloud.css @@ -279,6 +279,13 @@ button.vcpu-cell:disabled { opacity: .65; } .nic-wire::after { right: -3px; } .nic-wire.nic-up { color: var(--bs-success); border-top-style: solid; } +/* a job state badge starts with a capital, as the VM state badges; the label stays + lowercase for sentences ("… is running on this resource"), and the page's lang + gives Turkish its dotted İ */ +.job-state::first-letter { + text-transform: uppercase; +} + /* a log message keeps a readable width when its table scrolls on a phone */ .log-message { min-width: 16rem; diff --git a/static/js/charts.js b/static/js/charts.js index 13a4078f..a2d6be60 100644 --- a/static/js/charts.js +++ b/static/js/charts.js @@ -10,6 +10,10 @@ var TICK_ROOM = 60; // no thousands separator, as the panel's own pages var PAGE_LANGUAGE = document.documentElement.lang || undefined; var formatNumber = new Intl.NumberFormat(PAGE_LANGUAGE, {maximumFractionDigits: 1, useGrouping: false}).format; +// a percentage as the language writes it: 13% in English, %13 in Turkish +function formatPercent(value) { + return new Intl.NumberFormat(PAGE_LANGUAGE, {style: "percent", maximumFractionDigits: 1}).format(value / 100); +} (function () { var style = getComputedStyle(document.body); @@ -26,6 +30,10 @@ function lineChart(canvas, unit, labels, options) { return style.getPropertyValue(name).trim(); }); options = options || {}; + // a reading with its unit: a percentage as the language writes it + function withUnit(value, text) { + return unit === "%" ? formatPercent(value) : text + " " + unit; + } return new Chart(canvas, { type: "line", data: { @@ -64,7 +72,9 @@ function lineChart(canvas, unit, labels, options) { }, }, // the axis as Chart.js writes it (its precision, the page language), with the unit - y: {min: 0, max: options.max, ticks: {callback: function () { return Chart.Ticks.formatters.numeric.apply(this, arguments) + " " + unit; }}}, + y: {min: 0, max: options.max, ticks: {callback: function (value) { + return withUnit(value, Chart.Ticks.formatters.numeric.apply(this, arguments)); + }}}, }, plugins: { legend: {display: labels.length > 1}, @@ -74,7 +84,7 @@ function lineChart(canvas, unit, labels, options) { return items.length ? labelAt(items[0].chart, items[0].parsed.x) : ""; }, label: function (context) { - var text = context.dataset.label + ": " + context.formattedValue + " " + unit; + var text = context.dataset.label + ": " + withUnit(context.parsed.y, context.formattedValue); return options.tooltip ? options.tooltip(context, text) : text; }, }, diff --git a/static/js/find_address.js b/static/js/find_address.js index 95cacf90..9a471381 100644 --- a/static/js/find_address.js +++ b/static/js/find_address.js @@ -81,7 +81,7 @@ }); table.classList.toggle("d-none", matches.length === 0); if (answer.coverage) { - var readAt = fill(text.readAt, "%(time)s", new Date(answer.read_at).toLocaleTimeString()); + var readAt = fill(text.readAt, "%(time)s", new Date(answer.read_at).toLocaleTimeString(document.documentElement.lang || undefined)); var none = MAC.test(form.elements.q.value.trim()) ? text.noneMac : text.none; coverage.textContent = (matches.length ? "" : none + " ") + coverageText(answer.coverage) + " " + readAt; } else { diff --git a/static/js/host_graphs.js b/static/js/host_graphs.js index e0ef18a0..1f111837 100644 --- a/static/js/host_graphs.js +++ b/static/js/host_graphs.js @@ -50,7 +50,7 @@ pollWhileVisible(5000, function () { stale(); return; } - cpuNow.textContent = formatNumber(data.cpudata) + " %"; + cpuNow.textContent = formatPercent(data.cpudata); lastUpdate = data.timeline; state.textContent = state.dataset.updated.replace("%(time)s", data.timeline); state.classList.remove("text-danger"); diff --git a/static/js/instance_stats.js b/static/js/instance_stats.js index afe94878..c13bdb9b 100644 --- a/static/js/instance_stats.js +++ b/static/js/instance_stats.js @@ -53,7 +53,7 @@ cpuWindows.shift(); } addPoint(cpuChart, data.timeline, [data.cpudata]); - document.getElementById("cpuNow").textContent = reading(data.cpudata) + " %"; + document.getElementById("cpuNow").textContent = data.cpudata == null ? "–" : formatPercent(data.cpudata); // a VM whose memory could not be read gives total 0: a gap, same axis; // the RSS may pass the balloon size: then the axis grows to it if (data.memdata.total) { diff --git a/static/js/new_vm_dialog.js b/static/js/new_vm_dialog.js index c336438a..a5c390e8 100644 --- a/static/js/new_vm_dialog.js +++ b/static/js/new_vm_dialog.js @@ -5,6 +5,9 @@ const addInstance = document.getElementById("AddInstance"); let opening = 0, queue = [], reading = 0; +// a percentage as the page's language writes it: 13% in English, %13 in Turkish +const percentFormat = new Intl.NumberFormat(document.documentElement.lang || undefined, {style: "percent"}); + function setCpuUsage(cell, percent, text) { const meter = cell.querySelector(".progress"); cell.querySelector(".progress-bar").style.width = (percent || 0) + "%"; @@ -23,7 +26,7 @@ function show(element, data) { return; } const usage = data !== null && typeof data.cpudata === "number" ? Math.round(data.cpudata) : null; - setCpuUsage(element, usage, usage === null ? "—" : usage + "%"); + setCpuUsage(element, usage, usage === null ? "—" : percentFormat.format(usage / 100)); } function readNext() { diff --git a/storages/templates/storage.html b/storages/templates/storage.html index 1a9625db..1ca8017b 100644 --- a/storages/templates/storage.html +++ b/storages/templates/storage.html @@ -1,5 +1,6 @@ {% extends "base.html" %} {% load i18n %} +{% load common_tags %} {% load operations %} {% load static %} {% load bootstrap_icons %} @@ -66,9 +67,9 @@ {% elif not size %}
    {% trans "The pool has no size." %}
    {% else %} -
    {{ percent }} %
    +
    {{ percent|percent }}
    - {% blocktrans with used=used|filesizeformat size=size|filesizeformat %}{{ used }} used of {{ size }}{% endblocktrans %} + {% blocktrans with used=used|binary_size size=size|binary_size %}{{ used }} used of {{ size }}{% endblocktrans %} {# what the space is the space of: other pools may share it #} {% if type == "dir" or type == "fs" or type == "netfs" %}· {% trans "the filesystem of its path" %} {% elif type == "logical" %}· {% trans "its volume group" %} @@ -78,7 +79,7 @@ aria-valuenow="{{ percent }}" aria-valuemin="0" aria-valuemax="100">
    -
    {% blocktrans with free=free|filesizeformat %}{{ free }} free{% endblocktrans %}
    +
    {% blocktrans with free=free|binary_size %}{{ free }} free{% endblocktrans %}
    {% endif %}
    @@ -160,8 +161,8 @@ {% endif %} {# capacity: what the guest sees; allocated: what it takes on the storage now #}
    -
    {{ volume.size|filesizeformat }}
    -
    {% blocktrans with allocated=volume.allocation|filesizeformat %}{{ allocated }} allocated{% endblocktrans %}
    +
    {{ volume.size|binary_size }}
    +
    {% blocktrans with allocated=volume.allocation|binary_size %}{{ allocated }} allocated{% endblocktrans %}
    diff --git a/storages/tests/test_pool_page.py b/storages/tests/test_pool_page.py index b38dbee7..5759a8d8 100644 --- a/storages/tests/test_pool_page.py +++ b/storages/tests/test_pool_page.py @@ -234,8 +234,8 @@ class PoolListTests(TestCase): page = html.fromstring(self.client.get(reverse("storages", args=[compute.pk])).content) cards = [" ".join(" ".join(card.itertext()).split()) for card in page.xpath("//div[@class='card h-100']")] self.assertEqual(cards, [ - "default Active Autostart Type dir Path /var/lib/libvirt/images Volumes 3 60 bytes free of 100 bytes", - "ceph-vms Active Type rbd Path vms Volumes 9 5 bytes free of 100 bytes", + "default Active Autostart Type dir Path /var/lib/libvirt/images Volumes 3 60 B free of 100 B", + "ceph-vms Active Type rbd Path vms Volumes 9 5 B free of 100 B", "backup Stopped Type dir Path /srv/backup Volumes – Space unavailable while stopped", ]) self.assertEqual(page.xpath("//div[contains(@class,'progress-bar')]/@class"), diff --git a/vmbackups/templates/vmbackups/index.html b/vmbackups/templates/vmbackups/index.html index 4733efa3..488b3cfd 100644 --- a/vmbackups/templates/vmbackups/index.html +++ b/vmbackups/templates/vmbackups/index.html @@ -1,5 +1,6 @@ {% extends "base.html" %} {% load i18n %} +{% load common_tags %} {% load static %} {% load bootstrap_icons %} {% load django_bootstrap5 %} @@ -67,7 +68,7 @@
    {{ backup.compute_name }}{% if backup.policy %}, {{ backup.policy.name }}{% endif %}
    {% include "vmbackups/consistency.html" %}{% if backup.size %}{{ backup.size|filesizeformat }}{% else %}–{% endif %}{% if backup.size %}{{ backup.size|binary_size }}{% else %}–{% endif %} {% include "vmbackups/state.html" %} {% include "vmbackups/delete_form.html" %}
    {{ backup.created_at|date:"Y-m-d H:i" }} {{ backup.target.name }} {% include "vmbackups/consistency.html" %}{% if backup.size %}{{ backup.size|filesizeformat }}{% else %}–{% endif %}{% if backup.size %}{{ backup.size|binary_size }}{% else %}–{% endif %} {% include "vmbackups/state.html" with pending_deletes=backups.pending_deletes %} {% include "vmbackups/delete_form.html" with pending_deletes=backups.pending_deletes %}