Statistics
| Branch: | Tag: | Revision:

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

History | View | Annotate | Download (20.4 kB)

1
# Copyright 2011, 2012, 2013 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 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 synnefo_branding.utils import render_to_string
44
from django.core.urlresolvers import reverse
45
from django.template import RequestContext
46

    
47
from synnefo.util.version import get_component_version
48

    
49
from synnefo.ui import settings as uisettings
50

    
51
SYNNEFO_JS_LIB_VERSION = get_component_version('app')
52

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

    
64
# predefined values settings
65
VM_IMAGE_COMMON_METADATA = \
66
    getattr(settings, "UI_VM_IMAGE_COMMON_METADATA", ["OS", "users"])
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
IMAGE_ICONS = settings.IMAGE_ICONS
75
IMAGE_DELETED_TITLE = \
76
    getattr(settings, 'UI_IMAGE_DELETED_TITLE', '(deleted)')
77
IMAGE_DELETED_SIZE_TITLE = \
78
    getattr(settings, 'UI_IMAGE_DELETED_SIZE_TITLE', '(none)')
79

    
80
SUPPORT_SSH_OS_LIST = getattr(settings, "UI_SUPPORT_SSH_OS_LIST",)
81
SUPPORT_SSH_OS_FAMILY_LIST = getattr(settings, "UI_SUPPORT_SSH_OS_FAMILY_LIST",
82
                                     ['linux', 'openbsd', 'freebsd', 'netbsd'])
83

    
84
OS_CREATED_USERS = getattr(settings, "UI_OS_DEFAULT_USER_MAP")
85
UNKNOWN_OS = getattr(settings, "UI_UNKNOWN_OS", "unknown")
86

    
87
AUTH_COOKIE_NAME = getattr(settings, "UI_AUTH_COOKIE_NAME", 'synnefo_user')
88

    
89
# never change window location. Helpful in development environments
90
AUTH_SKIP_REDIRECTS = getattr(settings, "UI_AUTH_SKIP_REDIRECTS", False)
91

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

    
99
# Additional settings
100
VM_NAME_TEMPLATE = getattr(settings, "VM_CREATE_NAME_TPL", "My {0} server")
101
NO_FQDN_MESSAGE = getattr(settings, "UI_NO_FQDN_MESSAGE", "No available FQDN")
102

    
103
MAX_SSH_KEYS_PER_USER = getattr(settings, "USERDATA_MAX_SSH_KEYS_PER_USER")
104
FLAVORS_DISK_TEMPLATES_INFO = \
105
    getattr(settings, "UI_FLAVORS_DISK_TEMPLATES_INFO", {})
106
SYSTEM_IMAGES_OWNERS = getattr(settings, "UI_SYSTEM_IMAGES_OWNERS", {})
107
CUSTOM_IMAGE_HELP_URL = getattr(settings, "UI_CUSTOM_IMAGE_HELP_URL", None)
108

    
109
# MEDIA PATHS
110
UI_MEDIA_URL = \
111
    getattr(settings, "UI_MEDIA_URL",
112
            "%sui/static/snf/" % (settings.MEDIA_URL,))
113
UI_SYNNEFO_IMAGES_URL = \
114
    getattr(settings,
115
            "UI_SYNNEFO_IMAGES_URL", UI_MEDIA_URL + "images/")
116
UI_SYNNEFO_CSS_URL = \
117
    getattr(settings,
118
            "UI_SYNNEFO_CSS_URL", UI_MEDIA_URL + "css/")
119
UI_SYNNEFO_JS_URL = \
120
    getattr(settings,
121
            "UI_SYNNEFO_JS_URL", UI_MEDIA_URL + "js/")
122
UI_SYNNEFO_JS_LIB_URL = \
123
    getattr(settings,
124
            "UI_SYNNEFO_JS_LIB_URL", UI_SYNNEFO_JS_URL + "lib/")
