cc1  v2.1
CC1 source code docs
All Classes Namespaces Files Functions Variables Pages
vm.py
Go to the documentation of this file.
1 # -*- coding: utf-8 -*-
2 # @COPYRIGHT_begin
3 #
4 # Copyright [2010-2014] Institute of Nuclear Physics PAN, Krakow, Poland
5 #
6 # Licensed under the Apache License, Version 2.0 (the "License");
7 # you may not use this file except in compliance with the License.
8 # You may obtain a copy of the License at
9 #
10 # http://www.apache.org/licenses/LICENSE-2.0
11 #
12 # Unless required by applicable law or agreed to in writing, software
13 # distributed under the License is distributed on an "AS IS" BASIS,
14 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 # See the License for the specific language governing permissions and
16 # limitations under the License.
17 #
18 # @COPYRIGHT_end
19 
20 ##
21 # @package src.wi.forms.vm
22 #
23 # @author Krzysztof Danielowski
24 # @author Piotr Wójcik
25 # @date 26.11.2010
26 #
27 
28 from itertools import chain
29 
30 from django import forms
31 from django.forms.fields import CheckboxInput
32 from django.utils.encoding import force_unicode
33 from django.utils.html import conditional_escape
34 from django.utils.safestring import mark_safe
35 from django.utils.translation import ugettext_lazy as _
36 
37 from wi.utils import parsing
38 from wi.utils.forms import attrs_dict, RequiredSelectValidation
39 from wi.utils.regexp import regexp, regexp_text
40 from wi.utils.states import stat_names_reversed, stat_short_names_reversed, stat_resolutions_reversed, stat_ranges_reversed
41 from wi.utils.widgets import SelectWithDisabled, CheckboxSelectMultipleWithDisabled
42 
43 
44 class My2CheckboxSelectMultiple(forms.CheckboxSelectMultiple):
45  def render(self, name, value, attrs=None, choices=()):
46  if value is None:
47  value = []
48  has_id = attrs and 'id' in attrs
49  final_attrs = self.build_attrs(attrs, name=name)
50  output = [u'<ul>']
51  # Normalize to strings
52  str_values = set([force_unicode(v) for v in value])
53  for i, (option_value, option_label) in enumerate(chain(self.choices, choices)):
54  # If an ID attribute was given, add a numeric index as a suffix,
55  # so that the checkboxes don't all have the same ID attribute.
56  if has_id:
57  final_attrs = dict(final_attrs, id='%s_%s' % (attrs['id'], i))
58  label_for = u' for="%s"' % final_attrs['id']
59  else:
60  label_for = ''
61 
62  cb = CheckboxInput(final_attrs, check_test=lambda value: value in str_values)
63  option_value = force_unicode(option_value)
64  rendered_cb = cb.render(name, option_value)
65  option_label = conditional_escape(force_unicode(option_label))
66  output.append(u'<li class="stats ' + stat_short_names_reversed[int(option_value)] + '"><label%s>%s %s</label></li>' % (label_for, rendered_cb, option_label))
67  output.append(u'</ul>')
68  return mark_safe(u'\n'.join(output))
69 
70 
71 ##
72 #
73 # Form for <b>VM edition</b>.
74 #
75 class EditVMForm(forms.Form):
76 
77  name = forms.CharField(widget=forms.TextInput(attrs=dict(attrs_dict, maxlength=45)),
78  label=_('Name'))
79  description = forms.CharField(required=False,
80  widget=forms.Textarea(attrs=dict(attrs_dict, maxlength=512, rows=4, cols=20)),
81  label=_('Description'))
82 
83 
84 ##
85 #
86 # Form for <b>setting SSH key</b>.
87 #
88 class SetSshKeyForm(forms.Form):
89  vm_username = forms.RegexField(regex=regexp['login'],
90  initial="root",
91  widget=forms.TextInput(attrs=dict(attrs_dict, maxlength=35)),
92  error_messages={'invalid': regexp_text['login']},
93  label=_('Username'))
94 
95  def __init__(self, *args, **kwargs):
96  rest_data = kwargs.pop('rest_data')
97  super(SetSshKeyForm, self).__init__(*args, **kwargs)
98  self.fields['vm_key'] = forms.ChoiceField(choices=parsing.parse_ssh_keys(rest_data), initial=0, label=_('Key'))
99  self.fields['vm_key'].widget.attrs['class'] = 'medium'
100 
101  ##
102  #
103  # Cast 'vm_key' to int.
104  #
105  def clean_vm_key(self):
106  return int(self.cleaned_data['vm_key'])
107 
108 
109 ##
110 #
111 # Form for <b>changing VM password</b>.
112 #
113 class ChangeVMPasswordForm(forms.Form):
114  vm_username = forms.RegexField(regex=regexp['login'],
115  initial="root",
116  widget=forms.TextInput(attrs=dict(attrs_dict, maxlength=35)),
117  error_messages={'invalid': regexp_text['login']},
118  label=_('Username'))
119 
120 
121 ##
122 #
123 # Form for <b>IP assignment</b>.
124 #
125 class AssignChosenIPForm(RequiredSelectValidation):
126 
127  def __init__(self, *args, **kwargs):
128  rest_data = kwargs.pop('rest_data')
129  super(AssignChosenIPForm, self).__init__(*args, **kwargs)
130  self.fields['public_ip_id'] = forms.ChoiceField(choices=parsing.parse_ips(rest_data, False), initial=0,
131  widget=SelectWithDisabled(attrs=dict({'class': 'medium'})),
132  label=_("IP address"))
133  self.fields['public_ip_id'].widget.attrs['class'] = 'medium'
134 
135  ##
136  #
137  # Cast 'public_ip_id' to int.
138  #
140  return int(self.cleaned_data['public_ip_id'])
141 
142 
143 ##
144 #
145 # Form for <b>IP assignment</b>.
146 #
147 class AssignIPForm(RequiredSelectValidation):
148 
149  def __init__(self, *args, **kwargs):
150  rest_data = kwargs.pop('rest_data')
151  super(AssignIPForm, self).__init__(*args, **kwargs)
152  self.fields['public_ip_id'] = forms.ChoiceField(choices=parsing.parse_ips(rest_data, False), initial=0,
153  widget=SelectWithDisabled(attrs=dict({'class': 'medium'})),
154  label=_("IP address"))
155  self.fields['public_ip_id'].widget.attrs['class'] = 'medium'
156  self.fields['lease_id'] = forms.ChoiceField(choices=parsing.parse_leases(rest_data), initial=0,
157  widget=SelectWithDisabled(attrs=dict({'class': 'medium'})),
158  label=_("Lease"))
159  self.fields['lease_id'].widget.attrs['class'] = 'medium'
160 
161  ##
162  #
163  # Cast 'lease_id' to int.
164  #
165  def clean_lease_id(self):
166  return int(self.cleaned_data['lease_id'])
167 
168  ##
169  #
170  # Cast 'public_ip_id' to int.
171  #
173  return int(self.cleaned_data['public_ip_id'])
174 
175 
176 ##
177 #
178 # For for IP address revoking.
179 #
180 class RevokeIPForm(RequiredSelectValidation):
181 
182  def __init__(self, *args, **kwargs):
183  rest_data = kwargs.pop('rest_data')
184  super(RevokeIPForm, self).__init__(*args, **kwargs)
185  self.fields['public_ip_id'] = forms.ChoiceField(choices=parsing.parse_ips_from_vm(rest_data), initial=0,
186  widget=SelectWithDisabled(attrs=dict({'class': 'medium'})),
187  label=_("IP address"))
188  self.fields['public_ip_id'].widget.attrs['class'] = 'medium'
189 
190  ##
191  #
192  # Cast 'public_ip_id' to int.
193  #
195  return int(self.cleaned_data['public_ip_id'])
196 
197 
198 ##
199 #
200 # Form for <b>disk assignment</b>.
201 #
202 class AssignDiskForm(RequiredSelectValidation):
203 
204  def __init__(self, *args, **kwargs):
205  rest_data = kwargs.pop('rest_data')
206  super(AssignDiskForm, self).__init__(*args, **kwargs)
207  self.fields['storage_image_id'] = forms.ChoiceField(choices=parsing.parse_disks(rest_data, False), initial=0,
208  widget=SelectWithDisabled(attrs=dict({'class': 'medium'})),
209  label=_("Disk"))
210  self.fields['storage_image_id'].widget.attrs['class'] = 'medium'
211 
212  ##
213  #
214  # Cast 'storage_image_id' to int.
215  #
217  return int(self.cleaned_data['storage_image_id'])
218 
219 
220 ##
221 #
222 # Form for <b>disk unassignment</b>.
223 #
224 class RevokeDiskForm(RequiredSelectValidation):
225 
226  def __init__(self, *args, **kwargs):
227  rest_data = kwargs.pop('rest_data')
228  super(RevokeDiskForm, self).__init__(*args, **kwargs)
229  self.fields['storage_image_id'] = forms.ChoiceField(choices=parsing.parse_disks_from_vm(rest_data), initial=0,
230  widget=SelectWithDisabled(attrs=dict({'class': 'medium'})),
231  label=_('Disk'))
232  self.fields['storage_image_id'].widget.attrs['class'] = 'medium'
233 
234  ##
235  #
236  # Cast 'img_id' to int.
237  #
239  return int(self.cleaned_data['storage_image_id'])
240 
241 
242 ##
243 #
244 # Form for <b>creating a virtual machine</b>.
245 #
246 class CreateVMForm1(forms.Form):
247 
248  image_id = forms.CharField(widget=forms.HiddenInput())
249 
250  def __init__(self, *args, **kwargs):
251  super(CreateVMForm1, self).__init__(*args, **kwargs)
252 
253  ##
254  #
255  # Cast 'image_id' to int.
256  #
257  def clean_image_id(self):
258  if int(self.cleaned_data['image_id']) < 0:
259  raise forms.ValidationError(_('Please select an image.'))
260  else:
261  return int(self.cleaned_data['image_id'])
262 
263 
264 ##
265 #
266 # Form for <b>creating a virtual machine</b>.
267 #
268 class CreateVMForm2(forms.Form):
269 
270  template_id = forms.CharField(widget=forms.HiddenInput())
271 
272  def __init__(self, *args, **kwargs):
273  super(CreateVMForm2, self).__init__(*args, **kwargs)
274 
275  ##
276  #
277  # Cast 'template_id' to int.
278  #
279  def clean_template_id(self):
280  if int(self.cleaned_data['template_id']) < 0:
281  raise forms.ValidationError(_('Please select a template.'))
282  else:
283  return int(self.cleaned_data['template_id'])
284 
285 
286 ##
287 #
288 # Form for <b>creating a virtual machine</b>.
289 #
290 class CreateVMForm3(forms.Form):
291 
292  def __init__(self, *args, **kwargs):
293  rest_data = kwargs.pop('rest_data')
294  super(CreateVMForm3, self).__init__(*args, **kwargs)
295 
296  self.fields['public_ip_id'] = forms.ChoiceField(choices=parsing.parse_ips(rest_data),
297  required=False,
298  widget=SelectWithDisabled(attrs=dict()),
299  label=_('Assign IP address'),
300  help_text=_('Public IP address - To get a new IP address go to: VM Resources -&gt; Elastic IP addresses'))
301 
302  self.fields['disk_list'] = forms.MultipleChoiceField(choices=parsing.parse_disks(rest_data, True),
303  required=False,
304  widget=CheckboxSelectMultipleWithDisabled,
305  label=_('Attach disk volume'),
306  help_text=_('Virtual disk - '))
307 
308  self.fields['iso_list'] = forms.ChoiceField(choices=parsing.parse_iso(rest_data),
309  required=False,
310  widget=SelectWithDisabled(attrs=dict()),
311  label=_("Attach ISO image"))
312 
313  self.fields['vnc'] = forms.BooleanField(required=False,
314  label=_("VNC"),
315  widget=forms.CheckboxInput(attrs={'class': 'checkbox'}),
316  help_text=_('VNC - Enable/Disable VNC redirection'))
317 
318  self.fields.keyOrder = ['public_ip_id', 'disk_list', 'iso_list', 'vnc']
319 
320  ##
321  #
322  # Cast 'public_ip_id' to int.
323  #
325  return int(self.cleaned_data['public_ip_id'])
326 
327  ##
328  #
329  # Cast each item in 'disk_list' to int.
330  #
331  def clean_disk_list(self):
332  for i in self.cleaned_data['disk_list']:
333  if int(i) < 0:
334  return []
335  return [int(a) for a in self.cleaned_data['disk_list']]
336 
337  ##
338  #
339  # Cast each item in 'iso_list' to int.
340  #
341  def clean_iso_list(self):
342  if int(self.cleaned_data['iso_list']) < 0:
343  return []
344  return [int(self.cleaned_data['iso_list'])]
345 
346 
347 ##
348 #
349 # Form for <b>creating a virtual machine</b>.
350 #
352 
353  def __init__(self, *args, **kwargs):
354  super(CreateVMForm4, self).__init__(*args, **kwargs)
355  self.fields.keyOrder = ['name', 'description']
356 
357 
358 ##
359 #
360 # Form for fetching the monitoring data for a selected virtual machine.
361 #
362 class MonitoringVMForm(forms.Form):
363 
364  vm_id = forms.CharField(widget=forms.HiddenInput())
365  time = forms.CharField(widget=forms.HiddenInput())
366 
367  def __init__(self, *args, **kwargs):
368  super(MonitoringVMForm, self).__init__(*args, **kwargs)
369 
370  self.fields['stat_name'] = forms.MultipleChoiceField(choices=stat_names_reversed.items(),
371  widget=My2CheckboxSelectMultiple,
372  label=_('Statistic'),
373  initial=['0'])
374  self.fields['resolution'] = forms.ChoiceField(choices=stat_resolutions_reversed.items(),
375  label=_('Time range'))
376  self.fields['resolution'].widget.attrs['class'] = 'small'
377 
378  self.fields['stat_range'] = forms.ChoiceField(choices=stat_ranges_reversed.items(),
379  label=_('Period'))
380  self.fields['stat_range'].widget.attrs['class'] = 'small'
381 
382  ##
383  #
384  # Cast 'vm_id' to int.
385  #
386  def clean_vm_id(self):
387  return int(self.cleaned_data['vm_id'])
388 
389  ##
390  #
391  # Cast 'stat_name' to int.
392  #
393  def clean_stat_name(self):
394  return [int(i) for i in self.cleaned_data['stat_name']]
395 
396  ##
397  #
398  # Cast 'resolution' to int.
399  #
400  def clean_resolution(self):
401  return int(self.cleaned_data['resolution'])
402 
403  ##
404  #
405  # Cast 'stat_range' to int.
406  #
407  def clean_stat_range(self):
408  return int(self.cleaned_data['stat_range'])
409 
410 
411 ##
412 #
413 # CM admin's form for <b>creating a virtual machine</b>.
414 #
416 
417  def __init__(self, *args, **kwargs):
418  # not .pop() because CreateVMForm3 also needs it
419  rest_data = kwargs['rest_data']
420  super(CreateVMOnNodeForm, self).__init__(*args, **kwargs)
421 
422  self.fields['image_id'] = forms.ChoiceField(choices=parsing.parse_image_names(rest_data),
423  widget=SelectWithDisabled(attrs=dict()),
424  label=_("Image"),
425  help_text=_('Image file - From your public, private or group image pool'))
426 
427  self.fields['template_id'] = forms.ChoiceField(choices=parsing.parse_template_names(rest_data),
428  widget=forms.Select(attrs=dict()),
429  label=_("Template"),
430  help_text=_('Template of machine - Virtual machine parameters'))
431 
432  self.fields.keyOrder = ['image_id', 'name', 'description',
433  'template_id', 'public_ip_id', 'disk_list',
434  'iso_list', 'vnc']
435 
436  ##
437  #
438  # Cast 'image_id' to int.
439  #
440  def clean_image_id(self):
441  if int(self.cleaned_data['image_id']) < 0:
442  raise forms.ValidationError(_("Please select an image."))
443  else:
444  return int(self.cleaned_data['image_id'])
445 
446  ##
447  #
448  # Cast 'template_id' to int.
449  #
450  def clean_template_id(self):
451  if int(self.cleaned_data['template_id']) < 0:
452  raise forms.ValidationError(_("Please select a template."))
453  else:
454  return int(self.cleaned_data['template_id'])
455