Statistics
| Branch: | Tag: | Revision:

root / snf-cyclades-app / synnefo / ui / views.py @ fcdd2549

History | View | Annotate | Download (15 kB)

1
# Copyright 2011 GRNET S.A. All rights reserved.
2
#
3
# Redistribution and use in source and binary forms, with or
4
# without modification, are permitted provided that the following
5
# conditions are met:
6
#
7
#   1. Redistributions of source code must retain the above
8
#      copyright notice, this list of conditions and the following
9
#      disclaimer.
10
#
11
#   2. Redistributions in binary form must reproduce the above
12
#      copyright notice, this list of conditions and the following
13
#      disclaimer in the documentation and/or other materials
14
#      provided with the distribution.
15
#
16
# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
17
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
19
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
20
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
23
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
24
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
26
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27
# POSSIBILITY OF SUCH DAMAGE.
28
#
29
# The views and conclusions contained in the software and
30
# documentation are those of the authors and should not be
31
# interpreted as representing official policies, either expressed
32
# or implied, of GRNET S.A.
33
#
34

    
35
import os
36

    
37
from django.conf import settings
38
from django.utils.translation import gettext_lazy as _
39
from django.template import Context, loader
40
from django.http import HttpResponse
41
from django.utils.translation import get_language
42
from django.utils import simplejson as json
43
from django.shortcuts import render_to_response
44
from django.template.loader import render_to_string
45
from django.core.urlresolvers import reverse
46
from django.core.mail import send_mail
47
from django.http import Http404
48
from django.template import RequestContext
49

    
50
from synnefo.util.version import get_component_version
51

    
52
from synnefo.lib.astakos import get_user
53

    
54
SYNNEFO_JS_LIB_VERSION = get_component_version('app')
55

    
56
# api configuration
57
COMPUTE_API_URL = getattr(settings, 'COMPUTE_API_URL', '/api/v1.1')
58

    
59
# UI preferences settings
60
TIMEOUT = getattr(settings, "TIMEOUT", 10000)
61
UPDATE_INTERVAL = getattr(settings, "UI_UPDATE_INTERVAL", 5000)
62
UPDATE_INTERVAL_INCREASE = getattr(settings, "UI_UPDATE_INTERVAL_INCREASE", 500)
63
UPDATE_INTERVAL_INCREASE_AFTER_CALLS_COUNT = getattr(settings,
64
                                "UI_UPDATE_INTERVAL_INCREASE_AFTER_CALLS_COUNT",
65
                                3)
66
UPDATE_INTERVAL_FAST = getattr(settings, "UI_UPDATE_INTERVAL_FAST", 2500)
67
UPDATE_INTERVAL_MAX = getattr(settings, "UI_UPDATE_INTERVAL_MAX", 10000)
68

    
69
# predefined values settings
70
VM_IMAGE_COMMON_METADATA = getattr(settings, "VM_IMAGE_COMMON_METADATA", ["OS"])
71
SUGGESTED_FLAVORS_DEFAULT = {}
72
SUGGESTED_FLAVORS = getattr(settings, "VM_CREATE_SUGGESTED_FLAVORS",
73
                            SUGGESTED_FLAVORS_DEFAULT)
74
SUGGESTED_ROLES_DEFAULT = ["Database server", "File server", "Mail server",
75
                           "Web server", "Proxy"]
76
SUGGESTED_ROLES = getattr(settings, "VM_CREATE_SUGGESTED_ROLES",
77
                          SUGGESTED_ROLES_DEFAULT)
78
IMAGE_ICONS = settings.IMAGE_ICONS
79
IMAGE_DELETED_TITLE = getattr(settings, 'UI_IMAGE_DELETED_TITLE',
80
                            '(deleted image)')
81
IMAGE_DELETED_SIZE_TITLE = getattr(settings, 'UI_IMAGE_DELETED_SIZE_TITLE',
82
                            '(none)')