125
UI_SYNNEFO_JS_WEB_URL = \
126
    getattr(settings, "UI_SYNNEFO_JS_WEB_URL", UI_SYNNEFO_JS_URL + "ui/web/")
127
UI_SYNNEFO_FONTS_BASE_URL = \
128
    getattr(settings,
129
            "UI_FONTS_BASE_URL", "//fonts.googleapis.com/")
130

    
131
# extensions
132
ENABLE_GLANCE = getattr(settings, 'UI_ENABLE_GLANCE', True)
133

    
134
DIAGNOSTICS_UPDATE_INTERVAL = \
135
    getattr(settings, 'UI_DIAGNOSTICS_UPDATE_INTERVAL', 2000)
136

    
137
# network settings
138
DEFAULT_NETWORK_TYPES = {'MAC_FILTERED': 'mac-filtering',
139
                         'PHYSICAL_VLAN': 'physical-vlan'}
140
NETWORK_TYPES = \
141
    getattr(settings,
142
            'UI_NETWORK_AVAILABLE_NETWORK_TYPES', DEFAULT_NETWORK_TYPES)
143
DEFAULT_NETWORK_SUBNETS = ['10.0.0.0/24', '192.168.1.1/24']
144
NETWORK_SUBNETS = \
145
    getattr(settings,
146
            'UI_NETWORK_AVAILABLE_SUBNETS', DEFAULT_NETWORK_SUBNETS)
147
NETWORK_DUPLICATE_NICS = \
148
    getattr(settings,
149
            'UI_NETWORK_ALLOW_DUPLICATE_VM_NICS', False)
150
NETWORK_STRICT_DESTROY = \
151
    getattr(settings,
152
            'UI_NETWORK_STRICT_DESTROY', False)
153
NETWORK_ALLOW_MULTIPLE_DESTROY = \
154
    getattr(settings,
155
            'UI_NETWORK_ALLOW_MULTIPLE_DESTROY', False)
156
AUTOMATIC_NETWORK_RANGE_FORMAT = getattr(settings,
157
                                         'UI_AUTOMATIC_NETWORK_RANGE_FORMAT',
158
                                         "192.168.%d.0/24").replace("%d",
159
                                                                    "{0}")
160
GROUP_PUBLIC_NETWORKS = getattr(settings, 'UI_GROUP_PUBLIC_NETWORKS', True)
161
GROUPED_PUBLIC_NETWORK_NAME = \
162
    getattr(settings, 'UI_GROUPED_PUBLIC_NETWORK_NAME', 'Internet')
163

    
164

    
165
DEFAULT_FORCED_SERVER_NETWORKS = \
166
    getattr(settings, "CYCLADES_FORCED_SERVER_NETWORKS", [])
167
FORCED_SERVER_NETWORKS = getattr(settings, "UI_FORCED_SERVER_NETWORKS",
168
                                 DEFAULT_FORCED_SERVER_NETWORKS)
169

    
170
DEFAULT_HOTPLUG_ENABLED = getattr(settings, "CYCLADES_GANETI_USE_HOTPLUG",
171
                                  True)
172
HOTPLUG_ENABLED = getattr(settings, "UI_HOTPLUG_ENABLED",
173
                          DEFAULT_HOTPLUG_ENABLED)
174

    
175
def template(name, request, context):
176
    template_path = os.path.join(os.path.dirname(__file__), "templates/")
177
    current_template = template_path + name + '.html'
178
    t = loader.get_template(current_template)
179
    media_context = {
180
        'UI_MEDIA_URL': UI_MEDIA_URL,
181
        'SYNNEFO_JS_URL': UI_SYNNEFO_JS_URL,
182
        'SYNNEFO_JS_LIB_URL': UI_SYNNEFO_JS_LIB_URL,
183
        'SYNNEFO_FONTS_BASE_URL': UI_SYNNEFO_FONTS_BASE_URL,
184
        'SYNNEFO_JS_WEB_URL': UI_SYNNEFO_JS_WEB_URL,
185
        'SYNNEFO_IMAGES_URL': UI_SYNNEFO_IMAGES_URL,
186
        'SYNNEFO_CSS_URL': UI_SYNNEFO_CSS_URL,
187
        'SYNNEFO_JS_LIB_VERSION': SYNNEFO_JS_LIB_VERSION,
188
        'DEBUG': settings.DEBUG
189
    }
