Commit 8db3512f by Szeberényi Imre

Node capab & Bottom group actions added

parent 4ba5ef6b
...@@ -480,6 +480,19 @@ class NodeForm(forms.ModelForm): ...@@ -480,6 +480,19 @@ class NodeForm(forms.ModelForm):
css_class="row", css_class="row",
), ),
Div( Div(
Div( # compability_group
HTML('<label for="id_compatibility_group">'
'Compatibility group'
'</label>'),
css_class="col-sm-3",
),
Div(
'compatibility_group',
css_class="col-sm-9",
),
css_class="row",
),
Div(
Div( # enabled Div( # enabled
HTML('<label for="node-nodename-box">' HTML('<label for="node-nodename-box">'
'Enabled' 'Enabled'
...@@ -521,7 +534,7 @@ class NodeForm(forms.ModelForm): ...@@ -521,7 +534,7 @@ class NodeForm(forms.ModelForm):
class Meta: class Meta:
model = Node model = Node
fields = ['name', 'priority', 'enabled', ] fields = ['name', 'priority', 'enabled', 'compatibility_group']
class TemplateForm(forms.ModelForm): class TemplateForm(forms.ModelForm):
......
...@@ -837,7 +837,7 @@ textarea[name="new_members"] { ...@@ -837,7 +837,7 @@ textarea[name="new_members"] {
font-size: 0.8em; font-size: 0.8em;
} }
#vm-list-search, #vm-list-search,
#vm-mass-ops { .vm-mass-ops {
margin-top: 8px; margin-top: 8px;
} }
.list-group-item { .list-group-item {
......
...@@ -279,6 +279,13 @@ $(function () { ...@@ -279,6 +279,13 @@ $(function () {
return true; return true;
$('#vm-migrate-node-list li').removeClass('panel-primary'); $('#vm-migrate-node-list li').removeClass('panel-primary');
li.addClass('panel-primary').find('input').prop("checked", true); li.addClass('panel-primary').find('input').prop("checked", true);
// Mass migration scheduling warnings
var node = li.find('input').val();
li.closest('form').find('.mass-migrate-warning').each(function() {
var suitable = $(this).attr('data-suitable-nodes').split(',');
$(this).toggle(!!node && suitable.indexOf(node) === -1);
});
return true; return true;
}); });
}); });
......
...@@ -409,7 +409,11 @@ a.hover-black { ...@@ -409,7 +409,11 @@ a.hover-black {
} }
#vm-migrate-node-list li { #vm-migrate-node-list li {
padding-bottom: 10px; padding-bottom: 0px;
}
#vm-migrate-node-list .panel-body {
padding: 8px 15px;
} }
.vm-migrate-node-property { .vm-migrate-node-property {
...@@ -957,7 +961,7 @@ textarea[name="new_members"] { ...@@ -957,7 +961,7 @@ textarea[name="new_members"] {
font-size: .8em; font-size: .8em;
} }
#vm-list-search, #vm-mass-ops { #vm-list-search, .vm-mass-ops {
margin-top: 8px; margin-top: 8px;
} }
...@@ -1613,4 +1617,4 @@ textarea[name="new_members"] { ...@@ -1613,4 +1617,4 @@ textarea[name="new_members"] {
position: absolute; position: absolute;
width: 95%; width: 95%;
height: 150px; height: 150px;
} }
\ No newline at end of file
...@@ -49,9 +49,9 @@ $(function() { ...@@ -49,9 +49,9 @@ $(function() {
// show/hide group controls // show/hide group controls
if(selected.length > 0) { if(selected.length > 0) {
$('#vm-mass-ops .mass-operation').attr('disabled', false); $('.vm-mass-ops .mass-operation').attr('disabled', false);
} else { } else {
$('#vm-mass-ops .mass-operation').attr('disabled', true); $('.vm-mass-ops .mass-operation').attr('disabled', true);
} }
return retval; return retval;
}); });
...@@ -64,7 +64,7 @@ $(function() { ...@@ -64,7 +64,7 @@ $(function() {
/* group actions */ /* group actions */
/* select all */ /* select all */
$('#vm-list-group-select-all').click(function() { $('.vm-list-group-select-all').click(function() {
$('.vm-list-table tbody tr').each(function() { $('.vm-list-table tbody tr').each(function() {
var index = $(this).index(); var index = $(this).index();
var vm = $(this).data("vm-pk"); var vm = $(this).data("vm-pk");
...@@ -74,13 +74,13 @@ $(function() { ...@@ -74,13 +74,13 @@ $(function() {
} }
}); });
if(selected.length > 0) if(selected.length > 0)
$('#vm-mass-ops .mass-operation').attr('disabled', false); $('.vm-mass-ops .mass-operation').attr('disabled', false);
return false; return false;
}); });
/* mass operations */ /* mass operations */
$("#vm-mass-ops").on('click', '.mass-operation', function(e) { $(".vm-mass-ops").on('click', '.mass-operation', function(e) {
var icon = $(this).children("i").addClass('fa-spinner fa-spin'); var icon = $(this).children("i").addClass('fa-spinner fa-spin');
params = "?" + selected.map(function(a){return "vm=" + a.vm;}).join("&"); params = "?" + selected.map(function(a){return "vm=" + a.vm;}).join("&");
......
...@@ -24,10 +24,21 @@ ...@@ -24,10 +24,21 @@
<div class="panel-body"> <div class="panel-body">
<label for="migrate-to-{{n.pk}}"> <label for="migrate-to-{{n.pk}}">
<strong>{{ n }}</strong> <strong>{{ n }}</strong>
<div class="label label-primary">
<i class="fa {{n.get_status_icon}}"></i> {{n.get_status_display}}</div>
</label> </label>
<input id="migrate-to-{{n.pk}}" type="radio" name="to_node" value="{{ n.pk }}" style="float: right;"/> <input id="migrate-to-{{n.pk}}" type="radio" name="to_node" value="{{ n.pk }}" style="float: right;"/>
<span class="vm-migrate-node-property">{% trans "CPU load" %}: {{ n.cpu_usage }}</span> <span class="vm-migrate-node-property">
<span class="vm-migrate-node-property">{% trans "RAM usage" %}: {{ n.byte_ram_usage|filesize }}/{{ n.ram_size|filesize }}</span> {% trans "CPU load" %}: {{ n.cpu_usage }}
<span class="text-muted">&nbsp;|&nbsp;</span>
{% trans "RAM usage" %}: {{ n.byte_ram_usage|filesize }} / {{ n.ram_size|filesize }}
</span>
<span class="vm-migrate-node-property">
{% trans "Compatibility group" %}: {{ n.compatibility_group|default:"-" }}
</span>
<span class="vm-migrate-node-property">
{% trans "Traits" %}: {% if n.traits.all %} {{ n.traits.all|join:", " }} {% else %} - {% endif %}
</span>
<div style="clear: both;"></div> <div style="clear: both;"></div>
</div> </div>
</li> </li>
......
...@@ -26,35 +26,30 @@ Choose a compute node to migrate {{obj}} to. ...@@ -26,35 +26,30 @@ Choose a compute node to migrate {{obj}} to.
{% if n.pk not in nodes_w_traits %} {% if n.pk not in nodes_w_traits %}
<div class="label label-warning"> <div class="label label-warning">
<i class="fa fa-warning"></i> <i class="fa fa-warning"></i>
{% trans "missing traits" %}</div> {% trans "Placement mismatch" %}</div>
{% endif %} {% endif %}
</label> </label>
<input id="migrate-to-{{n.pk}}" type="radio" name="to_node" value="{{ n.pk }}" style="float: right;" <input id="migrate-to-{{n.pk}}" type="radio" name="to_node" value="{{ n.pk }}" style="float: right;"
{% if current == n.pk %}disabled="disabled"{% endif %} {% if current == n.pk %}disabled="disabled"{% endif %}
{% if recommended == n.pk and n.pk != current %}checked="checked"{% endif %} {% if recommended == n.pk and n.pk != current %}checked="checked"{% endif %}
/> />
{% if n.pk not in nodes_w_traits %}
<span class="vm-migrate-node-property">
{% trans "Node traits" %}:
{% if n.traits.all %}
{{ n.traits.all|join:", " }}
{% else %}
-
{% endif %}
</span>
<span class="vm-migrate-node-property">
{% trans "Required traits" %}:
{% if object.req_traits.all %}
{{ object.req_traits.all|join:", " }}
{% else %}
-
{% endif %}
</span>
<hr />
{% endif %}
<span class="vm-migrate-node-property">{% trans "CPU load" %}: {{ n.cpu_usage }}</span>
<span class="vm-migrate-node-property"> <span class="vm-migrate-node-property">
{% trans "RAM usage" %}: {{ n.byte_ram_usage|filesize }}/{{ n.ram_size|filesize }}</span> {% trans "CPU load" %}: {{ n.cpu_usage }}
<span class="text-muted">&nbsp;|&nbsp;</span>
{% trans "RAM usage" %}: {{ n.byte_ram_usage|filesize }} / {{ n.ram_size|filesize }}
</span>
<span class="vm-migrate-node-property">
{% trans "Compatibility group" %}: {{ n.compatibility_group|default:"-" }}
<span class="text-muted">
({% trans "required" %}: {{ object.runtime_compatibility_group|default:"-" }})
</span>
</span>
<span class="vm-migrate-node-property">
{% trans "Traits" %}: {% if n.traits.all %} {{ n.traits.all|join:", " }} {% else %} - {% endif %}
<span class="text-muted">
({% trans "required" %}: {% if object.req_traits.all %} {{ object.req_traits.all|join:", " }} {% else %} - {% endif %})
</span>
</span>
<div style="clear: both;"></div> <div style="clear: both;"></div>
</li> </li>
{% endfor %} {% endfor %}
......
...@@ -17,6 +17,26 @@ Do you want to perform the <strong>{{op}}</strong> operation on the following {{ ...@@ -17,6 +17,26 @@ Do you want to perform the <strong>{{op}}</strong> operation on the following {{
<div class="panel panel-default mass-op-panel"> <div class="panel panel-default mass-op-panel">
<i class="fa {{ i.get_status_icon }} fa-fw"></i> <i class="fa {{ i.get_status_icon }} fa-fw"></i>
{{ i.name }} ({{ i.pk }}) {{ i.name }} ({{ i.pk }})
{% if opview.op == "migrate" %}
{% if not i.disabled %}
<span class="mass-migrate-warning text-warning"
data-suitable-nodes="{{ i.suitable_nodes|join:',' }}"
style="display: none;"
title="{% trans 'Placement mismatch' %}">
<i class="fa fa-warning"></i>
</span>
{% endif %}
<small class="text-muted">
<span class="text-muted">&nbsp;|&nbsp;</span>
{% trans "Runtime compatibility group" %}:
{{ i.runtime_compatibility_group|default:"-" }}
<span class="text-muted">&nbsp;|&nbsp;</span>
{% trans "Req. traits" %}:
{{ i.req_traits.all|join:", "|default:"-" }}
</small>
{% endif %}
<div style="float: right;" title="{{ i.disabled }}" class="status-icon"> <div style="float: right;" title="{{ i.disabled }}" class="status-icon">
<span class="fa-stack"> <span class="fa-stack">
<i class="fa fa-stack-2x fa-square {{ i.disabled|yesno:"minus,check" }}"></i> <i class="fa fa-stack-2x fa-square {{ i.disabled|yesno:"minus,check" }}"></i>
......
...@@ -9,7 +9,52 @@ ...@@ -9,7 +9,52 @@
<dt>{% trans "Host IP" %}:</dt><dd>{{ node.host.ipv4 }}</dd> <dt>{% trans "Host IP" %}:</dt><dd>{{ node.host.ipv4 }}</dd>
<dt>{% trans "Enabled" %}:</dt><dd>{{ node.enabled|yesno }}</dd> <dt>{% trans "Enabled" %}:</dt><dd>{{ node.enabled|yesno }}</dd>
<dt>{% trans "Host online" %}:</dt><dd> {{ node.online|yesno }}</dd> <dt>{% trans "Host online" %}:</dt><dd> {{ node.online|yesno }}</dd>
<dt>{% trans "Priority" %}:</dt><dd>{{ node.priority }}</dd> <dt>{% trans "Priority" %}:</dt>
<dd>
{% if request.user.is_superuser %}
<form method="post" class="form-inline">
{% csrf_token %}
<div class="input-group input-group-sm">
<input type="number"
name="priority"
class="form-control"
value="{{ node.priority }}"
required>
<span class="input-group-btn">
<button type="submit" class="btn btn-default"
title="{% trans 'Save' %}">
<i class="fa fa-save"></i>
</button>
</span>
</div>
</form>
{% else %}
{{ node.priority }}
{% endif %}
</dd>
<dt>{% trans "Compatibility group" %}:</dt>
<dd>
{% if request.user.is_superuser %}
<form method="post" class="form-inline">
{% csrf_token %}
<div class="input-group input-group-sm">
<input type="text"
name="compatibility_group"
class="form-control"
maxlength="20"
value="{{ node.compatibility_group|default_if_none:'' }}">
<span class="input-group-btn">
<button type="submit" class="btn btn-default"
title="{% trans 'Save' %}">
<i class="fa fa-save"></i>
</button>
</span>
</div>
</form>
{% else %}
{{ node.compatibility_group|default:"-" }}
{% endif %}
</dd>
<dt>{% trans "Driver Version:" %}</dt> <dt>{% trans "Driver Version:" %}</dt>
<dd> <dd>
{% if node.driver_version %} {% if node.driver_version %}
......
...@@ -19,16 +19,7 @@ ...@@ -19,16 +19,7 @@
</div> </div>
<div class="panel-body"> <div class="panel-body">
<div class="row"> <div class="row">
<div class="col-md-8 vm-list-group-control" id="vm-mass-ops"> {% include "dashboard/vm-list/group-actions.html" %}
<strong>{% trans "Group actions" %}</strong>
<button id="vm-list-group-select-all" class="btn btn-info btn-xs">{% trans "Select all" %}</button>
{% for o in ops %}
<a href="{{ o.get_url }}" class="btn btn-xs btn-{{ o.effect }} mass-operation"
title="{{ o.name|capfirst }}" disabled>
<i class="fa fa-{{ o.icon }}"></i>
</a>
{% endfor %}
</div><!-- .vm-list-group-control -->
<div class="col-md-4" id="vm-list-search"> <div class="col-md-4" id="vm-list-search">
<form action="" method="GET"> <form action="" method="GET">
<div class="input-group"> <div class="input-group">
...@@ -144,6 +135,13 @@ ...@@ -144,6 +135,13 @@
</table> </table>
</div><!-- .table-responsive --> </div><!-- .table-responsive -->
</div> </div>
<div class="panel-footer">
<div class="row">
{% include "dashboard/vm-list/group-actions.html" %}
</div>
</div>
</div> </div>
</div> </div>
</div> </div>
......
{% load i18n %}
<div class="col-md-8 vm-list-group-control vm-mass-ops">
<strong>{% trans "Group actions" %}</strong>
<button class="btn btn-info btn-xs vm-list-group-select-all">
{% trans "Select all" %}
</button>
{% for o in ops %}
<a href="{{ o.get_url }}"
class="btn btn-xs btn-{{ o.effect }} mass-operation"
title="{{ o.name|capfirst }}" disabled>
<i class="fa fa-{{ o.icon }}"></i>
</a>
{% endfor %}
</div>
...@@ -21,7 +21,7 @@ from collections import OrderedDict ...@@ -21,7 +21,7 @@ from collections import OrderedDict
from django.conf import settings from django.conf import settings
from django.contrib import messages from django.contrib import messages
from django.core.exceptions import PermissionDenied from django.core.exceptions import PermissionDenied, ValidationError
from django.urls import reverse_lazy from django.urls import reverse_lazy
from django.db.models import Count from django.db.models import Count
from django.forms.models import inlineformset_factory from django.forms.models import inlineformset_factory
...@@ -193,6 +193,10 @@ class NodeDetailView(LoginRequiredMixin, ...@@ -193,6 +193,10 @@ class NodeDetailView(LoginRequiredMixin,
raise PermissionDenied() raise PermissionDenied()
if request.POST.get('new_name'): if request.POST.get('new_name'):
return self.__set_name(request) return self.__set_name(request)
if 'compatibility_group' in request.POST:
return self.__set_compatibility_group(request)
if 'priority' in request.POST:
return self.__set_priority(request)
if request.POST.get('to_remove'): if request.POST.get('to_remove'):
return self.__remove_trait(request) return self.__remove_trait(request)
return redirect(reverse_lazy("dashboard.views.node-detail", return redirect(reverse_lazy("dashboard.views.node-detail",
...@@ -242,6 +246,32 @@ class NodeDetailView(LoginRequiredMixin, ...@@ -242,6 +246,32 @@ class NodeDetailView(LoginRequiredMixin,
else: else:
return redirect(node.get_absolute_url()) return redirect(node.get_absolute_url())
def __set_compatibility_group(self, request):
node = self.get_object()
group = request.POST.get('compatibility_group', '').strip()
if len(group) > 20:
messages.error(request, _("Compatibility group is too long."))
else:
node.compatibility_group = group or None
node.save(update_fields=['compatibility_group'])
messages.success(request, _("Compatibility group updated."))
return redirect(node.get_absolute_url())
def __set_priority(self, request):
node = self.get_object()
try:
priority = int(request.POST.get('priority', ''))
node.priority = priority
node.full_clean()
node.save(update_fields=['priority'])
messages.success(request, _("Priority updated."))
except (ValueError, ValidationError):
messages.error(request, _("Invalid priority."))
return redirect(node.get_absolute_url())
class NodeList(LoginRequiredMixin, GraphMixin, SingleTableView): class NodeList(LoginRequiredMixin, GraphMixin, SingleTableView):
template_name = "dashboard/node-list.html" template_name = "dashboard/node-list.html"
......
...@@ -83,7 +83,7 @@ from django.views.generic.edit import FormMixin ...@@ -83,7 +83,7 @@ from django.views.generic.edit import FormMixin
from request.models import TemplateAccessType, LeaseType from request.models import TemplateAccessType, LeaseType
from request.forms import LeaseRequestForm, TemplateRequestForm from request.forms import LeaseRequestForm, TemplateRequestForm
from ..models import Favourite, pwgen from ..models import Favourite, pwgen
from manager.scheduler import has_traits from manager.scheduler import has_traits, common_select
import re import re
...@@ -935,9 +935,9 @@ class VmMigrateView(FormOperationMixin, VmOperationView): ...@@ -935,9 +935,9 @@ class VmMigrateView(FormOperationMixin, VmOperationView):
inst = self.get_object() inst = self.get_object()
try: try:
if isinstance(inst, Instance): if isinstance(inst, Instance):
default = inst.select_node() default = inst.select_node(excl=inst.node, preserve_runtime=True)
except SchedulerError: except SchedulerError:
logger.exception("scheduler error:") logger.debug("No suitable migration target.")
val = super(VmMigrateView, self).get_form_kwargs() val = super(VmMigrateView, self).get_form_kwargs()
val.update({'choices': choices, 'default': default}) val.update({'choices': choices, 'default': default})
...@@ -948,10 +948,16 @@ class VmMigrateView(FormOperationMixin, VmOperationView): ...@@ -948,10 +948,16 @@ class VmMigrateView(FormOperationMixin, VmOperationView):
inst = self.get_object() inst = self.get_object()
if isinstance(inst, Instance): if isinstance(inst, Instance):
nodes_w_traits = [ try:
n.pk for n in Node.objects.filter(enabled=True) nodes_w_traits = [
if n.online and has_traits(inst.req_traits.all(), n) n.pk for n in common_select(
] inst,
Node.objects.filter(enabled=True),
preserve_runtime=True)
]
except SchedulerError:
nodes_w_traits = []
ctx['nodes_w_traits'] = nodes_w_traits ctx['nodes_w_traits'] = nodes_w_traits
return ctx return ctx
...@@ -1445,6 +1451,25 @@ class MassOperationView(OperationView): ...@@ -1445,6 +1451,25 @@ class MassOperationView(OperationView):
class MassMigrationView(MassOperationView, VmMigrateView): class MassMigrationView(MassOperationView, VmMigrateView):
template_name = 'dashboard/_vm-mass-migrate.html' template_name = 'dashboard/_vm-mass-migrate.html'
def get_context_data(self, **kwargs):
ctx = super(MassMigrationView, self).get_context_data(**kwargs)
nodes = list(Node.objects.filter(enabled=True))
for inst in ctx['instances']:
inst.suitable_nodes = []
if not inst.disabled:
try:
inst.suitable_nodes = [
n.pk for n in common_select(
inst, nodes, preserve_runtime=True)
if n.pk != inst.node_id
]
except SchedulerError:
pass
return ctx
vm_mass_ops = OrderedDict([ vm_mass_ops = OrderedDict([
('deploy', MassOperationView.factory(vm_ops['deploy'])), ('deploy', MassOperationView.factory(vm_ops['deploy'])),
......
...@@ -53,15 +53,23 @@ class NotEnoughMemoryException(SchedulerError): ...@@ -53,15 +53,23 @@ class NotEnoughMemoryException(SchedulerError):
class TraitsUnsatisfiableException(SchedulerError): class TraitsUnsatisfiableException(SchedulerError):
message = gettext_noop( message = gettext_noop(
"No node can satisfy the required traits of the " "No node can satisfy the placement requirements "
"new virtual machine currently.") "of the virtual machine.")
def common_select(instance, nodes): def common_select(instance, nodes, preserve_runtime=False):
# check required traits # check required traits
nodes = [n for n in nodes nodes = [n for n in nodes
if n.schedule_enabled and n.online and if n.schedule_enabled and n.online and
has_traits(instance.req_traits.all(), n)] has_traits(instance.req_traits.all(), n)]
# check runtime compability
if preserve_runtime:
nodes = [
n for n in nodes
if (n.compatibility_group or "") ==
(instance.runtime_compatibility_group or "")
]
if not nodes: if not nodes:
logger.warning('select_node: no usable node for %s', str(instance)) logger.warning('select_node: no usable node for %s', str(instance))
raise TraitsUnsatisfiableException() raise TraitsUnsatisfiableException()
...@@ -76,22 +84,19 @@ def common_select(instance, nodes): ...@@ -76,22 +84,19 @@ def common_select(instance, nodes):
nodes.sort(key=lambda n: n.priority, reverse=True) nodes.sort(key=lambda n: n.priority, reverse=True)
return nodes return nodes
def common_evenly(instance, nodes, preserve_runtime=False):
def common_evenly(instance, nodes): nodes = common_select(instance, nodes, preserve_runtime)
nodes = common_select(instance, nodes)
nodes.sort(key=free_cpu_time, reverse=True) nodes.sort(key=free_cpu_time, reverse=True)
result = nodes[0] result = nodes[0]
return result return result
def common_random(instance, nodes, preserve_runtime=False):
def common_random(instance, nodes): nodes = common_select(instance, nodes, preserve_runtime)
nodes = common_select(instance, nodes)
result = random.choice(nodes) result = random.choice(nodes)
return result return result
def advanced_with_time_stamp(instance, nodes, preserve_runtime=False):
def advanced_with_time_stamp(instance, nodes): nodes = common_select(instance, nodes, preserve_runtime)
nodes = common_select(instance, nodes)
nodes.sort(key=sorting_key, reverse=True) nodes.sort(key=sorting_key, reverse=True)
logger.info("SCHEDLOG: {}".format(json.dumps({ logger.info("SCHEDLOG: {}".format(json.dumps({
"event": "after_sort", "event": "after_sort",
...@@ -100,23 +105,21 @@ def advanced_with_time_stamp(instance, nodes): ...@@ -100,23 +105,21 @@ def advanced_with_time_stamp(instance, nodes):
return result return result
def select_node(instance, nodes): def select_node(instance, nodes, preserve_runtime=False):
''' Select a node for hosting an instance based on its requirements. ''' Select a node for hosting an instance based on its requirements.
''' '''
if SCHEDULER_METHOD == 'evenly': if SCHEDULER_METHOD == 'evenly':
result = common_evenly(instance, nodes) result = common_evenly(instance, nodes, preserve_runtime)
elif SCHEDULER_METHOD == 'random': elif SCHEDULER_METHOD == 'random':
result = common_random(instance, nodes) result = common_random(instance, nodes, preserve_runtime)
elif SCHEDULER_METHOD == 'advanced': elif SCHEDULER_METHOD == 'advanced':
result = advanced_with_time_stamp(instance, nodes) result = advanced_with_time_stamp(instance, nodes, preserve_runtime)
else: # Default method is the random else: # Default method is the random
result = common_random(instance, nodes) result = common_random(instance, nodes, preserve_runtime)
logger.info("SCHEDLOG: {}".format(json.dumps( logger.info("SCHEDLOG: {}".format(json.dumps(
{"event": "select", {"event": "select",
"node": str(result), "node": str(result),
"vm": str(instance)}))) "vm": str(instance)})))
set_time_stamp(result) set_time_stamp(result)
return result return result
......
from types import SimpleNamespace
from unittest import TestCase
from unittest.mock import Mock, MagicMock, patch
from manager import scheduler
class CompatibilityTestCase(TestCase):
def setUp(self):
self.instance = Mock()
self.instance.runtime_compatibility_group = None
self.nodes = [
self.make_node("legacy1", None),
self.make_node("legacy2", ""),
self.make_node("new1", "new"),
self.make_node("new2", "new"),
self.make_node("other1", "other"),
]
@staticmethod
def make_node(name, group):
return SimpleNamespace(
name=name,
compatibility_group=group,
schedule_enabled=True,
online=True,
priority=0,
)
def select(self, preserve_runtime=False):
with patch.object(scheduler, "has_traits", return_value=True):
with patch.object(scheduler, "has_enough_ram",
return_value=True):
return scheduler.common_select(
self.instance,
self.nodes,
preserve_runtime=preserve_runtime,
)
def test_normal_deploy(self):
self.assertEqual(self.select(), self.nodes)
def test_normal_deploy_with_previous_group(self):
self.instance.runtime_compatibility_group = "new"
self.assertEqual(self.select(), self.nodes)
def test_preserve_runtime_null_group(self):
self.instance.runtime_compatibility_group = None
self.assertEqual(
self.select(preserve_runtime=True),
self.nodes[:2],
)
def test_preserve_runtime_empty_group(self):
self.instance.runtime_compatibility_group = ""
self.assertEqual(
self.select(preserve_runtime=True),
self.nodes[:2],
)
def test_preserve_runtime_named_group(self):
self.instance.runtime_compatibility_group = "new"
self.assertEqual(
self.select(preserve_runtime=True),
self.nodes[2:4],
)
def test_no_compatible_node(self):
self.instance.runtime_compatibility_group = "unknown"
with self.assertRaises(
scheduler.TraitsUnsatisfiableException):
self.select(preserve_runtime=True)
def test_offline_compatible_node(self):
self.instance.runtime_compatibility_group = "new"
self.nodes[2].online = False
self.assertEqual(
self.select(preserve_runtime=True),
[self.nodes[3]],
)
def test_disabled_compatible_node(self):
self.instance.runtime_compatibility_group = "new"
self.nodes[2].schedule_enabled = False
self.assertEqual(
self.select(preserve_runtime=True),
[self.nodes[3]],
)
# Generated by Django 4.2.30 on 2026-11-28 14:16
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('vm', '0019_alter_instancetemplate_overlay_path'),
]
operations = [
migrations.AddField(
model_name='instance',
name='runtime_compatibility_group',
field=models.CharField(blank=True, db_column='capability_group', help_text='Compatibility group required to preserve the current runtime state of the instance.', max_length=20, null=True, verbose_name='Runtime compatibility group'),
),
migrations.AddField(
model_name='node',
name='compatibility_group',
field=models.CharField(blank=True, db_column='capability', help_text='Compatibility group of the node.', max_length=20, null=True, verbose_name='Compatibility group'),
),
]
...@@ -386,6 +386,15 @@ class Instance(AclBase, VirtualMachineDescModel, StatusModel, OperatedMixin, ...@@ -386,6 +386,15 @@ class Instance(AclBase, VirtualMachineDescModel, StatusModel, OperatedMixin,
destroyed_at = DateTimeField(blank=True, null=True, destroyed_at = DateTimeField(blank=True, null=True,
help_text=_("The virtual machine's time of " help_text=_("The virtual machine's time of "
"destruction.")) "destruction."))
runtime_compatibility_group = CharField(
max_length=20, blank=True, null=True,
db_column='capability_group',
help_text=_(
"Compatibility group required to preserve "
"the current runtime state of the instance."
),
verbose_name=_("Runtime compatibility group"),
)
objects = Manager() objects = Manager()
active = QueryManager(destroyed_at=None) active = QueryManager(destroyed_at=None)
...@@ -985,10 +994,14 @@ class Instance(AclBase, VirtualMachineDescModel, StatusModel, OperatedMixin, ...@@ -985,10 +994,14 @@ class Instance(AclBase, VirtualMachineDescModel, StatusModel, OperatedMixin,
timezone.now() + lease.suspend_interval, timezone.now() + lease.suspend_interval,
timezone.now() + lease.delete_interval) timezone.now() + lease.delete_interval)
def select_node(self): def select_node(self, excl=None, preserve_runtime=False):
"""Returns the node the VM should be deployed or migrated to. """Returns the node the VM should be deployed or migrated to.
""" """
return scheduler.select_node(self, Node.objects.all()) nodes = Node.objects.all()
if excl is not None:
nodes = nodes.exclude(pk=excl.pk)
return scheduler.select_node(
self, nodes, preserve_runtime=preserve_runtime)
def destroy_disks(self): def destroy_disks(self):
"""Destroy all associated disks. """Destroy all associated disks.
...@@ -1014,16 +1027,19 @@ class Instance(AclBase, VirtualMachineDescModel, StatusModel, OperatedMixin, ...@@ -1014,16 +1027,19 @@ class Instance(AclBase, VirtualMachineDescModel, StatusModel, OperatedMixin,
for net in self.interface_set.all(): for net in self.interface_set.all():
net.shutdown() net.shutdown()
def allocate_node(self): def allocate_node(self, preserve_runtime=False):
if self.node is None: if self.node is None:
self.node = self.select_node() self.node = self.select_node(preserve_runtime=preserve_runtime)
self.save() if not preserve_runtime:
return self.node self.runtime_compatibility_group = self.node.compatibility_group
self.save()
def yield_node(self): return self.node
if self.node is not None:
self.node = None def yield_node(self, preserve_runtime=False):
self.save() self.node = None
# if not preserve_runtime:
# self.runtime_compatibility_group = None
self.save()
def allocate_vnc_port(self): def allocate_vnc_port(self):
if self.vnc_port is None: if self.vnc_port is None:
......
...@@ -160,6 +160,12 @@ class Node(OperatedMixin, TimeStampedModel): ...@@ -160,6 +160,12 @@ class Node(OperatedMixin, TimeStampedModel):
help_text=_("A timestamp for the node, used by the scheduler."), help_text=_("A timestamp for the node, used by the scheduler."),
verbose_name=_("Last Scheduled Time Stamp") verbose_name=_("Last Scheduled Time Stamp")
) )
compatibility_group = CharField(
max_length=20, blank=True, null=True,
db_column='capability',
help_text=_("Compatibility group of the node."),
verbose_name=_("Compatibility group"),
)
class Meta: class Meta:
app_label = 'vm' app_label = 'vm'
......
...@@ -473,6 +473,7 @@ class DeployOperation(InstanceOperation): ...@@ -473,6 +473,7 @@ class DeployOperation(InstanceOperation):
self.instance.allocate_vnc_port() self.instance.allocate_vnc_port()
if node is not None: if node is not None:
self.instance.node = node self.instance.node = node
self.instance.runtime_compatibility_group = node.compatibility_group
self.instance.save() self.instance.save()
else: else:
self.instance.allocate_node() self.instance.allocate_node()
...@@ -677,9 +678,10 @@ class MigrateOperation(RemoteInstanceOperation): ...@@ -677,9 +678,10 @@ class MigrateOperation(RemoteInstanceOperation):
with activity.sub_activity('scheduling', with activity.sub_activity('scheduling',
readable_name=gettext_noop( readable_name=gettext_noop(
"schedule")) as sa: "schedule")) as sa:
to_node = self.instance.select_node(excl=self.instance.node) to_node = self.instance.select_node(excl=self.instance.node, preserve_runtime=True)
sa.result = to_node sa.result = to_node
if to_node == self.instance.node:
return
try: try:
with activity.sub_activity( with activity.sub_activity(
'migrate_vm', readable_name=create_readable( 'migrate_vm', readable_name=create_readable(
...@@ -699,6 +701,7 @@ class MigrateOperation(RemoteInstanceOperation): ...@@ -699,6 +701,7 @@ class MigrateOperation(RemoteInstanceOperation):
# Refresh node information # Refresh node information
self.instance.node = to_node self.instance.node = to_node
self.instance.runtime_compatibility_group = to_node.compatibility_group
self.instance.save() self.instance.save()
# Estabilish network connection (vmdriver) # Estabilish network connection (vmdriver)
...@@ -1039,7 +1042,7 @@ class SleepOperation(InstanceOperation): ...@@ -1039,7 +1042,7 @@ class SleepOperation(InstanceOperation):
"shutdown network")): "shutdown network")):
self.instance.shutdown_net() self.instance.shutdown_net()
self.instance._suspend_vm(parent_activity=activity) self.instance._suspend_vm(parent_activity=activity)
self.instance.yield_node() self.instance.yield_node(preserve_runtime=True)
logger.info('sleep vm operation ' + str(system)) logger.info('sleep vm operation ' + str(system))
if system: if system:
self.instance.callhookurl() self.instance.callhookurl()
...@@ -1082,7 +1085,7 @@ class WakeUpOperation(InstanceOperation): ...@@ -1082,7 +1085,7 @@ class WakeUpOperation(InstanceOperation):
def _operation(self, activity): def _operation(self, activity):
# Schedule vm # Schedule vm
self.instance.allocate_vnc_port() self.instance.allocate_vnc_port()
self.instance.allocate_node() self.instance.allocate_node(preserve_runtime=True)
# Resume vm # Resume vm
self.instance._wake_up_vm(parent_activity=activity) self.instance._wake_up_vm(parent_activity=activity)
......
from django.test import SimpleTestCase
from unittest.mock import Mock, MagicMock, patch
from vm.models import Instance, Node
class RuntimeCompatibilityTestCase(SimpleTestCase):
def setUp(self):
self.inst = MagicMock(spec=Instance)
self.node = MagicMock(spec=Node)
self.node.compatibility_group = "new"
self.inst.node = None
self.inst.runtime_compatibility_group = "old"
self.inst.select_node.return_value = self.node
def test_allocate_inherits_group(self):
Instance.allocate_node(self.inst)
self.assertEqual(self.inst.node, self.node)
self.assertEqual(
self.inst.runtime_compatibility_group, "new")
self.inst.select_node.assert_called_once_with(
preserve_runtime=False)
self.inst.save.assert_called_once()
def test_allocate_with_existing_node(self):
self.inst.node = self.node
Instance.allocate_node(self.inst)
self.inst.select_node.assert_not_called()
self.assertEqual(
self.inst.runtime_compatibility_group, "new")
def test_allocate_preserves_runtime(self):
self.node.compatibility_group = "old"
Instance.allocate_node(
self.inst, preserve_runtime=True)
self.assertEqual(self.inst.node, self.node)
self.assertEqual(
self.inst.runtime_compatibility_group, "old")
self.inst.select_node.assert_called_once_with(
preserve_runtime=True)
def test_allocate_preserves_null_group(self):
self.inst.runtime_compatibility_group = None
self.node.compatibility_group = ""
Instance.allocate_node(
self.inst, preserve_runtime=True)
self.assertIsNone(
self.inst.runtime_compatibility_group)
def test_yield_preserves_runtime(self):
self.inst.node = self.node
Instance.yield_node(self.inst)
self.assertIsNone(self.inst.node)
self.assertEqual(
self.inst.runtime_compatibility_group, "old")
self.inst.save.assert_called_once()
from django.test import SimpleTestCase
from unittest.mock import MagicMock
from vm.models import Instance, Node
class RuntimeCompatibilityTestCase(SimpleTestCase):
def setUp(self):
self.inst = MagicMock(spec=Instance)
self.node = MagicMock(spec=Node)
self.node.compatibility_group = "new"
self.inst.node = None
self.inst.runtime_compatibility_group = "old"
self.inst.select_node.return_value = self.node
def test_allocate_inherits_group(self):
Instance.allocate_node(self.inst)
self.assertEqual(self.inst.node, self.node)
self.assertEqual(
self.inst.runtime_compatibility_group, "new")
self.inst.select_node.assert_called_once_with(
preserve_runtime=False)
self.inst.save.assert_called_once()
def test_allocate_with_existing_node(self):
self.inst.node = self.node
Instance.allocate_node(self.inst)
self.inst.select_node.assert_not_called()
self.assertEqual(
self.inst.runtime_compatibility_group, "new")
def test_allocate_preserves_runtime(self):
self.node.compatibility_group = "old"
Instance.allocate_node(
self.inst, preserve_runtime=True)
self.assertEqual(self.inst.node, self.node)
self.assertEqual(
self.inst.runtime_compatibility_group, "old")
self.inst.select_node.assert_called_once_with(
preserve_runtime=True)
def test_allocate_preserves_null_group(self):
self.inst.runtime_compatibility_group = None
self.node.compatibility_group = ""
Instance.allocate_node(
self.inst, preserve_runtime=True)
self.assertIsNone(
self.inst.runtime_compatibility_group)
def test_yield_preserves_runtime(self):
self.inst.node = self.node
Instance.yield_node(self.inst)
self.assertIsNone(self.inst.node)
self.assertEqual(
self.inst.runtime_compatibility_group, "old")
self.inst.save.assert_called_once()
...@@ -16,7 +16,7 @@ ...@@ -16,7 +16,7 @@
# with CIRCLE. If not, see <http://www.gnu.org/licenses/>. # with CIRCLE. If not, see <http://www.gnu.org/licenses/>.
from django.test import TestCase from django.test import TestCase
from unittest.mock import MagicMock from unittest.mock import MagicMock, patch
from common.operations import operation_registry_name as op_reg_name from common.operations import operation_registry_name as op_reg_name
from vm.models import Instance, InstanceActivity, Node from vm.models import Instance, InstanceActivity, Node
...@@ -58,10 +58,58 @@ class MigrateOperationTestCase(TestCase): ...@@ -58,10 +58,58 @@ class MigrateOperationTestCase(TestCase):
self.assertRaises( self.assertRaises(
MigrateException, op._operation, MigrateException, op._operation,
act, to_node=None) act, to_node=None)
assert inst.select_node.called inst.select_node.assert_called_once_with(
excl=inst.node, preserve_runtime=True)
op._get_remote_args.assert_called_once_with( op._get_remote_args.assert_called_once_with(
to_node='test', live_migration=True) to_node='test', live_migration=True)
def test_manual_migration_overrides_compatibility(self):
inst = MagicMock(spec=Instance)
act = MagicMock(spec=InstanceActivity)
inst.runtime_compatibility_group = "old"
target = MagicMock(spec=Node)
target.compatibility_group = "new"
op = MigrateOperation(inst)
with patch("vm.operations.RemoteInstanceOperation._operation"):
op._operation(act, to_node=target)
inst.select_node.assert_not_called()
self.assertEqual(inst.node, target)
self.assertEqual(
inst.runtime_compatibility_group, "new")
inst.save.assert_called_once()
def test_failed_migration_preserves_group(self):
inst = MagicMock(spec=Instance)
act = MagicMock(spec=InstanceActivity)
source = MagicMock(spec=Node)
source.compatibility_group = "old"
target = MagicMock(spec=Node)
target.compatibility_group = "new"
inst.node = source
inst.runtime_compatibility_group = "old"
op = MigrateOperation(inst)
with patch(
"vm.operations.RemoteInstanceOperation._operation",
side_effect=RuntimeError("Migration failed")
):
with self.assertRaises(RuntimeError):
op._operation(act, to_node=target)
self.assertEqual(inst.node, source)
self.assertEqual(
inst.runtime_compatibility_group, "old")
inst.save.assert_not_called()
class RebootOperationTestCase(TestCase): class RebootOperationTestCase(TestCase):
def test_operation_registered(self): def test_operation_registered(self):
...@@ -104,3 +152,18 @@ class SleepOperationTestCase(TestCase): ...@@ -104,3 +152,18 @@ class SleepOperationTestCase(TestCase):
class WakeUpOperationTestCase(TestCase): class WakeUpOperationTestCase(TestCase):
def test_operation_registered(self): def test_operation_registered(self):
assert WakeUpOperation.id in getattr(Instance, op_reg_name) assert WakeUpOperation.id in getattr(Instance, op_reg_name)
def test_wakeup_preserves_runtime(self):
inst = MagicMock(spec=Instance)
act = MagicMock(spec=InstanceActivity)
inst._wake_up_vm = MagicMock()
op = WakeUpOperation(inst)
op._operation(act)
inst.allocate_node.assert_called_once_with(
preserve_runtime=True)
inst._wake_up_vm.assert_called_once_with(
parent_activity=act)
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment