Statistics
| Branch: | Tag: | Revision:

root / ui / views.py @ 66be390b

History | View | Annotate | Download (11.8 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
IMAGE_ICONS = settings.IMAGE_ICONS
50
LOGOUT_URL = getattr(settings, "LOGOUT_URL", settings.LOGIN_URL)
51
INVITATIONS_PER_PAGE = getattr(settings, "INVITATIONS_PER_PAGE", 10)
52

    
53
# UI preferences settings
54
TIMEOUT = getattr(settings, "TIMEOUT", 10000)
55
UPDATE_INTERVAL = getattr(settings, "UPDATE_INTERVAL", 5000)
56

    
57
# predefined values settings
58
VM_IMAGE_COMMON_METADATA = getattr(settings, "VM_IMAGE_COMMON_METADATA", ["OS"])
59
SUGGESTED_FLAVORS_DEFAULT = {}
60
SUGGESTED_FLAVORS = getattr(settings, "VM_CREATE_SUGGESTED_FLAVORS", SUGGESTED_FLAVORS_DEFAULT)
61
SUGGESTED_ROLES_DEFAULT = ["Database server", "File server", "Mail server", "Web server", "Proxy"]
62
SUGGESTED_ROLES = getattr(settings, "VM_CREATE_SUGGESTED_ROLES", SUGGESTED_ROLES_DEFAULT)
63

    
64
# UI behaviour settings
65
DELAY_ON_BLUR = getattr(settings, "UI_DELAY_ON_BLUR", True)
66
BLUR_DELAY = getattr(settings, "UI_BLUR_DELAY", 8000)
67
UPDATE_HIDDEN_VIEWS = getattr(settings, "UI_UPDATE_HIDDEN_VIEWS", False)
68
HANDLE_WINDOW_EXCEPTIONS = getattr(settings, "UI_HANDLE_WINDOW_EXCEPTIONS", True)
69
SKIP_TIMEOUTS = getattr(settings, "UI_SKIP_TIMEOUTS", 1)
70

    
71
def template(name, context):
72
    template_path = os.path.join(os.path.dirname(__file__), "templates/")
73
    current_template = template_path + name + '.html'
74
    t = loader.get_template(current_template)
75
    return HttpResponse(t.render(Context(context)))
76

    
77
def home(request):
78
    context = {'timeout': TIMEOUT,
79
               'project': '+nefo',
80
               'request': request,
81
               'current_lang': get_language() or 'en',
82
               'update_interval': UPDATE_INTERVAL,
83
               'image_icons': IMAGE_ICONS,
84
               'logout_redirect': LOGOUT_URL,
85
               'suggested_flavors': json.dumps(SUGGESTED_FLAVORS),
86
               'suggested_roles': json.dumps(SUGGESTED_ROLES),
87
               'vm_image_common_metadata': json.dumps(VM_IMAGE_COMMON_METADATA),
88
               'invitations_per_page': INVITATIONS_PER_PAGE,
89
               'delay_on_blur': json.dumps(DELAY_ON_BLUR),
90
               'blur_delay': json.dumps(BLUR_DELAY),
91
               'update_hidden_views': json.dumps(UPDATE_HIDDEN_VIEWS),
92
               'handle_window_exceptions': json.dumps(HANDLE_WINDOW_EXCEPTIONS),
93
               'skip_timeouts': json.dumps(SKIP_TIMEOUTS),
94
               'DEBUG': settings.DEBUG}
95
    return template('home', context)
96

    
97
def machines(request):
98
    context = {'default_keywords': settings.DEFAULT_KEYWORDS}
99
    return template('machines', context)
100

    
101
def machines_icon(request):
102
    context = {'default_keywords': settings.DEFAULT_KEYWORDS}
103
    return template('machines_icon', context)
104

    
105
def machines_list(request):
106
    context = {'default_keywords': settings.DEFAULT_KEYWORDS}
107
    return template('machines_list', context)
108

    
109
def machines_single(request):
110
    context = {'default_keywords': settings.DEFAULT_KEYWORDS}
111
    return template('machines_single', context)
112

    
113
def machines_console(request):
114
    host, port, password = ('','','')
115
    host = request.GET.get('host','')
116
    port = request.GET.get('port','')
117
    password = request.GET.get('password','')
118
    machine = request.GET.get('machine','')
119
    host_ip = request.GET.get('host_ip','')
120
    host_ip_v6 = request.GET.get('host_ip_v6','')
121
    context = {'host': host, 'port': port, 'password': password, 'machine': machine, 'host_ip': host_ip, 'host_ip_v6': host_ip_v6}
122
    return template('machines_console', context)
123

    
124
def js_tests(request):
125
    return template('tests', {})
126

    
127
CONNECT_LINUX_LINUX_MESSAGE = _("""A direct connection to this machine can be established using the <a target="_blank"
128
href="http://en.wikipedia.org/wiki/Secure_Shell">SSH Protocol</a>.
129
To do so open a terminal and type the following at the prompt to connect to your machine:""")
130
CONNECT_LINUX_WINDOWS_MESSAGE = _("""A direct connection to this machine can be
131
established using <a target="_blank" href="http://en.wikipedia.org/wiki/Remote_Desktop_Services">Remote Desktop Service</a>.
132
To do so, open the following file with an appropriate remote desktop client.""")
133
CONNECT_LINUX_WINDOWS_SUBMESSAGE = _("""If you don't have one already
134
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>.""")
135
CONNECT_WINDOWS_LINUX_MESSAGE = _("""A direct connection to this machine can be established using the <a target="_blank"
136
href="http://en.wikipedia.org/wiki/Secure_Shell">SSH Protocol</a>.
137
Open an ssh client such as PuTTY and type the following:""")
138
CONNECT_WINDOWS_LINUX_SUBMESSAGE = _("""If you do not have an ssh client already installed,
139
<a target="_blank" href="http://the.earth.li/~sgtatham/putty/latest/x86/putty.exe">Download PuTTY</a>""")
140

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

    
145
# info/subinfo for all os combinations
146
#
147
# [0] info gets displayed on top of the message box
148
# [1] subinfo gets displayed on the bottom as extra info
149
# provided to the user when needed
150
CONNECT_PROMPT_MESSAGES = {
151
    'linux': {
152
            'linux': [CONNECT_LINUX_LINUX_MESSAGE, ""],
153
            'windows': [CONNECT_LINUX_WINDOWS_MESSAGE, CONNECT_LINUX_WINDOWS_SUBMESSAGE]
154
        },
155
    'windows': {
156
            'linux': [CONNECT_WINDOWS_LINUX_MESSAGE, CONNECT_WINDOWS_LINUX_SUBMESSAGE],
157
            'windows': [CONNECT_WINDOWS_WINDOWS_MESSAGE, CONNECT_WINDOWS_WINDOWS_SUBMESSAGE]
158
        }
159
    }
160

    
161
# retrieve domain prefix from settings
162
DOMAIN_PREFIX = getattr(settings, 'MACHINE_DOMAIN_PREFIX', getattr(settings, 'BACKEND_PREFIX_ID', ""))
163

    
164
# domain template string
165
DOMAIN_TPL = "%s%%s" % DOMAIN_PREFIX
166

    
167
def machines_connect(request):
168
    ip_address = request.GET.get('ip_address','')
169
    operating_system = metadata_os = request.GET.get('os','')
170
    server_id = request.GET.get('srv', 0)
171
    host_os = request.GET.get('host_os','Linux').lower()
172
    username = request.GET.get('username', None)
173
    domain = request.GET.get("domain", DOMAIN_TPL % int(server_id))
174

    
175
    # guess host os
176
    if host_os != "windows":
177
        host_os = 'linux'
178

    
179
    # guess username
180
    if not username:
181
        username = "root"
182

    
183
        if metadata_os.lower() in ['ubuntu', 'kubuntu', 'fedora']:
184
            username = "user"
185

    
186
        if metadata_os.lower() == "windows":
187
            username = "Administrator"
188

    
189
    # operating system provides ssh access
190
    ssh = False
191
    if operating_system != "windows":
192
        operating_system = "linux"
193
        ssh = True
194

    
195
    # rdp param is set, the user requested rdp file
196
    # check if we are on windows
197
    if operating_system == 'windows' and request.GET.get("rdp", False):
198

    
199
        # UI sent domain info (from vm metadata) use this
200
        # otherwise use our default snf-<vm_id> domain
201
        rdp_context = {
202
                'username': username,
203
                'domain': domain,
204
                'ip_address': ip_address
205
        }
206

    
207
        rdp_file_data = render_to_string("synnefo-windows.rdp", rdp_context)
208
        response = HttpResponse(rdp_file_data, mimetype='application/x-rdp')
209

    
210
        # proper filename, use server id and ip address
211
        filename = "%d-%s.rdp" % (int(server_id), ip_address)
212
        response['Content-Disposition'] = 'attachment; filename=%s' % filename
213
    else:
214
        link_title = _("Remote desktop to %s") % ip_address
215
        link_url = "%s?ip_address=%s&os=%s&rdp=1&srv=%d&username=%s&domain=%s" % (
216
                reverse("machines-connect"), ip_address, operating_system,int(server_id), username, domain)
217

    
218
        if (operating_system != "windows"):
219
            link_title = "ssh %s@%s" % (username, ip_address)
220
            link_url = None
221

    
222
            if host_os == "windows":
223
                link_title = "%s@%s" % (username, ip_address)
224

    
225
        # try to find a specific message
226
        try:
227
            connect_message = CONNECT_PROMPT_MESSAGES[host_os][operating_system][0]
228
            subinfo = CONNECT_PROMPT_MESSAGES[host_os][operating_system][1]
229
        except KeyError:
230
            connect_message = _("You are trying to connect from a %s machine to a %s machine") % (host_os, operating_system)
231
            subinfo = ""
232

    
233
        response_object = {
234
                'ip': ip_address,
235
                'os': operating_system,
236
                'ssh': ssh,
237
                'info': unicode(connect_message),
238
                'subinfo': unicode(subinfo),
239
                'link': {'title': unicode(link_title), 'url': link_url}
240
            }
241
        response = HttpResponse(json.dumps(response_object), mimetype='application/json')  #no windows, no rdp
242

    
243
    return response
244

    
245
FEEDBACK_CONTACTS = getattr(settings, "FEEDBACK_CONTACTS", [])
246
FEEDBACK_EMAIL_FROM = settings.FEEDBACK_EMAIL_FROM
247

    
248
def feedback_submit(request):
249
    if not request.method == "POST":
250
        raise Http404
251

    
252
    message = request.POST.get("feedback-msg")
253
    data = request.POST.get("feedback-data")
254

    
255
    # default to True (calls from error pages)
256
    allow_data_send = request.POST.get("feedback-submit-data", True)
257

    
258
    mail_subject = unicode(_("Feedback from synnefo application"))
259

    
260
    mail_context = {'message': message, 'data': data, 'allow_data_send': allow_data_send, 'request': request}
261
    mail_content = render_to_string("feedback_mail.txt", mail_context)
262

    
263
    send_mail(mail_subject, mail_content, FEEDBACK_EMAIL_FROM,
264
            dict(FEEDBACK_CONTACTS).values(), fail_silently=False)
265

    
266
    return HttpResponse('{"status":"send"}');
267

    
268
def images(request):
269
    context = {}
270
    return template('images', context)
271

    
272
def disks(request):
273
    context = {}
274
    return template('disks', context)
275

    
276
def networks(request):
277
    context = {}
278
    return template('networks', context)
279

    
280
def files(request):
281
    context = {}
282
    return template('files', context)
283

    
284
def desktops(request):
285
    context = {}
286
    return template('desktops', context)
287

    
288
def apps(request):
289
    context = {}
290
    return template('apps', context)