83

    
84
SUPPORT_SSH_OS_LIST = getattr(settings, "UI_SUPPORT_SSH_OS_LIST",)
85
OS_CREATED_USERS = getattr(settings, "UI_OS_DEFAULT_USER_MAP")
86
LOGOUT_URL = getattr(settings, "UI_LOGOUT_URL", '/im/authenticate')
87
LOGIN_URL = getattr(settings, "UI_LOGIN_URL", '/im/login')
88
AUTH_COOKIE_NAME = getattr(settings, "UI_AUTH_COOKIE_NAME", 'synnefo_user')
89

    
90
# UI behaviour settings
91
DELAY_ON_BLUR = getattr(settings, "UI_DELAY_ON_BLUR", True)
92
UPDATE_HIDDEN_VIEWS = getattr(settings, "UI_UPDATE_HIDDEN_VIEWS", False)
93
HANDLE_WINDOW_EXCEPTIONS = getattr(settings, "UI_HANDLE_WINDOW_EXCEPTIONS", True)
94
SKIP_TIMEOUTS = getattr(settings, "UI_SKIP_TIMEOUTS", 1)
95

    
96
# Additional settings
97
VM_NAME_TEMPLATE = getattr(settings, "VM_CREATE_NAME_TPL", "My {0} server")
98
MAX_SSH_KEYS_PER_USER = getattr(settings, "USERDATA_MAX_SSH_KEYS_PER_USER")
99
FLAVORS_DISK_TEMPLATES_INFO = getattr(settings, "UI_FLAVORS_DISK_TEMPLATES_INFO", {})
100
SYSTEM_IMAGES_OWNERS = getattr(settings, "UI_SYSTEM_IMAGES_OWNERS", {})
101

    
102
# MEDIA PATHS
103
UI_MEDIA_URL = getattr(settings, "UI_MEDIA_URL",
104
                    "%ssnf-%s/" % (settings.MEDIA_URL, SYNNEFO_JS_LIB_VERSION))
105
UI_SYNNEFO_IMAGES_URL = getattr(settings,
106
                    "UI_SYNNEFO_IMAGES_URL", UI_MEDIA_URL + "images/")
107
UI_SYNNEFO_CSS_URL = getattr(settings,
108
                    "UI_SYNNEFO_CSS_URL", UI_MEDIA_URL + "css/")
109
UI_SYNNEFO_JS_URL = getattr(settings,
110
                    "UI_SYNNEFO_JS_URL", UI_MEDIA_URL + "js/")
111
UI_SYNNEFO_JS_LIB_URL = getattr(settings,
112
                    "UI_SYNNEFO_JS_LIB_URL", UI_SYNNEFO_JS_URL + "lib/")
113
UI_SYNNEFO_JS_WEB_URL = getattr(settings,
114
                    "UI_SYNNEFO_JS_WEB_URL",
115
                    UI_SYNNEFO_JS_URL + "ui/web/")
116

    
117
# extensions
118
ENABLE_GLANCE = getattr(settings, 'UI_ENABLE_GLANCE', True)
119
GLANCE_API_URL = getattr(settings, 'UI_GLANCE_API_URL', '/glance')
120
FEEDBACK_CONTACTS = getattr(settings, "FEEDBACK_CONTACTS", [])
121
FEEDBACK_EMAIL_FROM = settings.FEEDBACK_EMAIL_FROM
122

    
123
def template(name, request, context):
124
    template_path = os.path.join(os.path.dirname(__file__), "templates/")
125
    current_template = template_path + name + '.html'
126
    t = loader.get_template(current_template)
127
    media_context = {
128
       'UI_MEDIA_URL': UI_MEDIA_URL,
129
       'SYNNEFO_JS_URL': UI_SYNNEFO_JS_URL,
130
       'SYNNEFO_JS_LIB_URL': UI_SYNNEFO_JS_LIB_URL,
131
       'SYNNEFO_JS_WEB_URL': UI_SYNNEFO_JS_WEB_URL,
132
       'SYNNEFO_IMAGES_URL': UI_SYNNEFO_IMAGES_URL,
133
       'SYNNEFO_CSS_URL': UI_SYNNEFO_CSS_URL,
134
       'SYNNEFO_JS_LIB_VERSION': SYNNEFO_JS_LIB_VERSION,
135
       'DEBUG': settings.DEBUG
136
    }
137
    context.update(media_context)
138
    return HttpResponse(t.render(RequestContext(request, context)))
