Statistics
| Branch: | Tag: | Revision:

root / ui / views.py @ c4e70532

History | View | Annotate | Download (13.6 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
import os
35
from django.conf import settings
36
from django.utils.translation import gettext_lazy as _
37
from django.template import Context, loader
38
from django.http import HttpResponse
39
from django.utils.translation import get_language
40
from django.utils import simplejson as json
41
from django.shortcuts import render_to_response
42
from django.template.loader import render_to_string
43
from django.core.urlresolvers import reverse
44

    
45
from django.core.mail import send_mail
46

    
47
from django.http import Http404
48

    
49
SYNNEFO_JS_LIB_VERSION = "0.7"
50

    
51
IMAGE_ICONS = settings.IMAGE_ICONS
52
LOGOUT_URL = getattr(settings, "LOGOUT_URL", settings.LOGIN_URL)
53
INVITATIONS_PER_PAGE = getattr(settings, "INVITATIONS_PER_PAGE", 10)
54

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

    
65
# predefined values settings
66
VM_IMAGE_COMMON_METADATA = getattr(settings, "VM_IMAGE_COMMON_METADATA", ["OS"])
67
SUGGESTED_FLAVORS_DEFAULT = {}
68
SUGGESTED_FLAVORS = getattr(settings, "VM_CREATE_SUGGESTED_FLAVORS",
69
                            SUGGESTED_FLAVORS_DEFAULT)
70
SUGGESTED_ROLES_DEFAULT = ["Database server", "File server", "Mail server",
71
                           "Web server", "Proxy"]
72
SUGGESTED_ROLES = getattr(settings, "VM_CREATE_SUGGESTED_ROLES",
73
                          SUGGESTED_ROLES_DEFAULT)
74

    
75
SUPPORT_SSH_OS_LIST = getattr(settings, "UI_SUPPORT_SSH_OS_LIST",)
76

    
77
OS_CREATED_USERS = getattr(settings, "UI_OS_DEFAULT_USER_MAP")
78

    
79
# UI behaviour settings
80
DELAY_ON_BLUR = getattr(settings, "UI_DELAY_ON_BLUR", True)
81
UPDATE_HIDDEN_VIEWS = getattr(settings, "UI_UPDATE_HIDDEN_VIEWS", False)
82
HANDLE_WINDOW_EXCEPTIONS = getattr(settings, "UI_HANDLE_WINDOW_EXCEPTIONS", True)
83
SKIP_TIMEOUTS = getattr(settings, "UI_SKIP_TIMEOUTS", 1)
84

    
85
# MEDIA PATHS
86
UI_MEDIA_URL = getattr(settings, "UI_MEDIA_URL",
87
                    "%ssnf-%s/" % (settings.MEDIA_URL, SYNNEFO_JS_LIB_VERSION))
88
UI_SYNNEFO_IMAGES_URL = getattr(settings,
89
                    "UI_SYNNEFO_IMAGES_URL", UI_MEDIA_URL + "images/")
90
UI_SYNNEFO_CSS_URL = getattr(settings,
91
                    "UI_SYNNEFO_CSS_URL", UI_MEDIA_URL + "css/")
92
UI_SYNNEFO_JS_URL = getattr(settings,
93
                    "UI_SYNNEFO_JS_URL", UI_MEDIA_URL + "js/")
94
UI_SYNNEFO_JS_LIB_URL = getattr(settings,
95
                    "UI_SYNNEFO_JS_LIB_URL", UI_SYNNEFO_JS_URL + "lib/")
96
UI_SYNNEFO_JS_WEB_URL = getattr(settings,
97
                    "UI_SYNNEFO_JS_WEB_URL",
98
                    UI_SYNNEFO_JS_URL + "ui/web/")
99

    
100
VM_NAME_TEMPLATE = getattr(settings, "VM_CREATE_NAME_TPL", "My {0} server")
101

    
102
# ssh keys
103
MAX_SSH_KEYS_PER_USER = getattr(settings, "USERDATA_MAX_SSH_KEYS_PER_USER")
104

    
105
FLAVORS_DISK_TEMPLATES_INFO = getattr(settings, "UI_FLAVORS_DISK_TEMPLATES_INFO", {})
106

    
107
def template(name, context):
108
    template_path = os.path.join(os.path.dirname(__file__), "templates/")
109
    current_template = template_path + name + '.html'
110
    t = loader.get_template(current_template)
111
    media_context = {
112
       'UI_MEDIA_URL': UI_MEDIA_URL,
113
       'SYNNEFO_JS_URL': UI_SYNNEFO_JS_URL,
114
       'SYNNEFO_JS_LIB_URL': UI_SYNNEFO_JS_LIB_URL,
115
       'SYNNEFO_JS_WEB_URL': UI_SYNNEFO_JS_WEB_URL,
116
       'SYNNEFO_IMAGES_URL': UI_SYNNEFO_IMAGES_URL,
117
       'SYNNEFO_CSS_URL': UI_SYNNEFO_CSS_URL,
118
       'SYNNEFO_JS_LIB_VERSION': SYNNEFO_JS_LIB_VERSION,
119
       'DEBUG': settings.DEBUG
120
    }
121
    context.update(media_context)
122
    return HttpResponse(t.render(Context(context)))
123

    
124
def home(request):
125
    context = {'timeout': TIMEOUT,
126
               'project': '+nefo',
127
               'request': request,
128
               'current_lang': get_language() or 'en',
129

    
130
               'update_interval': UPDATE_INTERVAL,
131
               'update_interval_increase': UPDATE_INTERVAL_INCREASE,
132
               'update_interval_increase_after_calls': UPDATE_INTERVAL_INCREASE_AFTER_CALLS_COUNT,
133
               'update_interval_fast': UPDATE_INTERVAL_FAST,
134
               'update_interval_max': UPDATE_INTERVAL_MAX,
135

    
136
               'image_icons': IMAGE_ICONS,
137
               'logout_redirect': LOGOUT_URL,
138
               'suggested_flavors': json.dumps(SUGGESTED_FLAVORS),
139
               'suggested_roles': json.dumps(SUGGESTED_ROLES),
140
               'vm_image_common_metadata': json.dumps(VM_IMAGE_COMMON_METADATA),
141
               'synnefo_version': SYNNEFO_JS_LIB_VERSION,
142
               'invitations_per_page': INVITATIONS_PER_PAGE,
143
               'delay_on_blur': json.dumps(DELAY_ON_BLUR),
144
               'update_hidden_views': json.dumps(UPDATE_HIDDEN_VIEWS),
145
               'handle_window_exceptions': json.dumps(HANDLE_WINDOW_EXCEPTIONS),
146
               'skip_timeouts': json.dumps(SKIP_TIMEOUTS),
147
               'vm_name_template': json.dumps(VM_NAME_TEMPLATE),
148
               'flavors_disk_templates_info': json.dumps(FLAVORS_DISK_TEMPLATES_INFO),
149
               'support_ssh_os_list': json.dumps(SUPPORT_SSH_OS_LIST),
150
               'os_created_users': json.dumps(OS_CREATED_USERS),
151
               'userdata_keys_limit': json.dumps(MAX_SSH_KEYS_PER_USER),
152
               }
153
    return template('home', context)
154

    
155
def machines_console(request):
156
    host, port, password = ('','','')
157
    host = request.GET.get('host','')
158
    port = request.GET.get('port','')
159
    password = request.GET.get('password','')
160
    machine = request.GET.get('machine','')
161
    host_ip = request.GET.get('host_ip','')
162
    host_ip_v6 = request.GET.get('host_ip_v6','')
163
    context = {'host': host, 'port': port, 'password': password,
164
               'machine': machine, 'host_ip': host_ip, 'host_ip_v6': host_ip_v6}
165
    return template('machines_console', context)
166

    
167
def js_tests(request):
168
    return template('tests', {})
169

    
170
CONNECT_LINUX_LINUX_MESSAGE = _("""A direct connection to this machine can be established using the <a target="_blank"
171
href="http://en.wikipedia.org/wiki/Secure_Shell">SSH Protocol</a>.
172
To do so open a terminal and type the following at the prompt to connect to your machine:""")
173
CONNECT_LINUX_WINDOWS_MESSAGE = _("""A direct connection to this machine can be
174
established using <a target="_blank" href="http://en.wikipedia.org/wiki/Remote_Desktop_Services">Remote Desktop Service</a>.
175
To do so, open the following file with an appropriate remote desktop client.""")
176
CONNECT_LINUX_WINDOWS_SUBMESSAGE = _("""If you don't have one already
177
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>.""")
178
CONNECT_WINDOWS_LINUX_MESSAGE = _("""A direct connection to this machine can be established using the <a target="_blank"
179
href="http://en.wikipedia.org/wiki/Secure_Shell">SSH Protocol</a>.
180
Open an ssh client such as PuTTY and type the following:""")
181
CONNECT_WINDOWS_LINUX_SUBMESSAGE = _("""If you do not have an ssh client already installed,
182
<a target="_blank" href="http://the.earth.li/~sgtatham/putty/latest/x86/putty.exe">Download PuTTY</a>""")
183

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

    
188
# info/subinfo for all os combinations
189
#
190
# [0] info gets displayed on top of the message box
191
# [1] subinfo gets displayed on the bottom as extra info
192
# provided to the user when needed
193
CONNECT_PROMPT_MESSAGES = {
194
    'linux': {
195
            'linux': [CONNECT_LINUX_LINUX_MESSAGE, ""],
196
            'windows': [CONNECT_LINUX_WINDOWS_MESSAGE,
197
                        CONNECT_LINUX_WINDOWS_SUBMESSAGE]
198
        },
199
    'windows': {
200
            'linux': [CONNECT_WINDOWS_LINUX_MESSAGE,
201
                      CONNECT_WINDOWS_LINUX_SUBMESSAGE],
202
            'windows': [CONNECT_WINDOWS_WINDOWS_MESSAGE,
203
                        CONNECT_WINDOWS_WINDOWS_SUBMESSAGE]
204
        }
205
    }
206

    
207
# retrieve domain prefix from settings
208
DOMAIN_PREFIX = getattr(settings, 'MACHINE_DOMAIN_PREFIX', getattr(settings,
209
                        'BACKEND_PREFIX_ID', ""))
210

    
211
# domain template string
212
DOMAIN_TPL = "%s%%s" % DOMAIN_PREFIX
213

    
214
def machines_connect(request):
215
    ip_address = request.GET.get('ip_address','')
216
    operating_system = metadata_os = request.GET.get('os','')
217
    server_id = request.GET.get('srv', 0)
218
    host_os = request.GET.get('host_os','Linux').lower()
219
    username = request.GET.get('username', None)
220
    domain = request.GET.get("domain", DOMAIN_TPL % int(server_id))
221

    
222
    # guess host os
223
    if host_os != "windows":
224
        host_os = 'linux'
225

    
226
    # guess username
227
    if not username:
228
        username = "root"
229

    
230
        if metadata_os.lower() in ['ubuntu', 'kubuntu', 'fedora']:
231
            username = "user"
232

    
233
        if metadata_os.lower() == "windows":
234
            username = "Administrator"
235

    
236
    # operating system provides ssh access
237
    ssh = False
238
    if operating_system != "windows":
239
        operating_system = "linux"
240
        ssh = True
241

    
242
    # rdp param is set, the user requested rdp file
243
    # check if we are on windows
244
    if operating_system == 'windows' and request.GET.get("rdp", False):
245

    
246
        # UI sent domain info (from vm metadata) use this
247
        # otherwise use our default snf-<vm_id> domain
248
        rdp_context = {
249
                'username': username,
250
                'domain': domain,
251
                'ip_address': ip_address
252
        }
253

    
254
        rdp_file_data = render_to_string("synnefo-windows.rdp", rdp_context)
255
        response = HttpResponse(rdp_file_data, mimetype='application/x-rdp')
256

    
257
        # proper filename, use server id and ip address
258
        filename = "%d-%s.rdp" % (int(server_id), ip_address)
259
        response['Content-Disposition'] = 'attachment; filename=%s' % filename
260
    else:
261
        link_title = _("Remote desktop to %s") % ip_address
262
        link_url = "%s?ip_address=%s&os=%s&rdp=1&srv=%d&username=%s&domain=%s" % (
263
                reverse("machines-connect"), ip_address, operating_system,int(server_id), username, domain)
264

    
265
        if (operating_system != "windows"):
266
            link_title = "ssh %s@%s" % (username, ip_address)
267
            link_url = None
268

    
269
            if host_os == "windows":
270
                link_title = "%s@%s" % (username, ip_address)
271

    
272
        # try to find a specific message
273
        try:
274
            connect_message = CONNECT_PROMPT_MESSAGES[host_os][operating_system][0]
275
            subinfo = CONNECT_PROMPT_MESSAGES[host_os][operating_system][1]
276
        except KeyError:
277
            connect_message = _("You are trying to connect from a %s "
278
                                "machine to a %s machine") % (host_os, operating_system)
279
            subinfo = ""
280

    
281
        response_object = {
282
                'ip': ip_address,
283
                'os': operating_system,
284
                'ssh': ssh,
285
                'info': unicode(connect_message),
286
                'subinfo': unicode(subinfo),
287
                'link': {'title': unicode(link_title), 'url': link_url}
288
            }
289
        response = HttpResponse(json.dumps(response_object),
290
                                mimetype='application/json')  #no windows, no rdp
291

    
292
    return response
293

    
294
FEEDBACK_CONTACTS = getattr(settings, "FEEDBACK_CONTACTS", [])
295
FEEDBACK_EMAIL_FROM = settings.FEEDBACK_EMAIL_FROM
296

    
297
def feedback_submit(request):
298
    if not request.method == "POST":
299
        raise Http404
300

    
301
    message = request.POST.get("feedback-msg")
302
    data = request.POST.get("feedback-data")
303

    
304
    # default to True (calls from error pages)
305
    allow_data_send = request.POST.get("feedback-submit-data", True)
306

    
307
    mail_subject = unicode(_("Feedback from synnefo application"))
308

    
309
    mail_context = {'message': message, 'data': data,
310
                    'allow_data_send': allow_data_send, 'request': request}
311
    mail_content = render_to_string("feedback_mail.txt", mail_context)
312

    
313
    send_mail(mail_subject, mail_content, FEEDBACK_EMAIL_FROM,
314
            dict(FEEDBACK_CONTACTS).values(), fail_silently=False)
315

    
316
    return HttpResponse('{"status":"send"}');
317