190
    context.update(media_context)
191
    return HttpResponse(t.render(RequestContext(request, context)))
192

    
193

    
194
def home(request):
195
    context = {
196
        'timeout': TIMEOUT,
197
        'project': '+nefo',
198
        'request': request,
199
        'current_lang': get_language() or 'en',
200
        'compute_api_url': json.dumps(uisettings.COMPUTE_URL),
201
        'network_api_url': json.dumps(uisettings.NETWORK_URL),
202
        'user_catalog_url': json.dumps(uisettings.USER_CATALOG_URL),
203
        'feedback_post_url': json.dumps(uisettings.FEEDBACK_URL),
204
        'accounts_api_url': json.dumps(uisettings.ACCOUNT_URL),
205
        'logout_redirect': json.dumps(uisettings.LOGOUT_REDIRECT),
206
        'login_redirect': json.dumps(uisettings.LOGIN_URL),
207
        'glance_api_url': json.dumps(uisettings.GLANCE_URL),
208
        'translate_uuids': json.dumps(True),
209
        # update interval settings
210
        'update_interval': UPDATE_INTERVAL,
211
        'update_interval_increase': UPDATE_INTERVAL_INCREASE,
212
        'update_interval_increase_after_calls':
213
        UPDATE_INTERVAL_INCREASE_AFTER_CALLS_COUNT,
214
        'update_interval_fast': UPDATE_INTERVAL_FAST,
215
        'update_interval_max': UPDATE_INTERVAL_MAX,
216
        'changes_since_alignment': CHANGES_SINCE_ALIGNMENT,
217
        'image_icons': IMAGE_ICONS,
218
        'auth_cookie_name': AUTH_COOKIE_NAME,
219
        'auth_skip_redirects': json.dumps(AUTH_SKIP_REDIRECTS),
220
        'suggested_flavors': json.dumps(SUGGESTED_FLAVORS),
221
        'suggested_roles': json.dumps(SUGGESTED_ROLES),
222
        'vm_image_common_metadata': json.dumps(VM_IMAGE_COMMON_METADATA),
223
        'synnefo_version': SYNNEFO_JS_LIB_VERSION,
224
        'delay_on_blur': json.dumps(DELAY_ON_BLUR),
225
        'update_hidden_views': json.dumps(UPDATE_HIDDEN_VIEWS),
226
        'handle_window_exceptions': json.dumps(HANDLE_WINDOW_EXCEPTIONS),
227
        'skip_timeouts': json.dumps(SKIP_TIMEOUTS),
228
        'vm_name_template': json.dumps(VM_NAME_TEMPLATE),
229
        'flavors_disk_templates_info': json.dumps(FLAVORS_DISK_TEMPLATES_INFO),
230
        'support_ssh_os_list': json.dumps(SUPPORT_SSH_OS_LIST),
231
        'support_ssh_os_family_list': json.dumps(SUPPORT_SSH_OS_FAMILY_LIST),
232
        'unknown_os': json.dumps(UNKNOWN_OS),
233
        'os_created_users': json.dumps(OS_CREATED_USERS),
234
        'userdata_keys_limit': json.dumps(MAX_SSH_KEYS_PER_USER),
235
        'use_glance': json.dumps(ENABLE_GLANCE),
236
        'system_images_owners': json.dumps(SYSTEM_IMAGES_OWNERS),
237
        'custom_image_help_url': CUSTOM_IMAGE_HELP_URL,
238
        'image_deleted_title': json.dumps(IMAGE_DELETED_TITLE),
239
        'image_deleted_size_title': json.dumps(IMAGE_DELETED_SIZE_TITLE),
240
        'network_suggested_subnets': json.dumps(NETWORK_SUBNETS),
241
        'network_available_types': json.dumps(NETWORK_TYPES),
242
        'forced_server_networks': json.dumps(FORCED_SERVER_NETWORKS),
243
        'network_allow_duplicate_vm_nics': json.dumps(NETWORK_DUPLICATE_NICS),
244
        'network_strict_destroy': json.dumps(NETWORK_STRICT_DESTROY),
245
        'network_allow_multiple_destroy':
246
        json.dumps(NETWORK_ALLOW_MULTIPLE_DESTROY),
247
        'automatic_network_range_format':
248
        json.dumps(AUTOMATIC_NETWORK_RANGE_FORMAT),
249
        'grouped_public_network_name': json.dumps(GROUPED_PUBLIC_NETWORK_NAME),
250
        'group_public_networks': json.dumps(GROUP_PUBLIC_NETWORKS),
251
        'hotplug_enabled': json.dumps(HOTPLUG_ENABLED),
252
        'diagnostics_update_interval': json.dumps(DIAGNOSTICS_UPDATE_INTERVAL),
253
        'no_fqdn_message': json.dumps(NO_FQDN_MESSAGE)
254
    }