139

    
140
def home(request):
141
    context = {'timeout': TIMEOUT,
142
               'project': '+nefo',
143
               'request': request,
144
               'current_lang': get_language() or 'en',
145
               'compute_api_url': json.dumps(COMPUTE_API_URL),
146
                # update interval settings
147
               'update_interval': UPDATE_INTERVAL,
148
               'update_interval_increase': UPDATE_INTERVAL_INCREASE,
149
               'update_interval_increase_after_calls': UPDATE_INTERVAL_INCREASE_AFTER_CALLS_COUNT,
150
               'update_interval_fast': UPDATE_INTERVAL_FAST,
151
               'update_interval_max': UPDATE_INTERVAL_MAX,
152
                # additional settings
153
               'image_icons': IMAGE_ICONS,
154
               'logout_redirect': LOGOUT_URL,
155
               'login_redirect': LOGIN_URL,
156
               'auth_cookie_name': AUTH_COOKIE_NAME,
157
               'suggested_flavors': json.dumps(SUGGESTED_FLAVORS),
158
               'suggested_roles': json.dumps(SUGGESTED_ROLES),
159
               'vm_image_common_metadata': json.dumps(VM_IMAGE_COMMON_METADATA),
160
               'synnefo_version': SYNNEFO_JS_LIB_VERSION,
161
               'delay_on_blur': json.dumps(DELAY_ON_BLUR),
162
               'update_hidden_views': json.dumps(UPDATE_HIDDEN_VIEWS),
163
               'handle_window_exceptions': json.dumps(HANDLE_WINDOW_EXCEPTIONS),
164
               'skip_timeouts': json.dumps(SKIP_TIMEOUTS),
165
               'vm_name_template': json.dumps(VM_NAME_TEMPLATE),
166
               'flavors_disk_templates_info': json.dumps(FLAVORS_DISK_TEMPLATES_INFO),
167
               'support_ssh_os_list': json.dumps(SUPPORT_SSH_OS_LIST),
168
               'os_created_users': json.dumps(OS_CREATED_USERS),
169
               'userdata_keys_limit': json.dumps(MAX_SSH_KEYS_PER_USER),
170
               'use_glance': json.dumps(ENABLE_GLANCE),
171
               'glance_api_url': json.dumps(GLANCE_API_URL),
172
               'system_images_owners': json.dumps(SYSTEM_IMAGES_OWNERS),
173
               'image_deleted_title': json.dumps(IMAGE_DELETED_TITLE),
174
               'image_deleted_size_title': json.dumps(IMAGE_DELETED_SIZE_TITLE),
175
               }
176
    return template('home', request, context)
177

    
178
def machines_console(request):
179
    host, port, password = ('','','')
180
    host = request.GET.get('host','')
181
    port = request.GET.get('port','')
182
    password = request.GET.get('password','')
183
    machine = request.GET.get('machine','')
184
    host_ip = request.GET.get('host_ip','')
185
    host_ip_v6 = request.GET.get('host_ip_v6','')
186
    context = {'host': host, 'port': port, 'password': password,
187
               'machine': machine, 'host_ip': host_ip, 'host_ip_v6': host_ip_v6}
188
    return template('machines_console', request, context)
189

    
190
def js_tests(request):
191
    return template('tests', request, {})
192

    
193
CONNECT_LINUX_LINUX_MESSAGE = _("""A direct connection to this machine can be established using the <a target="_blank"
194
href="http://en.wikipedia.org/wiki/Secure_Shell">SSH Protocol</a>.
195
To do so open a terminal and type the following at the prompt to connect to your machine:""")
196
CONNECT_LINUX_WINDOWS_MESSAGE = _("""A direct connection to this machine can be
197
established using <a target="_blank" href="http://en.wikipedia.org/wiki/Remote_Desktop_Services">Remote Desktop Service</a>.
198
To do so, open the following file with an appropriate remote desktop client.""")
199
CONNECT_LINUX_WINDOWS_SUBMESSAGE = _("""If you don't have one already
200
installed, we suggest the use of <a target="_blank" href="http://sourceforge.net/projects/tsclient/files/tsclient/tsclient-unstable/tsclient-2.0.1.tar.bz2/download">tsclient</a>.""")
201
CONNECT_WINDOWS_LINUX_MESSAGE = _("""A direct connection to this machine can be established using the <a target="_blank"
202
href="http://en.wikipedia.org/wiki/Secure_Shell">SSH Protocol</a>.
203
Open an ssh client such as PuTTY and type the following:""")
204
CONNECT_WINDOWS_LINUX_SUBMESSAGE = _("""If you do not have an ssh client already installed,
205
<a target="_blank" href="http://the.earth.li/~sgtatham/putty/latest/x86/putty.exe">Download PuTTY</a>""")
206

    
207
CONNECT_WINDOWS_WINDOWS_MESSAGE = _("""A direct connection to this machine can be
208
established using Remote Desktop. Click on the following link, and if asked open it using "Remote Desktop Connection" """)
209
CONNECT_WINDOWS_WINDOWS_SUBMESSAGE = _("""Save this file to disk for future use""")
210

    
211
# info/subinfo for all os combinations
212
#
213
# [0] info gets displayed on top of the message box
214
# [1] subinfo gets displayed on the bottom as extra info
215
# provided to the user when needed
216
CONNECT_PROMPT_MESSAGES = {
217
    'linux': {
218
            'linux': [CONNECT_LINUX_LINUX_MESSAGE, ""],
219
            'windows': [CONNECT_LINUX_WINDOWS_MESSAGE,
220
                        CONNECT_LINUX_WINDOWS_SUBMESSAGE]
221
        },
222
    'windows': {
223
            'linux': [CONNECT_WINDOWS_LINUX_MESSAGE,
224
                      CONNECT_WINDOWS_LINUX_SUBMESSAGE],
225
            'windows': [CONNECT_WINDOWS_WINDOWS_MESSAGE,
226
                        CONNECT_WINDOWS_WINDOWS_SUBMESSAGE]
227
        }
228
    }
