Commit d31bb288 by Szabolcs Gelencser

Add skeleton of save as template operation

parent 63501e0a
...@@ -62,7 +62,7 @@ from .util import ( ...@@ -62,7 +62,7 @@ from .util import (
) )
from ..forms import ( from ..forms import (
AclUserOrGroupAddForm, VmResourcesForm, VmCustomizeForm, VmDeployForm, VmFromPlainImageForm, VmRemoveInterfaceForm, AclUserOrGroupAddForm, VmResourcesForm, VmCustomizeForm, VmDeployForm, VmFromPlainImageForm, VmRemoveInterfaceForm,
VmAddInterfaceForm) VmAddInterfaceForm, VmSaveForm)
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
...@@ -523,24 +523,24 @@ class VmAddInterfaceView(FormOperationMixin, VmOperationView): ...@@ -523,24 +523,24 @@ class VmAddInterfaceView(FormOperationMixin, VmOperationView):
# return val # return val
# #
# #
# class VmSaveView(FormOperationMixin, VmOperationView): class VmSaveView(FormOperationMixin, VmOperationView):
#
# op = 'save_as_template' op = 'save_as_template'
# icon = 'save' icon = 'save'
# effect = 'info' effect = 'info'
# form_class = VmSaveForm form_class = VmSaveForm
#
# def get_form_kwargs(self): def get_form_kwargs(self):
# op = self.get_op() context = super(VmSaveView, self).get_form_kwargs()
# val = super(VmSaveView, self).get_form_kwargs() op = self.get_op()
# val['default'] = op._rename(op.instance.name)
# obj = self.get_object() context['default'] = op._rename(op.instance.name)
# if obj.template and obj.template.has_level( obj = self.get_object()
# self.request.user, "owner"):
# val['clone'] = True #context['clone'] = True #TODO: if instance has a template already this option allows clone of permissions
# return val return context
#
#
# class VmResourcesChangeView(VmOperationView): # class VmResourcesChangeView(VmOperationView):
# op = 'resources_change' # op = 'resources_change'
# icon = "save" # icon = "save"
...@@ -761,7 +761,7 @@ vm_ops = OrderedDict([ ...@@ -761,7 +761,7 @@ vm_ops = OrderedDict([
('sleep', VmOperationView.factory( ('sleep', VmOperationView.factory(
op='sleep', icon='moon-o', effect='info')), op='sleep', icon='moon-o', effect='info')),
# ('migrate', VmMigrateView), # ('migrate', VmMigrateView),
# ('save_as_template', VmSaveView), ('save_as_template', VmSaveView),
('reboot', VmOperationView.factory( ('reboot', VmOperationView.factory(
op='reboot', icon='refresh', effect='warning')), op='reboot', icon='refresh', effect='warning')),
# ('reset', VmOperationView.factory( # ('reset', VmOperationView.factory(
......
...@@ -124,16 +124,17 @@ class InstanceOperation(Operation): ...@@ -124,16 +124,17 @@ class InstanceOperation(Operation):
raise self.instance.WrongStateError(self.instance) raise self.instance.WrongStateError(self.instance)
def check_auth(self, user, request): def check_auth(self, user, request):
from django.utils.module_loading import import_string if self.os_policy_actions:
check = import_string("openstack_auth.policy.check") from django.utils.module_loading import import_string
check = import_string("openstack_auth.policy.check")
has_rights = check(self.os_policy_actions, request, has_rights = check(self.os_policy_actions, request,
{'project_id': self.instance.tenant_id}) {'project_id': self.instance.tenant_id})
if not has_rights: if not has_rights:
raise humanize_exception(ugettext_noop( raise humanize_exception(ugettext_noop(
"operation not permitted"), "operation not permitted"),
PermissionDenied()) PermissionDenied())
super(InstanceOperation, self).check_auth(user=user) super(InstanceOperation, self).check_auth(user=user)
...@@ -505,15 +506,8 @@ class SaveAsTemplateOperation(InstanceOperation): ...@@ -505,15 +506,8 @@ class SaveAsTemplateOperation(InstanceOperation):
"with users and groups. Anyone who has access to a " "with users and groups. Anyone who has access to a "
"template (and to the networks it uses) will be able to " "template (and to the networks it uses) will be able to "
"start an instance of it.") "start an instance of it.")
has_percentage = True accept_states = ('SHUTOFF', 'ACTIVE') # TODO: try other states
abortable = True # os_policy_actions = (("compute", "compute:stop"),)
required_perms = ('vm.create_template',)
accept_states = ('ACTIVE', 'STOPPED')
async_queue = "localhost.man.slow"
def is_preferred(self):
return (self.instance.is_base and
self.instance.status == self.instance.STATUS.RUNNING)
@staticmethod @staticmethod
def _rename(name): def _rename(name):
...@@ -525,87 +519,13 @@ class SaveAsTemplateOperation(InstanceOperation): ...@@ -525,87 +519,13 @@ class SaveAsTemplateOperation(InstanceOperation):
v = 1 v = 1
return "%s v%d" % (name, v) return "%s v%d" % (name, v)
def on_abort(self, activity, error): def _operation(self, request, user, system, name=None,
if hasattr(self, 'disks'):
for disk in self.disks:
disk.destroy()
def _operation(self, activity, user, system, name=None,
with_shutdown=True, clone=False, task=None, **kwargs): with_shutdown=True, clone=False, task=None, **kwargs):
try: print "TODO: create template"
self.instance._cleanup(parent_activity=activity, user=user) # return create_readable(
except: # ugettext_noop("New template: %(template)s"),
pass # template=reverse('dashboard.views.template-detail',
# kwargs={'pk': 0}))
if with_shutdown:
try:
self.instance.shutdown(parent_activity=activity,
user=user, task=task)
except Instance.WrongStateError:
pass
# prepare parameters
params = {
'access_method': self.instance.access_method,
'arch': self.instance.arch,
'boot_menu': self.instance.boot_menu,
'description': self.instance.description,
'lease': self.instance.lease, # Can be problem in new VM
'max_ram_size': self.instance.max_ram_size,
'name': name or self._rename(self.instance.name),
'num_cores': self.instance.num_cores,
'owner': user,
'parent': self.instance.template or None, # Can be problem
'priority': self.instance.priority,
'ram_size': self.instance.ram_size,
'raw_data': self.instance.raw_data,
'system': self.instance.system,
}
params.update(kwargs)
params.pop("parent_activity", None)
from storage.models import Disk
def __try_save_disk(disk):
try:
return disk.save_as(task)
except Disk.WrongDiskTypeError:
return disk
self.disks = []
for disk in self.instance.disks.all():
with activity.sub_activity(
'saving_disk',
readable_name=create_readable(
ugettext_noop("saving disk %(name)s"),
name=disk.name)
):
self.disks.append(__try_save_disk(disk))
# create template and do additional setup
tmpl = InstanceTemplate(**params)
tmpl.full_clean() # Avoiding database errors.
tmpl.save()
# Copy traits from the VM instance
tmpl.req_traits.add(*self.instance.req_traits.all())
if clone:
tmpl.clone_acl(self.instance.template)
# Add permission for the original owner of the template
tmpl.set_level(self.instance.template.owner, 'owner')
tmpl.set_level(user, 'owner')
try:
tmpl.disks.add(*self.disks)
# create interface templates
for i in self.instance.interface_set.all():
i.save_as_template(tmpl)
except:
tmpl.delete()
raise
else:
return create_readable(
ugettext_noop("New template: %(template)s"),
template=reverse('dashboard.views.template-detail',
kwargs={'pk': tmpl.pk}))
@register_operation @register_operation
......
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