255
    return template('home', request, context)
256

    
257

    
258
def machines_console(request):
259
    host, port, password = ('', '', '')
260
    host = request.GET.get('host', '')
261
    port = request.GET.get('port', '')
262
    password = request.GET.get('password', '')
263
    machine = request.GET.get('machine', '')
264
    host_ip = request.GET.get('host_ip', '')
265
    host_ip_v6 = request.GET.get('host_ip_v6', '')
266
    context = {'host': host, 'port': port, 'password': password,
267
               'machine': machine, 'host_ip': host_ip,
268
               'host_ip_v6': host_ip_v6}
269
    return template('machines_console', request, context)
270

    
271

    
272
def js_tests(request):
273
    return template('tests', request, {})
274

    
275

    
276
CONNECT_LINUX_LINUX_MESSAGE = \
277
    _("""A direct connection to this machine can be established using the
278
<a target="_blank" href="http://en.wikipedia.org/wiki/Secure_Shell">
279
SSH Protocol</a>.
280
To do so open a terminal and type the following at the prompt to connect
281
to your machine:""")
282
CONNECT_LINUX_WINDOWS_MESSAGE = \
283
    _("""A direct connection to this machine can be established using
284
<a target="_blank"
285
href="http://en.wikipedia.org/wiki/Remote_Desktop_Services">
286
Remote Desktop Service</a>.
287
To do so, open the following file with an appropriate \
288
remote desktop client.""")
289
CONNECT_LINUX_WINDOWS_SUBMESSAGE = \
290
    _("""If you don't have a Remote Desktop client already installed,
291
we suggest the use of <a target="_blank"
292
href=
293
"http://sourceforge.net/projects/tsclient/files/latest/download?source=files">
294
tsclient</a>.<br /><span class="important">IMPORTANT: It may take up to 15
295
minutes for your Windows VM to become available
296
after its creation.</span>""")
297
CONNECT_WINDOWS_LINUX_MESSAGE = \
298
    _("""A direct connection to this machine can be established using the
299
<a target="_blank"
300
href="http://en.wikipedia.org/wiki/Secure_Shell">SSH Protocol</a>.
301
Open an ssh client such as PuTTY and type the following:""")
302
CONNECT_WINDOWS_LINUX_SUBMESSAGE = \
303
    _("""If you do not have an ssh client already installed,
304
<a target="_blank"
305
href="http://the.earth.li/~sgtatham/putty/latest/x86/putty.exe">
306
Download PuTTY</a>""")
307

    
308
CONNECT_WINDOWS_WINDOWS_MESSAGE = \
309
    _("""A direct connection to this machine can be
310
established using Remote Desktop. Click on the following link, and if asked
311
open it using "Remote Desktop Connection".
312
<br /><span class="important">
313
IMPORTANT: It may take up to 15 minutes for your Windows VM to become available
314
after its creation.</span>""")
315
CONNECT_WINDOWS_WINDOWS_SUBMESSAGE = \
316
    _("""Save this file to disk for future use.""")