229

    
230
# retrieve domain prefix from settings
231
DOMAIN_PREFIX = getattr(settings, 'MACHINE_DOMAIN_PREFIX', getattr(settings,
232
                        'BACKEND_PREFIX_ID', ""))
233

    
234
# domain template string
235
DOMAIN_TPL = "%s%%s" % DOMAIN_PREFIX
236

    
237
def machines_connect(request):
238
    ip_address = request.GET.get('ip_address','')
239
    operating_system = metadata_os = request.GET.get('os','')
240
    server_id = request.GET.get('srv', 0)
241
    host_os = request.GET.get('host_os','Linux').lower()
242
    username = request.GET.get('username', None)
243
    domain = request.GET.get("domain", DOMAIN_TPL % int(server_id))
244

    
245
    # guess host os
246
    if host_os != "windows":
247
        host_os = 'linux'
248

    
249
    # guess username
250
    if not username:
251
        username = "root"
252

    
253
        if metadata_os.lower() in ['ubuntu', 'kubuntu', 'fedora']:
254
            username = "user"
255

    
256
        if metadata_os.lower() == "windows":
257
            username = "Administrator"
258

    
259
    # operating system provides ssh access
260
    ssh = False
261
    if operating_system != "windows":
262
        operating_system = "linux"
263
        ssh = True
264

    
265
    # rdp param is set, the user requested rdp file
266
    # check if we are on windows
267
    if operating_system == 'windows' and request.GET.get("rdp", False):
268

    
269
        # UI sent domain info (from vm metadata) use this
270
        # otherwise use our default snf-<vm_id> domain
271
        rdp_context = {
272
                'username': username,
273
                'domain': domain,
274
                'ip_address': ip_address
275
        }
276

    
277
        rdp_file_data = render_to_string("synnefo-windows.rdp", rdp_context)
278
        response = HttpResponse(rdp_file_data, mimetype='application/x-rdp')
279

    
280
        # proper filename, use server id and ip address
281
        filename = "%d-%s.rdp" % (int(server_id), ip_address)
282
        response['Content-Disposition'] = 'attachment; filename=%s' % filename
283
    else:
284
        link_title = _("Remote desktop to %s") % ip_address
285
        link_url = "%s?ip_address=%s&os=%s&rdp=1&srv=%d&username=%s&domain=%s" % (
286
                reverse("machines-connect"), ip_address, operating_system,int(server_id), username, domain)
287

    
288
        if (operating_system != "windows"):
289
            link_title = "ssh %s@%s" % (username, ip_address)
290
            link_url = None
291

    
292
            if host_os == "windows":
293
                link_title = "%s@%s" % (username, ip_address)
294

    
295
        # try to find a specific message
296
        try:
297
            connect_message = CONNECT_PROMPT_MESSAGES[host_os][operating_system][0]
298
            subinfo = CONNECT_PROMPT_MESSAGES[host_os][operating_system][1]
299
        except KeyError:
300
            connect_message = _("You are trying to connect from a %s "
301
                                "machine to a %s machine") % (host_os, operating_system)
302
            subinfo = ""
303

    
304
        response_object = {
305
                'ip': ip_address,
306
                'os': operating_system,
307
                'ssh': ssh,
308
                'info': unicode(connect_message),
309
                'subinfo': unicode(subinfo),
310
                'link': {'title': unicode(link_title), 'url': link_url}
311
            }
312
        response = HttpResponse(json.dumps(response_object),
313
                                mimetype='application/json')  #no windows, no rdp
314

    
315
    return response
316

    
317
def feedback_submit(request):
318
    if not request.method == "POST":
319
        raise Http404
320

    
321
    # fill request object with astakos user information
322
    get_user(request, settings.ASTAKOS_URL)
323

    
324
    message = request.POST.get("feedback-msg")
325
    data = request.POST.get("feedback-data")
326

    
327
    # default to True (calls from error pages)
328
    allow_data_send = request.POST.get("feedback-submit-data", True)
329

    
330
    mail_subject = unicode(_("Feedback from synnefo application"))
331

    
332
    mail_context = {'message': message, 'data': data,
333
                    'allow_data_send': allow_data_send, 'request': request}
334
    mail_content = render_to_string("feedback_mail.txt", mail_context)
335

    
336
    send_mail(mail_subject, mail_content, FEEDBACK_EMAIL_FROM,
337
            dict(FEEDBACK_CONTACTS).values(), fail_silently=False)
338

    
339
    return HttpResponse('{"status":"send"}');
340