summaryrefslogtreecommitdiff
path: root/openstack_dashboard/dashboards/project/stacks/views.py
blob: f5d47ec56083e31084fb80967a333ec4c0bf820f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.

import json
from operator import attrgetter

import yaml

from django.core.urlresolvers import reverse
from django.core.urlresolvers import reverse_lazy
from django.http import HttpResponse
from django.utils.translation import ugettext_lazy as _
import django.views.generic

from horizon import exceptions
from horizon import forms
from horizon import tables
from horizon import tabs
from horizon.utils import memoized
from horizon import views
from openstack_dashboard import api
from openstack_dashboard.dashboards.project.stacks \
    import api as project_api
from openstack_dashboard.dashboards.project.stacks \
    import forms as project_forms
from openstack_dashboard.dashboards.project.stacks \
    import tables as project_tables
from openstack_dashboard.dashboards.project.stacks \
    import tabs as project_tabs


class IndexView(tables.DataTableView):
    table_class = project_tables.StacksTable
    page_title = _("Stacks")

    def __init__(self, *args, **kwargs):
        super(IndexView, self).__init__(*args, **kwargs)
        self._more = None

    def has_prev_data(self, table):
        return self._prev

    def has_more_data(self, table):
        return self._more

    def get_data(self):
        stacks = []
        filters = self.get_filters()
        prev_marker = self.request.GET.get(
            project_tables.StacksTable._meta.prev_pagination_param)
        if prev_marker is not None:
            sort_dir = 'asc'
            marker = prev_marker
        else:
            sort_dir = 'desc'
            marker = self.request.GET.get(
                project_tables.StacksTable._meta.pagination_param)
        try:
            stacks, self._more, self._prev = api.heat.stacks_list(
                self.request,
                marker=marker,
                paginate=True,
                sort_dir=sort_dir,
                filters=filters)
            if prev_marker is not None:
                stacks = sorted(stacks, key=attrgetter('creation_time'),
                                reverse=True)
        except Exception:
            self._prev = False
            self._more = False
            msg = _('Unable to retrieve stack list.')
            exceptions.handle(self.request, msg)
        return stacks


class SelectTemplateView(forms.ModalFormView):
    template_name = 'project/stacks/select_template.html'
    form_id = "select_template"
    form_class = project_forms.TemplateForm
    submit_label = _("Next")
    submit_url = reverse_lazy("horizon:project:stacks:select_template")
    success_url = reverse_lazy('horizon:project:stacks:launch')
    page_title = _("Select Template")

    def get_initial(self):
        initial = {}
        for name in [
            'template_url',
            'template_source',
            'template_data',
            'environment_source',
            'environment_data'
        ]:
            tmp = self.request.GET.get(name)
            if tmp:
                initial[name] = tmp
        return initial

    def get_form_kwargs(self):
        kwargs = super(SelectTemplateView, self).get_form_kwargs()
        kwargs['next_view'] = CreateStackView
        return kwargs


class ChangeTemplateView(forms.ModalFormView):
    template_name = 'project/stacks/change_template.html'
    form_id = "change_template"
    form_class = project_forms.ChangeTemplateForm
    submit_label = _("Next")
    submit_url = "horizon:project:stacks:change_template"
    cancel_url = reverse_lazy('horizon:project:stacks:index')
    success_url = reverse_lazy('horizon:project:stacks:edit_stack')
    page_title = _("Change Template")

    def get_context_data(self, **kwargs):
        context = super(ChangeTemplateView, self).get_context_data(**kwargs)
        args = (self.get_object().id,)
        context['submit_url'] = reverse(self.submit_url, args=args)
        return context

    @memoized.memoized_method
    def get_object(self):
        stack_id = self.kwargs['stack_id']
        try:
            self._stack = api.heat.stack_get(self.request, stack_id)
        except Exception:
            msg = _("Unable to retrieve stack.")
            redirect = reverse('horizon:project:stacks:index')
            exceptions.handle(self.request, msg, redirect=redirect)
        return self._stack

    def get_initial(self):
        stack = self.get_object()
        return {'stack_id': stack.id,
                'stack_name': stack.stack_name
                }

    def get_form_kwargs(self):
        kwargs = super(ChangeTemplateView, self).get_form_kwargs()
        kwargs['next_view'] = EditStackView
        return kwargs


