Statistics
| Branch: | Tag: | Revision:

root / ui / views.py @ b9ff7260

History | View | Annotate | Download (11 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
TIMEOUT = settings.TIMEOUT
50
UPDATE_INTERVAL = settings.UPDATE_INTERVAL
51
IMAGE_ICONS = settings.IMAGE_ICONS
52
LOGOUT_URL = getattr(settings, "LOGOUT_URL", settings.LOGIN_URL)
53
SUGGESTED_FLAVORS = getattr(settings, "SUGGESTED_FLAVORS", {})
54
SUGGESTED_ROLES = getattr(settings, "SUGGESTED_ROLES",
55
        ["Database server", "File server", "Mail server", "Web server", "Proxy", "CI server", "Leeching machine"])
56
VM_IMAGE_COMMON_METADATA = getattr(settings, "VM_IMAGE_COMMON_METADATA", ["OS"])
57
INVITATIONS_PER_PAGE = getattr(settings, "INVITATIONS_PER_PAGE", 10)
58

    
59
def template(name, context):
60
    template_path = os.path.join(os.path.dirname(__file__), "templates/")
61
    current_template = template_path + name + '.html'
62
    t = loader.get_template(current_template)
63
    return HttpResponse(t.render(Context(context)))
64

    
65
def home(request):
66
    context = {'timeout': TIMEOUT,
67
               'project': '+nefo',
68
               'request': request,
69
               'current_lang': get_language() or 'en',
70
               'update_interval': UPDATE_INTERVAL,
71
               'image_icons': IMAGE_ICONS,
72
               'logout_redirect': LOGOUT_URL,
73
               'suggested_flavors': json.dumps(SUGGESTED_FLAVORS),
74
               'suggested_roles': json.dumps(SUGGESTED_ROLES),
75
               'vm_image_common_metadata': json.dumps(VM_IMAGE_COMMON_METADATA),
76
               'invitations_per_page': INVITATIONS_PER_PAGE,
77
               'DEBUG': settings.DEBUG}
78
    return template('home', context)
79

    
80
def machines(request):
81
    context = {'default_keywords': settings.DEFAULT_KEYWORDS}
82
    return template('machines', context)
83

    
84
def machines_icon(request):
85
    context = {'default_keywords': settings.DEFAULT_KEYWORDS}
86
    return template('machines_icon', context)
87

    
88
def machines_list(request):
89
    context = {'default_keywords': settings.DEFAULT_KEYWORDS}
90
    return template('machines_list', context)
91

    
92
def machines_single(request):
93
    context = {'default_keywords': settings.DEFAULT_KEYWORDS}
94
    return template('machines_single', context)
95

    
96
def machines_console(request):
97
    host, port, password = ('','','')
98
    host = request.GET.get('host','')
99
    port = request.GET.get('port','')
100
    password = request.GET.get('password','')
101
    machine = request.GET.get('machine','')
102
    host_ip = request.GET.get('host_ip','')
103
    host_ip_v6 = request.GET.get('host_ip_v6','')
104
    context = {'host': host, 'port': port, 'password': password, 'machine': machine, 'host_ip': host_ip, 'host_ip_v6': host_ip_v6}
105
    return template('machines_console', context)
106

    
107
def js_tests(request):
108
    return template('tests', {})
109

    
110
CONNECT_LINUX_LINUX_MESSAGE = _("""A direct connection to this machine can be established using the <a target="_blank"
111
href="http://en.wikipedia.org/wiki/Secure_Shell">SSH Protocol</a>.
112
To do so open a terminal and type the following at the prompt to connect to your machine:""")
113
CONNECT_LINUX_WINDOWS_MESSAGE = _("""A direct connection to this machine can be
114
established using <a target="_blank" href="http://en.wikipedia.org/wiki/Remote_Desktop_Services">Remote Desktop Service</a>.
115
To do so, open the following file with an appropriate remote desktop client.""")
116
CONNECT_LINUX_WINDOWS_SUBMESSAGE = _("""If you don't have one already
117
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>.""")
118
CONNECT_WINDOWS_LINUX_MESSAGE = _("""A direct connection to this machine can be established using the <a target="_blank"
119
href="http://en.wikipedia.org/wiki/Secure_Shell">SSH Protocol</a>.
120
Open an ssh client such as PuTTY and type the following:""")
121
CONNECT_WINDOWS_LINUX_SUBMESSAGE = _("""If you do not have an ssh client already installed,
122
<a target="_blank" href="http://the.earth.li/~sgtatham/putty/latest/x86/putty.exe">Download PuTTY</a>""")
123

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

    
128
# info/subinfo for all os combinations
129
#
130
# [0] info gets displayed on top of the message box
131
# [1] subinfo gets displayed on the bottom as extra info
132
# provided to the user when needed
133
CONNECT_PROMPT_MESSAGES = {
134
    'linux': {
135
            'linux': [CONNECT_LINUX_LINUX_MESSAGE, ""],
136
            'windows': [CONNECT_LINUX_WINDOWS_MESSAGE, CONNECT_LINUX_WINDOWS_SUBMESSAGE]
137
        },
138
    'windows': {
139
            'linux': [CONNECT_WINDOWS_LINUX_MESSAGE, CONNECT_WINDOWS_LINUX_SUBMESSAGE],
140
            'windows': [CONNECT_WINDOWS_WINDOWS_MESSAGE, CONNECT_WINDOWS_WINDOWS_SUBMESSAGE]
141
        }
142
    }
143

    
144
# retrieve domain prefix from settings
145
DOMAIN_PREFIX = getattr(settings, 'MACHINE_DOMAIN_PREFIX', getattr(settings, 'BACKEND_PREFIX_ID', ""))
146

    
147
# domain template string
148
DOMAIN_TPL = "%s%%s" % DOMAIN_PREFIX
149

    
150
def machines_connect(request):
151
    ip_address = request.GET.get('ip_address','')
152
    operating_system = metadata_os = request.GET.get('os','')
153
    server_id = request.GET.get('srv', 0)
154
    host_os = request.GET.get('host_os','Linux').lower()
155
    username = request.GET.get('username', None)
156
    domain = request.GET.get("domain", DOMAIN_TPL % int(server_id))
157

    
158
    # guess host os
159
    if host_os != "windows":
160
        host_os = 'linux'
161

    
162
    # guess username
163
    if not username:
164
        username = "root"
165

    
166
        if metadata_os.lower() in ['ubuntu', 'kubuntu', 'fedora']:
167
            username = "user"
168

    
169
        if metadata_os.lower() == "windows":
170
            username = "Administrator"
171

    
172
    # operating system provides ssh access
173
    ssh = False
174
    if operating_system != "windows":
175
        operating_system = "linux"
176
        ssh = True
177

    
178
    # rdp param is set, the user requested rdp file
179
    # check if we are on windows
180
    if operating_system == 'windows' and request.GET.get("rdp", False):
181

    
182
        # UI sent domain info (from vm metadata) use this
183
        # otherwise use our default snf-<vm_id> domain
184
        rdp_context = {
185
                'username': username,
186
                'domain': domain,
187
                'ip_address': ip_address
188
        }
189

    
190
        rdp_file_data = render_to_string("synnefo-windows.rdp", rdp_context)
191
        response = HttpResponse(rdp_file_data, mimetype='application/x-rdp')
192

    
193
        # proper filename, use server id and ip address
194
        filename = "%d-%s.rdp" % (int(server_id), ip_address)
195
        response['Content-Disposition'] = 'attachment; filename=%s' % filename
196
    else:
197
        link_title = _("Remote desktop to %s") % ip_address
198
        link_url = "%s?ip_address=%s&os=%s&rdp=1&srv=%d&username=%s&domain=%s" % (
199
                reverse("machines-connect"), ip_address, operating_system,int(server_id), username, domain)
200

    
201
        if (operating_system != "windows"):
202
            link_title = "ssh %s@%s" % (username, ip_address)
203
            link_url = None
204

    
205
            if host_os == "windows":
206
                link_title = "%s@%s" % (username, ip_address)
207

    
208
        # try to find a specific message
209
        try:
210
            connect_message = CONNECT_PROMPT_MESSAGES[host_os][operating_system][0]
211
            subinfo = CONNECT_PROMPT_MESSAGES[host_os][operating_system][1]
212
        except KeyError:
213
            connect_message = _("You are trying to connect from a %s machine to a %s machine") % (host_os, operating_system)
214
            subinfo = ""
215

    
216
        response_object = {
217
                'ip': ip_address,
218
                'os': operating_system,
219
                'ssh': ssh,
220
                'info': unicode(connect_message),
221
                'subinfo': unicode(subinfo),
222
                'link': {'title': unicode(link_title), 'url': link_url}
223
            }
224
        response = HttpResponse(json.dumps(response_object), mimetype='application/json')  #no windows, no rdp
225

    
226
    return response
227

    
228
FEEDBACK_CONTACTS = getattr(settings, "FEEDBACK_CONTACTS", [])
229
FEEDBACK_EMAIL_FROM = settings.FEEDBACK_EMAIL_FROM
230

    
231
def feedback_submit(request):
232
    if not request.method == "POST":
233
        raise Http404
234

    
235
    message = request.POST.get("feedback-msg")
236
    data = request.POST.get("feedback-data")
237

    
238
    # default to True (calls from error pages)
239
    allow_data_send = request.POST.get("feedback-submit-data", True)
240

    
241
    mail_subject = unicode(_("Feedback from synnefo application"))
242

    
243
    mail_context = {'message': message, 'data': data, 'allow_data_send': allow_data_send, 'request': request}
244
    mail_content = render_to_string("feedback_mail.txt", mail_context)
245

    
246
    send_mail(mail_subject, mail_content, FEEDBACK_EMAIL_FROM,
247
            dict(FEEDBACK_CONTACTS).values(), fail_silently=False)
248

    
249
    return HttpResponse('{"status":"send"}');
250

    
251
def images(request):
252
    context = {}
253
    return template('images', context)
254

    
255
def disks(request):
256
    context = {}
257
    return template('disks', context)
258

    
259
def networks(request):
260
    context = {}
261
    return template('networks', context)
262

    
263
def files(request):
264
    context = {}
265
    return template('files', context)
266

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

    
271
def apps(request):
272
    context = {}
273
    return template('apps', context)