317

    
318
# info/subinfo for all os combinations
319
#
320
# [0] info gets displayed on top of the message box
321
# [1] subinfo gets displayed on the bottom as extra info
322
# provided to the user when needed
323
CONNECT_PROMPT_MESSAGES = {
324
    'linux': {
325
        'linux': [CONNECT_LINUX_LINUX_MESSAGE, ""],
326
        'windows': [CONNECT_LINUX_WINDOWS_MESSAGE,
327
                    CONNECT_LINUX_WINDOWS_SUBMESSAGE],
328
        'ssh_message': "ssh %(user)s@%(hostname)s",
329
        'ssh_message_port': "ssh -p %(port)s %(user)s@%(hostname)s"
330

    
331
    },
332
    'windows': {
333
        'linux': [CONNECT_WINDOWS_LINUX_MESSAGE,
334
                  CONNECT_WINDOWS_LINUX_SUBMESSAGE],
335
        'windows': [CONNECT_WINDOWS_WINDOWS_MESSAGE,
336
                    CONNECT_WINDOWS_WINDOWS_SUBMESSAGE],
337
        'ssh_message': "%(user)s@%(hostname)s",
338
        'ssh_message_port': "%(user)s@%(hostname)s (port: %(port)s)"
339
    },
340
}
341

    
342
APPEND_CONNECT_PROMPT_MESSAGES = \
343
    getattr(settings, 'UI_CONNECT_PROMPT_MESSAGES', {})
344
for k, v in APPEND_CONNECT_PROMPT_MESSAGES.iteritems():
345
    CONNECT_PROMPT_MESSAGES[k].update(v)
346

    
347
# retrieve domain prefix from settings
348
DOMAIN_PREFIX = getattr(settings, 'MACHINE_DOMAIN_PREFIX', getattr(settings,
349
                        'BACKEND_PREFIX_ID', ""))
350

    
351
# domain template string
352
DOMAIN_TPL = "%s%%s" % DOMAIN_PREFIX
353

    
354

    
355
def machines_connect(request):
356
    ip_address = request.GET.get('ip_address', '')
357
    hostname = request.GET.get('hostname', '')
358
    operating_system = metadata_os = request.GET.get('os', '')
359
    server_id = request.GET.get('srv', 0)
360
    host_os = request.GET.get('host_os', 'Linux').lower()
361
    username = request.GET.get('username', None)
362
    domain = request.GET.get("domain", DOMAIN_TPL % int(server_id))
363
    ports = json.loads(request.GET.get('ports', '{}'))
364

    
365
    # guess host os
366
    if host_os != "windows":
367
        host_os = 'linux'
368

    
369
    # guess username
370
    if not username:
371
        username = "root"
372

    
373
        if metadata_os.lower() in ['ubuntu', 'kubuntu', 'fedora']:
374
            username = "user"
375

    
376
        if metadata_os.lower() == "windows":
377
            username = "Administrator"
378

    
379
    ssh_forward = ports.get("22", None)
380
    rdp_forward = ports.get("3389", None)
381

    
382
    # operating system provides ssh access
383
    ssh = False
384
    if operating_system != "windows":
385
        operating_system = "linux"
386
        ssh = True
387

    
388
    # rdp param is set, the user requested rdp file
389
    # check if we are on windows
390
    if operating_system == 'windows' and request.GET.get("rdp", False):
391
        port = '3389'
392
        if rdp_forward:
393
            hostname = rdp_forward.get('host', hostname)
394
            ip_address = rdp_forward.get('host', ip_address)
395
            port = str(rdp_forward.get('port', '3389'))
396

    
397
        extra_rdp_content = ''
398
        # UI sent domain info (from vm metadata) use this
399
        # otherwise use our default snf-<vm_id> domain
