cc1  v2.1
CC1 source code docs
 All Classes Namespaces Files Functions Variables Pages
farm.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.views.user.farm
22 #
23 # @author Piotr W√≥jcik
24 # @date 14.11.2011
25 #
26 
27 from colorsys import hsv_to_rgb
28 
29 from django.contrib import messages
30 from django.shortcuts import redirect
31 from django.utils.decorators import method_decorator
32 from django.utils.translation import ugettext as _
33 
34 from wi.commontags.templatetags.templatetags import filesizeformatmb
35 from wi.utils import messages_ajax, parsing, get_dicts_from_list, get_dict_from_list
36 from wi.utils.decorators import django_view, user_permission
37 from wi.utils.exceptions import RestErrorException
38 from wi.utils.formatters import time_from_sec
39 from wi.utils.messages_ajax import ajax_request
40 from wi.utils.states import farm_states_reversed as farm_states, \
41  vm_states_reversed, farm_descriptions_reversed as farm_states_help
42 from wi.utils.views import prep_data, CustomWizardView
43 
44 
45 ##
46 #
47 # Form wizard for farm creation.
48 #
49 class CreateFarmWizard(CustomWizardView):
50  url_done = 'far_show_farm'
51  url_start = 'far_create_farm'
52 
53  wizard_name = 'create_farm_wizard'
54  template_dir_name = 'farms'
55 
56  ##
57  #
58  # Action executed on last step submition.
59  #
60  def done(self, form_list, **kwargs):
61  form_data = self.get_all_cleaned_data()
62  try:
63  prep_data({'farm': ('user/farm/create/', form_data)}, self.request.session)
64  except RestErrorException as ex:
65  messages.error(self.request, ex.value)
66  else:
67  messages.success(self.request, _('Farm is being created.'))
68 
69  return redirect(self.url_done)
70 
71  def get_form_kwargs(self, step=None):
72  step = int(step)
73  initial_data = {}
74 
75  if step == 1:
76  rest_data = prep_data({'templates': 'user/template/get_list/'}, self.request.session)
77  initial_data = {'rest_data': rest_data,
78  'session': self.request.session}
79 
80  if step == 2:
81  rest_data = prep_data({'ips': 'user/public_ip/get_list/',
82  'disks': 'user/storage_image/get_list/',
83  'iso': 'user/iso_image/get_list/'},
84  self.request.session)
85  initial_data = {'rest_data': rest_data}
86 
87  return initial_data
88 
89  def get_context_data(self, form, **kwargs):
90  context = super(CreateFarmWizard, self).get_context_data(form=form, **kwargs)
91  context.update({'steps_desc': [_('Image'), _('Hardware'), _('Optional resources'), _('Summary')]})
92 
93  if self.steps.current == '0':
94  rest_data = prep_data({'groups': 'user/group/list_groups/'}, self.request.session)
95 
96  categories = [
97  ['all', _('All images')],
98  ['private', _('My images')],
99  ['public', _('Public images')],
100  ]
101  for item in parsing.parse_groups(rest_data):
102  categories.append([item[0], _('Group images: ') + item[1]])
103 
104  context.update({'image_categories': categories})
105 
106  elif self.steps.current == '1':
107  form_cleaned_data = self.get_all_cleaned_data()
108  rest_data = prep_data({'image': ('user/system_image/get_by_id/', {'system_image_id': form_cleaned_data['image_id']})},
109  self.request.session)
110 
111  context.update({'steps_desc': [rest_data['image']['name'] if len(rest_data['image']['name']) <= 15 else rest_data['image']['name'][:15] + '...',
112  _('Hardware'),
113  _('Optional resources'),
114  _('Summary')]})
115 
116  elif self.steps.current == '2':
117  form_cleaned_data = self.get_all_cleaned_data()
118  rest_data = prep_data({'image': ('user/system_image/get_by_id/', {'system_image_id': form_cleaned_data['image_id']}),
119  'templates': 'user/template/get_list/'},
120  self.request.session)
121  template = get_dict_from_list(rest_data['templates'], form_cleaned_data['worker_template_id'], key='template_id')
122  context.update({'steps_desc': [rest_data['image']['name'] if len(rest_data['image']['name']) <= 15 else rest_data['image']['name'][:15] + '...',
123  str(form_cleaned_data['count']) + 'x' + str(template['cpu']) + ' CPU/' + str(filesizeformatmb(template['memory'])),
124  _('Optional resources'),
125  _('Summary')]})
126 
127  elif self.steps.current == '3':
128  form_cleaned_data = self.get_all_cleaned_data()
129  rest_data = prep_data({'image': ('user/system_image/get_by_id/', {'system_image_id': form_cleaned_data['image_id']}),
130  'templates': 'user/template/get_list/',
131  'ips': 'user/public_ip/get_list/',
132  'disks': 'user/storage_image/get_list/',
133  'iso': 'user/iso_image/get_list/'},
134  self.request.session)
135  summary_data = {'summary_image': rest_data['image'],
136  'summary_head_template': get_dict_from_list(rest_data['templates'], form_cleaned_data['head_template_id'], key='template_id'),
137  'summary_template': get_dict_from_list(rest_data['templates'], form_cleaned_data['worker_template_id'], key='template_id'),
138  'summary_count': form_cleaned_data['count'],
139  'summary_ip': get_dict_from_list(rest_data['ips'], form_cleaned_data['public_ip_id'], key='public_ip_id'),
140  'summary_disks': get_dicts_from_list(rest_data['disks'], form_cleaned_data['disk_list'], key='storage_image_id'),
141  'summary_iso': get_dicts_from_list(rest_data['iso'], form_cleaned_data['iso_list'], key='iso_image_id'),
142  'summary_vnc': form_cleaned_data['vnc']}
143 
144  template = get_dict_from_list(rest_data['templates'], form_cleaned_data['worker_template_id'], key='template_id')
145  context.update({'steps_desc': [rest_data['image']['name'] if len(rest_data['image']['name']) <= 15 else rest_data['image']['name'][:15] + '...',
146  str(form_cleaned_data['count']) + 'x' + str(template['cpu']) + ' CPU/' + str(filesizeformatmb(template['memory'])),
147  _('Optional resources'),
148  _('Summary')]})
149 
150  context.update(summary_data)
151 
152  return context
153 
154 
155 CreateFarmWizard.dispatch = method_decorator(user_permission)(
156  method_decorator(django_view)(
157  CreateFarmWizard.dispatch))
158 
159 
160 @django_view
161 @ajax_request
162 @user_permission
163 ##
164 #
165 # Ajax view for fetching farm list.
166 #
167 def far_ajax_get_table(request):
168  if request.method == 'GET':
169  rest_data = prep_data('user/farm/get_list/', request.session)
170 
171  for item in rest_data:
172  item['uptime'] = time_from_sec(item['uptime'])
173  item['stateName'] = unicode(farm_states[item['state']])
174  item['stateTooltip'] = unicode(farm_states_help[item['state']])
175 
176  for vm in item['vms']:
177  vm['stateName'] = unicode(vm_states_reversed[vm['state']])
178  vm['pub_ip'] = []
179  for i in vm['leases']:
180  if i['public_ip'] != "":
181  vm['pub_ip'].append(i['public_ip']['address'])
182 
183  vm['priv_ip'] = []
184  for i in vm['leases']:
185  vm['priv_ip'].append(i['address'])
186 
187  vm['cpuLoadPercent'] = int(min(float(vm['cpu_load'].get('60') or 0) * 100, 100))
188  vm['cpuLoadColor'] = "#%02x%02x%02x" % tuple(i * 255 for i in hsv_to_rgb(float(vm['cpuLoadPercent']) / 300, 1.0, 0.8))
189 
190  return messages_ajax.success(rest_data)
191