Statistics
| Branch: | Tag: | Revision:

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

History | View | Annotate | Download (14.4 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

    
49
from synnefo.util.version import get_component_version
50

    
51
SYNNEFO_JS_LIB_VERSION = get_component_version('app')
52

    
53
# api configuration
54
COMPUTE_API_URL = getattr(settings, 'COMPUTE_API_URL', '/api/v1.1')
55

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

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

    
77
SUPPORT_SSH_OS_LIST = getattr(settings, "UI_SUPPORT_SSH_OS_LIST",)
78
OS_CREATED_USERS = getattr(settings, "UI_OS_DEFAULT_USER_MAP")
79
LOGOUT_URL = getattr(settings, "UI_LOGOUT_URL", '/im/authenticate')
80
LOGIN_URL = getattr(settings, "UI_LOGIN_URL", '/im/login')
81
AUTH_COOKIE_NAME = getattr(settings, "UI_AUTH_COOKIE_NAME", 'synnefo_user')
82

    
83
# UI behaviour settings
84
DELAY_ON_BLUR = getattr(settings, "UI_DELAY_ON_BLUR", True)
85
UPDATE_HIDDEN_VIEWS = getattr(settings, "UI_UPDATE_HIDDEN_VIEWS", False)
86
HANDLE_WINDOW_EXCEPTIONS = getattr(settings, "UI_HANDLE_WINDOW_EXCEPTIONS", True)
87
SKIP_TIMEOUTS = getattr(settings, "UI_SKIP_TIMEOUTS", 1)
88

    
89
# Additional settings
90
VM_NAME_TEMPLATE = getattr(settings, "VM_CREATE_NAME_TPL", "My {0} server")
91
MAX_SSH_KEYS_PER_USER = getattr(settings, "USERDATA_MAX_SSH_KEYS_PER_USER")
92
FLAVORS_DISK_TEMPLATES_INFO = getattr(settings, "UI_FLAVORS_DISK_TEMPLATES_INFO", {})
93
SYSTEM_IMAGES_OWNERS = getattr(settings, "UI_SYSTEM_IMAGES_OWNERS", {})
94

    
95
# MEDIA PATHS
96
UI_MEDIA_URL = getattr(settings, "UI_MEDIA_URL",
97
                    "%ssnf-%s/" % (settings.MEDIA_URL, SYNNEFO_JS_LIB_VERSION))
98
UI_SYNNEFO_IMAGES_URL = getattr(settings,
99
                    "UI_SYNNEFO_IMAGES_URL", UI_MEDIA_URL + "images/")
100
UI_SYNNEFO_CSS_URL = getattr(settings,
101
                    "UI_SYNNEFO_CSS_URL", UI_MEDIA_URL + "css/")
102
UI_SYNNEFO_JS_URL = getattr(settings,
103
                    "UI_SYNNEFO_JS_URL", UI_MEDIA_URL + "js/")
104
UI_SYNNEFO_JS_LIB_URL = getattr(settings,
105
                    "UI_SYNNEFO_JS_LIB_URL", UI_SYNNEFO_JS_URL + "lib/")
106
UI_SYNNEFO_JS_WEB_URL = getattr(settings,
107
                    "UI_SYNNEFO_JS_WEB_URL",
108
                    UI_SYNNEFO_JS_URL + "ui/web/")
109

    
110
# extensions
111
ENABLE_GLANCE = getattr(settings, 'UI_ENABLE_GLANCE', True)
112
GLANCE_API_URL = getattr(settings, 'UI_GLANCE_API_URL', '/glance')
113
FEEDBACK_CONTACTS = getattr(settings, "FEEDBACK_CONTACTS", [])
114
FEEDBACK_EMAIL_FROM = settings.FEEDBACK_EMAIL_FROM
115

    
116
def template(name, context):
117
    template_path = os.path.join(os.path.dirname(__file__), "templates/")
118
    current_template = template_path + name + '.html'
119
    t = loader.get_template(current_template)
120
    media_context = {
121
       'UI_MEDIA_URL': UI_MEDIA_URL,
122
       'SYNNEFO_JS_URL': UI_SYNNEFO_JS_URL,
123
       'SYNNEFO_JS_LIB_URL': UI_SYNNEFO_JS_LIB_URL,
124
       'SYNNEFO_JS_WEB_URL': UI_SYNNEFO_JS_WEB_URL,
125
       'SYNNEFO_IMAGES_URL': UI_SYNNEFO_IMAGES_URL,
126
       'SYNNEFO_CSS_URL': UI_SYNNEFO_CSS_URL,
127
       'SYNNEFO_JS_LIB_VERSION': SYNNEFO_JS_LIB_VERSION,
128
       'DEBUG': settings.DEBUG
129
    }
130
    context.update(media_context)
131
    return HttpResponse(t.render(Context(context)))
132

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

    
169
def machines_console(request):
170
    host, port, password = ('','','')
171
    host = request.GET.get('host','')
172
    port = request.GET.get('port','')
173
    password = request.GET.get('password','')
174
    machine = request.GET.get('machine','')
175
    host_ip = request.GET.get('host_ip','')
176
    host_ip_v6 = request.GET.get('host_ip_v6','')
177
    context = {'host': host, 'port': port, 'password': password,
178
               'machine': machine, 'host_ip': host_ip, 'host_ip_v6': host_ip_v6}
179
    return template('machines_console', context)
180

    
181
def js_tests(request):
182
    return template('tests', {})
183

    
184
CONNECT_LINUX_LINUX_MESSAGE = _("""A direct connection to this machine can be established using the <a target="_blank"
185
href="http://en.wikipedia.org/wiki/Secure_Shell">SSH Protocol</a>.
186
To do so open a terminal and type the following at the prompt to connect to your machine:""")
187
CONNECT_LINUX_WINDOWS_MESSAGE = _("""A direct connection to this machine can be
188
established using <a target="_blank" href="http://en.wikipedia.org/wiki/Remote_Desktop_Services">Remote Desktop Service</a>.
189
To do so, open the following file with an appropriate remote desktop client.""")
190
CONNECT_LINUX_WINDOWS_SUBMESSAGE = _("""If you don't have one already
191
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>.""")
192
CONNECT_WINDOWS_LINUX_MESSAGE = _("""A direct connection to this machine can be established using the <a target="_blank"
193
href="http://en.wikipedia.org/wiki/Secure_Shell">SSH Protocol</a>.
194
Open an ssh client such as PuTTY and type the following:""")
195
CONNECT_WINDOWS_LINUX_SUBMESSAGE = _("""If you do not have an ssh client already installed,
196
<a target="_blank" href="http://the.earth.li/~sgtatham/putty/latest/x86/putty.exe">Download PuTTY</a>""")
197

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

    
202
# info/subinfo for all os combinations
203
#
204
# [0] info gets displayed on top of the message box
205
# [1] subinfo gets displayed on the bottom as extra info
206
# provided to the user when needed
207
CONNECT_PROMPT_MESSAGES = {
208
    'linux': {
209
            'linux': [CONNECT_LINUX_LINUX_MESSAGE, ""],
210
            'windows': [CONNECT_LINUX_WINDOWS_MESSAGE,
211
                        CONNECT_LINUX_WINDOWS_SUBMESSAGE]
212
        },
213
    'windows': {
214
            'linux': [CONNECT_WINDOWS_LINUX_MESSAGE,
215
                      CONNECT_WINDOWS_LINUX_SUBMESSAGE],
216
            'windows': [CONNECT_WINDOWS_WINDOWS_MESSAGE,
217
                        CONNECT_WINDOWS_WINDOWS_SUBMESSAGE]
218
        }
219
    }
220

    
221
# retrieve domain prefix from settings
222
DOMAIN_PREFIX = getattr(settings, 'MACHINE_DOMAIN_PREFIX', getattr(settings,
223
                        'BACKEND_PREFIX_ID', ""))
224

    
225
# domain template string
226
DOMAIN_TPL = "%s%%s" % DOMAIN_PREFIX
227

    
228
def machines_connect(request):
229
    ip_address = request.GET.get('ip_address','')
230
    operating_system = metadata_os = request.GET.get('os','')
231
    server_id = request.GET.get('srv', 0)
232
    host_os = request.GET.get('host_os','Linux').lower()
233
    username = request.GET.get('username', None)
234
    domain = request.GET.get("domain", DOMAIN_TPL % int(server_id))
235

    
236
    # guess host os
237
    if host_os != "windows":
238
        host_os = 'linux'
239

    
240
    # guess username
241
    if not username:
242
        username = "root"
243

    
244
        if metadata_os.lower() in ['ubuntu', 'kubuntu', 'fedora']:
245
            username = "user"
246

    
247
        if metadata_os.lower() == "windows":
248
            username = "Administrator"
249

    
250
    # operating system provides ssh access
251
    ssh = False
252
    if operating_system != "windows":
253
        operating_system = "linux"
254
        ssh = True
255

    
256
    # rdp param is set, the user requested rdp file
257
    # check if we are on windows
258
    if operating_system == 'windows' and request.GET.get("rdp", False):
259

    
260
        # UI sent domain info (from vm metadata) use this
261
        # otherwise use our default snf-<vm_id> domain
262
        rdp_context = {
263
                'username': username,
264
                'domain': domain,
265
                'ip_address': ip_address
266
        }
267

    
268
        rdp_file_data = render_to_string("synnefo-windows.rdp", rdp_context)
269
        response = HttpResponse(rdp_file_data, mimetype='application/x-rdp')
270

    
271
        # proper filename, use server id and ip address
272
        filename = "%d-%s.rdp" % (int(server_id), ip_address)
273
        response['Content-Disposition'] = 'attachment; filename=%s' % filename
274
    else:
275
        link_title = _("Remote desktop to %s") % ip_address
276
        link_url = "%s?ip_address=%s&os=%s&rdp=1&srv=%d&username=%s&domain=%s" % (
277
                reverse("machines-connect"), ip_address, operating_system,int(server_id), username, domain)
278

    
279
        if (operating_system != "windows"):
280
            link_title = "ssh %s@%s" % (username, ip_address)
281
            link_url = None
282

    
283
            if host_os == "windows":
284
                link_title = "%s@%s" % (username, ip_address)
285

    
286
        # try to find a specific message
287
        try:
288
            connect_message = CONNECT_PROMPT_MESSAGES[host_os][operating_system][0]
289
            subinfo = CONNECT_PROMPT_MESSAGES[host_os][operating_system][1]
290
        except KeyError:
291
            connect_message = _("You are trying to connect from a %s "
292
                                "machine to a %s machine") % (host_os, operating_system)
293
            subinfo = ""
294

    
295
        response_object = {
296
                'ip': ip_address,
297
                'os': operating_system,
298
                'ssh': ssh,
299
                'info': unicode(connect_message),
300
                'subinfo': unicode(subinfo),
301
                'link': {'title': unicode(link_title), 'url': link_url}
302
            }
303
        response = HttpResponse(json.dumps(response_object),
304
                                mimetype='application/json')  #no windows, no rdp
305

    
306
    return response
307

    
308
def feedback_submit(request):
309
    if not request.method == "POST":
310
        raise Http404
311

    
312
    message = request.POST.get("feedback-msg")
313
    data = request.POST.get("feedback-data")
314

    
315
    # default to True (calls from error pages)
316
    allow_data_send = request.POST.get("feedback-submit-data", True)
317

    
318
    mail_subject = unicode(_("Feedback from synnefo application"))
319

    
320
    mail_context = {'message': message, 'data': data,
321
                    'allow_data_send': allow_data_send, 'request': request}
322
    mail_content = render_to_string("feedback_mail.txt", mail_context)
323

    
324
    send_mail(mail_subject, mail_content, FEEDBACK_EMAIL_FROM,
325
            dict(FEEDBACK_CONTACTS).values(), fail_silently=False)
326

    
327
    return HttpResponse('{"status":"send"}');
328