~ubuntu-branches/ubuntu/precise/horizon/precise-updates

« back to all changes in this revision

Viewing changes to horizon/horizon/dashboards/nova/instances/views.py

  • Committer: Package Import Robot
  • Author(s): Chuck Short
  • Date: 2011-12-16 16:34:56 UTC
  • mfrom: (1.1.2)
  • Revision ID: package-import@ubuntu.com-20111216163456-ts9ldy8skhsg0scb
Tags: 2012.1~e2-0ubuntu1
* New upstream release (LP: #904039)
* debian/control: Update build-depends.
* debian/watch: Fix to fetch from Launchpad ad well.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# vim: tabstop=4 shiftwidth=4 softtabstop=4
2
 
 
3
 
# Copyright 2011 United States Government as represented by the
4
 
# Administrator of the National Aeronautics and Space Administration.
5
 
# All Rights Reserved.
6
 
#
7
 
# Copyright 2011 Nebula, Inc.
8
 
#
9
 
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
10
 
#    not use this file except in compliance with the License. You may obtain
11
 
#    a copy of the License at
12
 
#
13
 
#         http://www.apache.org/licenses/LICENSE-2.0
14
 
#
15
 
#    Unless required by applicable law or agreed to in writing, software
16
 
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
17
 
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
18
 
#    License for the specific language governing permissions and limitations
19
 
#    under the License.
20
 
 
21
 
"""
22
 
Views for managing Nova instances.
23
 
"""
24
 
import datetime
25
 
import logging
26
 
 
27
 
from django import http
28
 
from django import shortcuts
29
 
from django.contrib import messages
30
 
from django.contrib.auth.decorators import login_required
31
 
from django.utils.translation import ugettext as _
32
 
import openstackx.api.exceptions as api_exceptions
33
 
 
34
 
from horizon import api
35
 
from horizon import forms
36
 
from horizon import test
37
 
from horizon.dashboards.nova.instances.forms import (TerminateInstance,
38
 
        RebootInstance, UpdateInstance)
39
 
 
40
 
 
41
 
LOG = logging.getLogger(__name__)
42
 
 
43
 
 
44
 
@login_required
45
 
def index(request):
46
 
    tenant_id = request.user.tenant_id
47
 
    for f in (TerminateInstance, RebootInstance):
48
 
        form, handled = f.maybe_handle(request)
49
 
        if handled:
50
 
            return handled
51
 
    instances = []
52
 
    try:
53
 
        instances = api.server_list(request)
54
 
    except api_exceptions.ApiException as e:
55
 
        LOG.exception(_('Exception in instance index'))
56
 
        messages.error(request, _('Unable to get instance list: %s')
57
 
                       % e.message)
58
 
 
59
 
    # We don't have any way of showing errors for these, so don't bother
60
 
    # trying to reuse the forms from above
61
 
    terminate_form = TerminateInstance()
62
 
    reboot_form = RebootInstance()
63
 
 
64
 
    return shortcuts.render(request,
65
 
                            'nova/instances/index.html', {
66
 
                                'instances': instances,
67
 
                                'terminate_form': terminate_form,
68
 
                                'reboot_form': reboot_form})
69
 
 
70
 
 
71
 
@login_required
72
 
def refresh(request):
73
 
    tenant_id = request.user.tenant_id
74
 
    instances = []
75
 
    try:
76
 
        instances = api.server_list(request)
77
 
    except Exception as e:
78
 
        messages.error(request,
79
 
                       _('Unable to get instance list: %s') % e.message)
80
 
 
81
 
    # We don't have any way of showing errors for these, so don't bother
82
 
    # trying to reuse the forms from above
83
 
    terminate_form = TerminateInstance()
84
 
    reboot_form = RebootInstance()
85
 
 
86
 
    return shortcuts.render(request,
87
 
                            'nova/instances/_list.html', {
88
 
                                'instances': instances,
89
 
                                'terminate_form': terminate_form,
90
 
                                'reboot_form': reboot_form})
91
 
 
92
 
 
93
 
@login_required
94
 
def usage(request, tenant_id=None):
95
 
    tenant_id = tenant_id or request.user.tenant_id
96
 
    today = test.today()
97
 
    date_start = datetime.date(today.year, today.month, 1)
98
 
    datetime_start = datetime.datetime.combine(date_start, test.time())
99
 
    datetime_end = test.utcnow()
100
 
 
101
 
    show_terminated = request.GET.get('show_terminated', False)
102
 
 
103
 
    usage = {}
104
 
    if not tenant_id:
105
 
        tenant_id = request.user.tenant_id
106
 
 
107
 
    try:
108
 
        usage = api.usage_get(request, tenant_id, datetime_start, datetime_end)
109
 
    except api_exceptions.ApiException, e:
110
 
        LOG.exception(_('ApiException in instance usage'))
111
 
 
112
 
        messages.error(request, _('Unable to get usage info: %s') % e.message)
113
 
 
114
 
    ram_unit = "MB"
115
 
    total_ram = 0
116
 
    if hasattr(usage, 'total_active_ram_size'):
117
 
        total_ram = usage.total_active_ram_size
118
 
        if total_ram > 999:
119
 
            ram_unit = "GB"
120
 
            total_ram /= float(1024)
121
 
 
122
 
    running_instances = []
123
 
    terminated_instances = []
124
 
    if hasattr(usage, 'instances'):
125
 
        now = datetime.datetime.now()
126
 
        for i in usage.instances:
127
 
            # this is just a way to phrase uptime in a way that is compatible
128
 
            # with the 'timesince' filter.  Use of local time intentional
129
 
            i['uptime_at'] = now - datetime.timedelta(seconds=i['uptime'])
130
 
            if i['ended_at']:
131
 
                terminated_instances.append(i)
132
 
            else:
133
 
                running_instances.append(i)
134
 
 
135
 
    instances = running_instances
136
 
    if show_terminated:
137
 
        instances += terminated_instances
138
 
 
139
 
    if request.GET.get('format', 'html') == 'csv':
140
 
        template_name = 'nova/instances/usage.csv'
141
 
        mimetype = "text/csv"
142
 
    else:
143
 
        template_name = 'nova/instances/usage.html'
144
 
        mimetype = "text/html"
145
 
 
146
 
    return shortcuts.render(request, template_name, {
147
 
                                'usage': usage,
148
 
                                'ram_unit': ram_unit,
149
 
                                'total_ram': total_ram,
150
 
                                'csv_link': '?format=csv',
151
 
                                'show_terminated': show_terminated,
152
 
                                'datetime_start': datetime_start,
153
 
                                'datetime_end': datetime_end,
154
 
                                'instances': instances},
155
 
                            content_type=mimetype)
156
 
 
157
 
 
158
 
@login_required
159
 
def console(request, instance_id):
160
 
    tenant_id = request.user.tenant_id
161
 
    try:
162
 
        # TODO(jakedahn): clean this up once the api supports tailing.
163
 
        length = request.GET.get('length', '')
164
 
        console = api.console_create(request, instance_id, 'text')
165
 
        response = http.HttpResponse(mimetype='text/plain')
166
 
        if length:
167
 
            response.write('\n'.join(console.output.split('\n')
168
 
                           [-int(length):]))
169
 
        else:
170
 
            response.write(console.output)
171
 
        response.flush()
172
 
        return response
173
 
    except api_exceptions.ApiException, e:
174
 
        LOG.exception(_('ApiException while fetching instance console'))
175
 
        messages.error(request,
176
 
                   _('Unable to get log for instance %(inst)s: %(msg)s') %
177
 
                    {"inst": instance_id, "msg": e.message})
178
 
        return shortcuts.redirect('horizon:nova:instances:index')
179
 
 
180
 
 
181
 
@login_required
182
 
def vnc(request, instance_id):
183
 
    tenant_id = request.user.tenant_id
184
 
    try:
185
 
        console = api.console_create(request, instance_id, 'vnc')
186
 
        instance = api.server_get(request, instance_id)
187
 
        return shortcuts.redirect(console.output +
188
 
                ("&title=%s(%s)" % (instance.name, instance_id)))
189
 
    except api_exceptions.ApiException, e:
190
 
        LOG.exception(_('ApiException while fetching instance vnc connection'))
191
 
        messages.error(request,
192
 
            _('Unable to get vnc console for instance %(inst)s: %(message)s') %
193
 
            {"inst": instance_id, "message": e.message})
194
 
        return shortcuts.redirect('horizon:nova:instances:index')
195
 
 
196
 
 
197
 
@login_required
198
 
def update(request, instance_id):
199
 
    tenant_id = request.user.tenant_id
200
 
    try:
201
 
        instance = api.server_get(request, instance_id)
202
 
    except api_exceptions.ApiException, e:
203
 
        LOG.exception(_('ApiException while fetching instance info'))
204
 
        messages.error(request,
205
 
            _('Unable to get information for instance %(inst)s: %(message)s') %
206
 
            {"inst": instance_id, "message": e.message})
207
 
        return shortcuts.redirect('horizon:nova:instances:index')
208
 
 
209
 
    form, handled = UpdateInstance.maybe_handle(request, initial={
210
 
                                'instance': instance_id,
211
 
                                'tenant_id': tenant_id,
212
 
                                'name': instance.name})
213
 
 
214
 
    if handled:
215
 
        return handled
216
 
 
217
 
    return shortcuts.render(request,
218
 
                            'nova/instances/update.html', {
219
 
                                'instance': instance,
220
 
                                'form': form})
221
 
 
222
 
 
223
 
@login_required
224
 
def detail(request, instance_id):
225
 
    tenant_id = request.user.tenant_id
226
 
    try:
227
 
        instance = api.server_get(request, instance_id)
228
 
        volumes = api.volume_instance_list(request, instance_id)
229
 
        try:
230
 
            console = api.console_create(request, instance_id, 'vnc')
231
 
            vnc_url = "%s&title=%s(%s)" % (console.output,
232
 
                                           instance.name,
233
 
                                           instance_id)
234
 
        except api_exceptions.ApiException, e:
235
 
            LOG.exception(_('ApiException while fetching instance vnc \
236
 
                           connection'))
237
 
            messages.error(request,
238
 
                _('Unable to get vnc console for instance %(inst)s: %(msg)s') %
239
 
                {"inst": instance_id, "msg": e.message})
240
 
            return shortcuts.redirect('horizon:nova:instances:index')
241
 
    except api_exceptions.ApiException, e:
242
 
        LOG.exception(_('ApiException while fetching instance info'))
243
 
        messages.error(request,
244
 
            _('Unable to get information for instance %(inst)s: %(msg)s') %
245
 
            {"inst": instance_id, "msg": e.message})
246
 
        return shortcuts.redirect('horizon:nova:instances:index')
247
 
 
248
 
    return shortcuts.render(request,
249
 
                            'nova/instances/detail.html', {
250
 
                                'instance': instance,
251
 
                                'vnc_url': vnc_url,
252
 
                                'volumes': volumes})