class PreviewTemplateView(forms.ModalFormView):
    template_name = 'project/stacks/preview_template.html'
    form_id = "preview_template"
    form_class = project_forms.PreviewTemplateForm
    submit_label = _("Next")
    submit_url = reverse_lazy('horizon:project:stacks:preview_template')
    success_url = reverse_lazy('horizon:project:stacks:preview')
    page_title = _("Preview Template")

    def get_form_kwargs(self):
        kwargs = super(PreviewTemplateView, self).get_form_kwargs()
        kwargs['next_view'] = PreviewStackView
        return kwargs


class CreateStackView(forms.ModalFormView):
    template_name = 'project/stacks/create.html'
    form_id = "launch_stack"
    form_class = project_forms.CreateStackForm
    submit_label = _("Launch")
    submit_url = reverse_lazy("horizon:project:stacks:launch")
    success_url = reverse_lazy('horizon:project:stacks:index')
    page_title = _("Launch Stack")

    def get_initial(self):
        initial = {}
        if 'environment_data' in self.kwargs:
            initial['environment_data'] = self.kwargs['environment_data']
        if 'parameters' in self.kwargs:
            initial['parameters'] = json.dumps(self.kwargs['parameters'])
        return initial

    def get_form_kwargs(self):
        kwargs = super(CreateStackView, self).get_form_kwargs()
        if 'parameters' in self.kwargs:
            kwargs['parameters'] = self.kwargs['parameters']
        else:
            data = json.loads(self.request.POST['parameters'])
            kwargs['parameters'] = data
        return kwargs


# edit stack parameters, coming from template selector
class EditStackView(CreateStackView):
    template_name = 'project/stacks/update.html'
    form_id = "update_stack"
    form_class = project_forms.EditStackForm
    submit_label = _("Update")
    submit_url = "horizon:project:stacks:edit_stack"
    success_url = reverse_lazy('horizon:project:stacks:index')
    page_title = _("Update Stack")

    def get_initial(self):
        initial = super(EditStackView, self).get_initial()

        initial['stack'] = self.get_object()['stack']
        if initial['stack']:
            initial['stack_id'] = initial['stack'].id
            initial['stack_name'] = initial['stack'].stack_name

        return initial

    def get_context_data(self, **kwargs):
        context = super(EditStackView, self).get_context_data(**kwargs)
        args = (self.get_object()['stack'].id,)
        context['submit_url'] = reverse(self.submit_url, args=args)
        return context

    @memoized.memoized_method
    def get_object(self):
        stack_id = self.kwargs['stack_id']
        try:
            stack = {}
            stack['stack'] = api.heat.stack_get(self.request, stack_id)
            stack['template'] = api.heat.template_get(self.request, stack_id)
            self._stack = stack
        except Exception:
            msg = _("Unable to retrieve stack.")
            redirect = reverse('horizon:project:stacks:index')
            exceptions.handle(self.request, msg, redirect=redirect)
        return self._stack


class PreviewStackView(CreateStackView):
    template_name = 'project/stacks/preview.html'
    form_id = "preview_stack"
    form_class = project_forms.PreviewStackForm
    submit_label = _("Preview")
    submit_url = reverse_lazy('horizon:project:stacks:preview')
    success_url = reverse_lazy('horizon:project:stacks:index')
    page_title = _("Preview Stack")

    def get_form_kwargs(self):
        kwargs = super(CreateStackView, self).get_form_kwargs()
        kwargs['next_view'] = PreviewStackDetailsView
        return kwargs


