Rename Disks and Snapshots in Configuration tab

- Rename Disks to Storage
- Rename Snapshot to Storage Snapshots

Reviewed-by: Joseph Nuthalapati <njoseph@thoughtworks.com>
This commit is contained in:
abilashr authored and Joseph Nuthalpati committed 2017-09-27 09:39:34 +05:30
1 parent 87001a7cd6
commit 81fde34254
13 files changed
+29 -28

No files matched your search

+132
View File
@@ -0,0 +1,132 @@
#
# This file is part of Plinth.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
"""
Plinth module to manage storage.
"""
from django.utils.translation import ugettext_lazy as _
import logging
import subprocess
import json
from plinth import actions
from plinth.menu import main_menu
version = 1
name = _('Storage')
description = []
service = None
logger = logging.getLogger(__name__)
def init():
"""Intialize the module."""
menu = main_menu.get('system')
menu.add_urlname(name, 'glyphicon-hdd', 'storage:index')
def get_disks():
"""Returns list of disks by combining information from df and lsblk."""
disks_from_df = _get_disks_from_df()
disks_from_lsblk = _get_disks_from_lsblk()
# Combine both sources of info dicts into one dict, based on mount point;
# note this discards disks without a (current) mount point.
combined_list = []
for disk_from_df in disks_from_df:
for disk_from_lsblk in disks_from_lsblk:
if disk_from_df['mount_point'] == disk_from_lsblk['mountpoint']:
disk_from_df.update(disk_from_lsblk)
combined_list.append(disk_from_df)
return combined_list
def _get_disks_from_df():
"""Return the list of disks and free space available using 'df'."""
command = ['df', '--exclude-type=tmpfs', '--exclude-type=devtmpfs',
'--output=source,target,fstype,size,used,pcent',
'--human-readable']
try:
process = subprocess.run(command, stdout=subprocess.PIPE, check=True)
except subprocess.CalledProcessError as exception:
logger.exception('Error getting disk information: %s', exception)
return []
output = process.stdout.decode()
disks = []
for line in output.splitlines()[1:]:
parts = line.split()
keys = ('device', 'mount_point', 'file_system_type', 'size', 'used',
'percentage_used')
disk = dict(zip(keys, parts))
disk['percentage_used'] = int(disk['percentage_used'].rstrip('%'))
disks.append(disk)
return disks
def _get_disks_from_lsblk():
"""Return the list of disks and other information from 'lsblk'."""
command = ['lsblk', '--json', '--output', 'kname,pkname,mountpoint,type']
try:
process = subprocess.run(command, stdout=subprocess.PIPE, check=True)
except subprocess.CalledProcessError as exception:
logger.exception('Error getting disk information: %s', exception)
return []
output = process.stdout.decode()
disks = json.loads(output)['blockdevices']
for disk in disks:
disk['dev_kname'] = '/dev/{0}'.format(disk['kname'])
return disks
def get_root_device(disks):
"""Return the root partition's device from list of partitions."""
devices = [disk['dev_kname'] for disk in disks
if disk['mountpoint'] == '/' and disk['type'] == 'part']
try:
return devices[0]
except IndexError:
return None
def is_expandable(device):
"""Return the list of partitions that can be expanded."""
if not device:
return False
try:
output = actions.superuser_run(
'disks', ['is-partition-expandable', device])
except actions.ActionError:
return False
return int(output.strip())
def expand_partition(device):
"""Expand a partition."""
actions.superuser_run('disks', ['expand-partition', device])
@@ -0,0 +1,106 @@
{% extends "base.html" %}
{% comment %}
#
# This file is part of Plinth.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
{% endcomment %}
{% load bootstrap %}
{% load i18n %}
{% block page_head %}
<style type="text/css">
.progress {
margin-bottom: 0;
}
</style>
{% endblock %}
{% block content %}
<h2>{{ title }}</h2>
<div>{% trans "The following disks are in use:" %}</div>
<div class="row">
<div class="col-lg-12">
<table class="table table-bordered table-condensed table-striped">
<thead>
<tr>
<th>{% trans "Device" %}</th>
<th>{% trans "Mount Point" %}</th>
<th>{% trans "Type" %}</th>
<th>{% trans "Used" %}</th>
</tr>
</thead>
<tbody>
{% for disk in disks %}
<tr>
<td>{{ disk.dev_kname }}</td>
<td>{{ disk.mount_point }}</td>
<td>{{ disk.file_system_type }}</td>
<td>
<div class="progress">
{% if disk.percentage_used < 75 %}
<div class="progress-bar progress-bar-striped progress-bar-success"
{% elif disk.percentage_used < 90 %}
<div class="progress-bar progress-bar-striped progress-bar-warning"
{% else %}
<div class="progress-bar progress-bar-striped progress-bar-danger"
{% endif %}
role="progressbar" aria-valuenow="disk.percentage_used"
aria-valuemin="0" aria-valuemax="100"
style="width: {{ disk.percentage_used }}%;">
{{ disk.percentage_used }}%
</div>
</div>
<div>{{ disk.used }} / {{ disk.size }}</div>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
<h3>{% trans "Partition Expansion" %}</h3>
{% if expandable_root_size %}
<p>
{% blocktrans trimmed %}
There is {{ expandable_root_size }} of unallocated space
available after your root partition. Root partition can be
expanded to use this space. This will provide you additional
free space to store your files.
{% endblocktrans %}
</p>
<p>
<a class="btn btn-primary btn-md" href="{% url 'storage:expand' %}"
role="button">
{% trans "Expand Root Partition" %}</a>
</p>
{% else %}
<p>
{% blocktrans trimmed %}
There is no unallocated space after your root partition.
There is no need to expand it.
{% endblocktrans %}
</p>
<p>
<a class="btn btn-primary btn-md disabled"
href="{% url 'storage:expand' %}" role="button">
{% trans "Expand Root Partition" %}</a>
</p>
{% endif %}
{% endblock %}
@@ -0,0 +1,51 @@
{% extends "base.html" %}
{% comment %}
#
# This file is part of Plinth.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
{% endcomment %}
{% load bootstrap %}
{% load i18n %}
{% block content %}
<h2>{{ title }}</h2>
{% if expandable_root_size %}
<div class="alert alert-danger" role="alert">
<span class="glyphicon glyphicon-exclamation-sign"
aria-hidden="true"></span>
This feature is still in beta. Use at your own risk.
</div>
<p>
{% blocktrans trimmed %}
Please backup your data before proceeding. After this
operation, {{ expandable_root_size }} of additional free space
will be available in your root partition.
{% endblocktrans %}
</p>
<form class="form" method="post">
{% csrf_token %}
<input type="submit" class="btn btn-primary"
value="{% trans "Expand Root Partition" %}"/>
</form>
{% else %}
<p>There are no partitions available to expand.
{% endif %}
{% endblock %}
Whitespace-only changes.
@@ -0,0 +1,243 @@
#
# This file is part of Plinth.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
"""
Test module for storage module operations.
"""
import os
import re
import subprocess
import unittest
euid = os.geteuid()
def _get_partition_device(device, partition_number):
"""Return the device corresponding to a parition in a given device."""
if re.match('[0-9]', device[-1]):
return device + 'p' + str(partition_number)
return device + str(partition_number)
class Disk():
"""Context manager to create/destroy a disk."""
def __init__(self, test_case, size, disk_info, file_system_info=None):
"""Initialize the context manager object."""
self.size = size
self.test_case = test_case
self.disk_info = disk_info
self.file_system_info = file_system_info
self.disk_file = None
self.device = None
def _create_disk_file(self):
"""Create a temporary file to act as a disk."""
directory = os.path.dirname(os.path.realpath(__file__))
disk_file = os.path.join(directory, 'temp_disk.img')
if os.path.isfile(disk_file):
os.remove(disk_file)
command = 'dd if=/dev/zero of={file} bs=1M count={size}' \
.format(size=self.size, file=disk_file)
subprocess.run(command.split(), stderr=subprocess.DEVNULL, check=True)
self.disk_file = disk_file
def _setup_loopback(self):
"""Setup loop back on the create disk file."""
command = 'losetup --show --find {file}'.format(file=self.disk_file)
process = subprocess.run(command.split(), stdout=subprocess.PIPE,
check=True)
device = process.stdout.decode().strip()
subprocess.run(['partprobe', device], check=True)
self.device = device
self.test_case.device = device
def _create_partitions(self):
"""Create partitions as specified in disk_info."""
steps = [step.split() for step in self.disk_info]
command = ['parted', '--align=optimal', '--script', self.disk_file]
for step in steps:
command += step
subprocess.run(command, check=True)
def _create_file_systems(self):
"""Create file systems inside partitions."""
if not self.file_system_info:
return
for partition, file_system_type in self.file_system_info:
device = _get_partition_device(self.device, partition)
if file_system_type == 'btrfs':
command = ['mkfs.btrfs', '-K', device]
else:
command = ['mkfs.ext4', device]
subprocess.run(command, stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL, check=True)
def _cleanup_loopback(self):
"""Undo the loopback device setup."""
subprocess.run(['losetup', '--detach', self.device])
def _remove_disk_file(self):
"""Delete the disk_file."""
os.remove(self.disk_file)
self.disk_file = None
def __enter__(self):
"""Enter the context, create the test disk."""
self._create_disk_file()
self._create_partitions()
self._setup_loopback()
self._create_file_systems()
def __exit__(self, *exc):
"""Exit the context, destroy the test disk."""
self._cleanup_loopback()
self._remove_disk_file()
class TestActions(unittest.TestCase):
"""Test all actions related to storage."""
@unittest.skipUnless(euid == 0, 'Needs to be root')
def test_simple_case(self):
"""Test a simple with no complications"""
disk_info = ['mktable msdos',
'mkpart primary btrfs 1 8',
'mkpart primary btrfs 9 16',
'mkpart primary btrfs 20 200']
with Disk(self, 256, disk_info, [(3, 'btrfs')]):
# No free space
self.assert_free_space(1, space=False)
# < 10 MiB of free space
self.assert_free_space(2, space=False)
self.assert_free_space(3, space=True)
self.expand_partition(1, success=False)
self.expand_partition(2, success=False)
self.expand_partition(3, success=True)
self.expand_partition(3, success=False)
@unittest.skipUnless(euid == 0, 'Needs to be root')
def test_extended_partition_free_space(self):
"""Test that free space does not show up when outside extended."""
disk_info = ['mktable msdos',
'mkpart primary 1 8',
'mkpart extended 8 32',
'mkpart logical 9 16']
with Disk(self, 64, disk_info):
self.assert_free_space(5, space=False)
self.expand_partition(5, success=False)
@unittest.skipUnless(euid == 0, 'Needs to be root')
def test_gpt_partition_free_space(self):
"""Test that GPT partitions can be expanded."""
# Specifically check for partition number > 4
disk_info = ['mktable gpt',
'mkpart primary 1 4',
'mkpart extended 4 8',
'mkpart extended 8 12',
'mkpart extended 12 16',
'mkpart extended 16 160']
with Disk(self, 256, disk_info, [(5, 'btrfs')]):
self.assert_free_space(5, space=True)
self.expand_partition(5, success=True)
self.expand_partition(5, success=False)
@unittest.skipUnless(euid == 0, 'Needs to be root')
def test_unsupported_file_system(self):
"""Test that free space after unknown file system does not count."""
disk_info = ['mktable msdos',
'mkpart primary 1 8']
with Disk(self, 32, disk_info):
self.assert_free_space(1, space=False)
self.expand_partition(1, success=False)
@unittest.skipUnless(euid == 0, 'Needs to be root')
def test_btrfs_expansion(self):
"""Test that btrfs file system can be expanded."""
disk_info = ['mktable msdos',
'mkpart primary btrfs 1 200']
with Disk(self, 256, disk_info, [(1, 'btrfs')]):
self.expand_partition(1, success=True)
self.expand_partition(1, success=False)
self.assert_btrfs_file_system_healthy(1)
@unittest.skipUnless(euid == 0, 'Needs to be root')
def test_ext4_expansion(self):
"""Test that ext4 file system can be expanded."""
disk_info = ['mktable msdos',
'mkpart primary ext4 1 64']
with Disk(self, 128, disk_info, [(1, 'ext4')]):
self.expand_partition(1, success=True)
self.expand_partition(1, success=False)
self.assert_ext4_file_system_healthy(1)
def assert_free_space(self, partition_number, space=True):
"""Verify that free is available/not available after a parition."""
device = _get_partition_device(self.device, partition_number)
result = self.run_action(['storage', 'is-partition-expandable', device])
self.assertEqual(result, space)
def expand_partition(self, partition_number, success=True):
"""Expand a partition."""
self.assert_aligned(partition_number)
device = _get_partition_device(self.device, partition_number)
result = self.run_action(['storage', 'expand-partition', device])
self.assertEqual(result, success)
self.assert_aligned(partition_number)
def run_action(self, action_command):
"""Run an action and return success/failure result."""
current_directory = os.path.dirname(os.path.realpath(__file__))
action = os.path.join(current_directory, '..', '..', '..', '..',
'actions', action_command[0])
action_command[0] = action
try:
subprocess.run(action_command, stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL, check=True)
return True
except subprocess.CalledProcessError:
return False
def assert_aligned(self, partition_number):
"""Test that partition is optimally aligned."""
subprocess.run(['parted', '--script', self.device, 'align-check',
'opti', str(partition_number)])
def assert_btrfs_file_system_healthy(self, partition_number):
"""Perform a successful ext4 file system check."""
device = _get_partition_device(self.device, partition_number)
command = ['btrfs', 'check', device]
subprocess.run(command, stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL, check=True)
def assert_ext4_file_system_healthy(self, partition_number):
"""Perform a successful ext4 file system check."""
device = _get_partition_device(self.device, partition_number)
command = ['e2fsck', '-n', device]
subprocess.run(command, stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL, check=True)
+30
View File
@@ -0,0 +1,30 @@
#
# This file is part of Plinth.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
"""
URLs for the disks module.
"""
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^sys/storage/$', views.index, name='index'),
url(r'^sys/storage/expand$', views.expand, name='expand'),
]
+145
View File
@@ -0,0 +1,145 @@
#
# This file is part of Plinth.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
"""
Views for storage module.
"""
import logging
from django.contrib import messages
from django.shortcuts import redirect
from django.template.response import TemplateResponse
from django.urls import reverse
from django.utils.translation import ugettext as _
from plinth.modules import storage as storage_module
from plinth.utils import format_lazy, is_user_admin
logger = logging.getLogger(__name__)
def index(request):
"""Show connection list."""
disks = storage_module.get_disks()
root_device = storage_module.get_root_device(disks)
expandable_root_size = storage_module.is_expandable(root_device)
expandable_root_size = _format_bytes(expandable_root_size)
warn_about_low_disk_space(request)
return TemplateResponse(request, 'storage.html',
{'title': _('Storage'),
'disks': disks,
'expandable_root_size': expandable_root_size})
def expand(request):
"""Warn and expand the root partition."""
disks = storage_module.get_disks()
root_device = storage_module.get_root_device(disks)
if request.method == 'POST':
expand_partition(request, root_device)
return redirect(reverse('storage:index'))
expandable_root_size = storage_module.is_expandable(root_device)
expandable_root_size = _format_bytes(expandable_root_size)
return TemplateResponse(request, 'storage_expand.html',
{'title': _('Expand Root Partition'),
'expandable_root_size': expandable_root_size})
def expand_partition(request, device):
"""Expand the partition."""
try:
storage_module.expand_partition(device)
except Exception as exception:
messages.error(request, _('Error expanding partition: {exception}')
.format(exception=exception))
else:
messages.success(request, _('Partition expanded successfully.'))
def warn_about_low_disk_space(request):
"""Warn about insufficient space on root partition."""
if not is_user_admin(request, cached=True):
return
disks = storage_module.get_disks()
list_root = [disk for disk in disks if disk['mountpoint'] == '/']
if not list_root:
logger.error('Error getting information about root partition.')
return
perc_used = list_root[0]['percentage_used']
size_bytes = _interpret_size_string(list_root[0]['size'])
free_bytes = size_bytes * (100 - perc_used) / 100
message = format_lazy(
_('Warning: Low space on system partition ({percent_used}% used, '
'{free_space} free).'),
percent_used=perc_used, free_space=_format_bytes(free_bytes))
free_gib = free_bytes / (1024 ** 3)
if perc_used > 90 or free_gib < 1:
messages.error(request, message)
elif perc_used > 75 or free_gib < 2:
messages.warning(request, message)
def _interpret_size_string(size_str):
"""Convert size string to number of bytes."""
if size_str[-1] in '0123456789':
return float(size_str[:-1])
if size_str[-1] == 'K':
return float(size_str[:-1]) * 1024
if size_str[-1] == 'M':
return float(size_str[:-1]) * 1024 ** 2
if size_str[-1] == 'G':
return float(size_str[:-1]) * 1024 ** 3
if size_str[-1] == 'T':
return float(size_str[:-1]) * 1024 ** 4
return -1
def _format_bytes(size):
"""Return human readable disk size from bytes."""
if not size:
return size
if size < 1024:
return _('{disk_size:.1f} bytes').format(disk_size=size)
if size < 1024 ** 2:
size /= 1024
return _('{disk_size:.1f} KiB').format(disk_size=size)
if size < 1024 ** 3:
size /= 1024 ** 2
return _('{disk_size:.1f} MiB').format(disk_size=size)
if size < 1024 ** 4:
size /= 1024 ** 3
return _('{disk_size:.1f} GiB').format(disk_size=size)
size /= 1024 ** 4
return _('{disk_size:.1f} TiB').format(disk_size=size)