400
        EXTRA_RDP_CONTENT = getattr(settings, 'UI_EXTRA_RDP_CONTENT', '')
401
        if callable(EXTRA_RDP_CONTENT):
402
            extra_rdp_content = EXTRA_RDP_CONTENT(server_id, ip_address,
403
                                                  hostname, username)
404
        else:
405
            if EXTRA_RDP_CONTENT:
406
                extra_rdp_content = EXTRA_RDP_CONTENT % \
407
                    {
408
                        'server_id': server_id,
409
                        'ip_address': ip_address,
410
                        'hostname': hostname,
411
                        'user': username,
412
                        'port': port
413
                    }
414

    
415
        rdp_context = {
416
            'username': username,
417
            'domain': domain,
418
            'ip_address': ip_address,
419
            'hostname': hostname,
420
            'port': request.GET.get('port', port),
421
            'extra_content': extra_rdp_content
422
        }
423

    
424
        rdp_file_data = render_to_string("synnefo-windows.rdp", rdp_context)
425
        response = HttpResponse(rdp_file_data, mimetype='application/x-rdp')
426

    
427
        # proper filename, use server id and ip address
428
        filename = "%d-%s.rdp" % (int(server_id), hostname)
429
        response['Content-Disposition'] = 'attachment; filename=%s' % filename
430
    else:
431
        message_key = "ssh_message"
432
        ip_address = ip_address
433
        hostname = hostname
434
        port = ''
435
        if ssh_forward:
436
            message_key = 'ssh_message_port'
437
            hostname = ssh_forward.get('host', hostname)
438
            ip_address = ssh_forward.get('host', ip_address)
439
            port = str(ssh_forward.get('port', '22'))
440

    
441
        ssh_message = CONNECT_PROMPT_MESSAGES['linux'].get(message_key)
442
        if host_os == 'windows':
443
            ssh_message = CONNECT_PROMPT_MESSAGES['windows'].get(message_key)
444
        if callable(ssh_message):
445
            link_title = ssh_message(server_id, ip_address, hostname, username)
446
        else:
447
            link_title = ssh_message % {
448
                'server_id': server_id,
449
                'ip_address': ip_address,
450
                'hostname': hostname,
451
                'user': username,
452
                'port': port
453
            }
454
        if (operating_system != "windows"):
455
            link_url = None
456

    
457
        else:
458
            link_title = _("Remote desktop to %s") % ip_address
459
            if rdp_forward:
460
                hostname = rdp_forward.get('host', hostname)
461
                ip_address = rdp_forward.get('host', ip_address)
462
                port = str(rdp_forward.get('port', '3389'))
463
                link_title = _("Remote desktop to %s (port %s)") % (ip_address,
464
                                                                    port)
465
            link_url = \
466
                "%s?ip_address=%s&os=%s&rdp=1&srv=%d&username=%s&domain=%s" \
467
                "&hostname=%s&port=%s" % (
468
                    reverse("ui_machines_connect"), ip_address,
469
                    operating_system, int(server_id), username,
470
                    domain, hostname, port)
471

    
472
        # try to find a specific message
473
        try:
474
            connect_message = \
475
                CONNECT_PROMPT_MESSAGES[host_os][operating_system][0]
476
            subinfo = CONNECT_PROMPT_MESSAGES[host_os][operating_system][1]
477
        except KeyError:
478
            connect_message = \
479
                _("You are trying to connect from a %s "
480
                  "machine to a %s machine") % (host_os, operating_system)
481
            subinfo = ""
482

    
483
        response_object = {
484
            'ip': ip_address,
485
            'os': operating_system,
486
            'ssh': ssh,
487
            'info': unicode(connect_message),
488
            'subinfo': unicode(subinfo),
489
            'link': {'title': unicode(link_title), 'url': link_url}
490
        }
491
        response = \
492
            HttpResponse(json.dumps(response_object),
493
                         mimetype='application/json')  # no windows, no rdp
494

    
495
    return response