class PreviewStackDetailsView(forms.ModalFormMixin, views.HorizonTemplateView):
    template_name = 'project/stacks/preview_details.html'
    page_title = _("Preview Stack Details")

    def get_context_data(self, **kwargs):
        context = super(
            PreviewStackDetailsView, self).get_context_data(**kwargs)
        context['stack_preview'] = self.kwargs['stack_preview'].to_dict()
        return context


class DetailView(tabs.TabView):
    tab_group_class = project_tabs.StackDetailTabs
    template_name = 'horizon/common/_detail.html'
    page_title = "{{ stack.stack_name|default:stack.id }}"

    def get_context_data(self, **kwargs):
        context = super(DetailView, self).get_context_data(**kwargs)
        stack = self.get_data(self.request, **kwargs)
        table = project_tables.StacksTable(self.request)
        context["stack"] = stack
        context["url"] = self.get_redirect_url()
        context["actions"] = table.render_row_actions(stack)
        return context

    @memoized.memoized_method
    def get_data(self, request, **kwargs):
        stack_id = kwargs['stack_id']
        try:
            stack = api.heat.stack_get(request, stack_id)
            request.session['stack_id'] = stack.id
            request.session['stack_name'] = stack.stack_name
            return stack
        except Exception:
            msg = _("Unable to retrieve stack.")
            exceptions.handle(request, msg, redirect=self.get_redirect_url())

    @memoized.memoized_method
    def get_template(self, request, **kwargs):
        try:
            stack_template = api.heat.template_get(
                request,
                kwargs['stack_id'])
            return yaml.safe_dump(stack_template, indent=2)
        except Exception:
            msg = _("Unable to retrieve stack template.")
            exceptions.handle(request, msg, redirect=self.get_redirect_url())

    def get_tabs(self, request, **kwargs):
        stack = self.get_data(request, **kwargs)
        stack_template = self.get_template(request, **kwargs)
        return self.tab_group_class(
            request, stack=stack, stack_template=stack_template, **kwargs)

    @staticmethod
    def get_redirect_url():
        return reverse('horizon:project:stacks:index')


class ResourceView(tabs.TabView):
    tab_group_class = project_tabs.ResourceDetailTabs
    template_name = 'horizon/common/_detail.html'
    page_title = "{{ resource.resource_name|"\
                 "default:resource.logical_resource_id }}"

    def get_context_data(self, **kwargs):
        context = super(ResourceView, self).get_context_data(**kwargs)
        context["resource"] = self.get_data(self.request, **kwargs)
        context["metadata"] = self.get_metadata(self.request, **kwargs)
        return context

    @memoized.memoized_method
    def get_data(self, request, **kwargs):
        try:
            resource = api.heat.resource_get(
                request,
                kwargs['stack_id'],
                kwargs['resource_name'])
            return resource
        except Exception:
            msg = _("Unable to retrieve resource.")
            redirect = reverse('horizon:project:stacks:index')
            exceptions.handle(request, msg, redirect=redirect)

    @memoized.memoized_method
    def get_metadata(self, request, **kwargs):
        try:
            metadata = api.heat.resource_metadata_get(
                request,
                kwargs['stack_id'],
                kwargs['resource_name'])
            return json.dumps(metadata, indent=2)
        except Exception:
            msg = _("Unable to retrieve metadata.")
            redirect = reverse('horizon:project:stacks:index')
            exceptions.handle(request, msg, redirect=redirect)

    def get_tabs(self, request, **kwargs):
        resource = self.get_data(request, **kwargs)
        metadata = self.get_metadata(request, **kwargs)
        return self.tab_group_class(
            request, resource=resource, metadata=metadata, **kwargs)


class JSONView(django.views.generic.View):
    def get(self, request, stack_id=''):
        return HttpResponse(project_api.d3_data(request, stack_id=stack_id),
                            content_type="application/json")