1# Licensed under the Apache License, Version 2.0 (the "License"); you may
2# not use this file except in compliance with the License. You may obtain
3# a copy of the License at
4#
5#      http://www.apache.org/licenses/LICENSE-2.0
6#
7# Unless required by applicable law or agreed to in writing, software
8# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
9# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
10# License for the specific language governing permissions and limitations
11# under the License.
12
13
14"""
15Views for managing backups.
16"""
17
18import operator
19
20from django.urls import reverse
21from django.utils.translation import ugettext_lazy as _
22
23from horizon import exceptions
24from horizon import forms
25from horizon import messages
26
27from openstack_dashboard import api
28from openstack_dashboard.dashboards.project.containers \
29    import utils as containers_utils
30
31
32class CreateBackupForm(forms.SelfHandlingForm):
33    name = forms.CharField(max_length=255, label=_("Backup Name"))
34    description = forms.CharField(widget=forms.Textarea(attrs={'rows': 4}),
35                                  label=_("Description"),
36                                  required=False)
37    container_name = forms.CharField(
38        max_length=255,
39        label=_("Container Name"),
40        validators=[containers_utils.no_slash_validator],
41        required=False)
42    volume_id = forms.CharField(widget=forms.HiddenInput())
43    snapshot_id = forms.ThemableChoiceField(label=_("Backup Snapshot"),
44                                            required=False)
45
46    def __init__(self, request, *args, **kwargs):
47        super().__init__(request, *args, **kwargs)
48        if kwargs['initial'].get('snapshot_id'):
49            snap_id = kwargs['initial']['snapshot_id']
50            try:
51                snapshot = api.cinder.volume_snapshot_get(request, snap_id)
52                self.fields['snapshot_id'].choices = [(snapshot.id,
53                                                       snapshot.name)]
54                self.fields['snapshot_id'].initial = snap_id
55            except Exception:
56                redirect = reverse('horizon:project:snapshots:index')
57                exceptions.handle(request, _('Unable to fetch snapshot'),
58                                  redirect=redirect)
59        else:
60            try:
61                sop = {'volume_id': kwargs['initial']['volume_id']}
62                snapshots = api.cinder.volume_snapshot_list(request,
63                                                            search_opts=sop)
64
65                snapshots.sort(key=operator.attrgetter('id', 'created_at'))
66                snapshotChoices = [[snapshot.id, snapshot.name]
67                                   for snapshot in snapshots]
68                if not snapshotChoices:
69                    snapshotChoices.insert(0, ('',
70                                           _("No snapshot for this volume")))
71                else:
72                    snapshotChoices.insert(
73                        0, ('',
74                            _("Select snapshot to backup (Optional)")))
75                self.fields['snapshot_id'].choices = snapshotChoices
76
77            except Exception:
78                redirect = reverse('horizon:project:volumes:index')
79                exceptions.handle(request, _('Unable to fetch snapshots'),
80                                  redirect=redirect)
81
82    def handle(self, request, data):
83        try:
84            volume = api.cinder.volume_get(request, data['volume_id'])
85            snapshot_id = data['snapshot_id'] or None
86            force = False
87            if volume.status == 'in-use':
88                force = True
89            backup = api.cinder.volume_backup_create(
90                request, data['volume_id'],
91                data['container_name'], data['name'],
92                data['description'], force=force,
93                snapshot_id=snapshot_id
94            )
95
96            message = _('Creating volume backup "%s"') % data['name']
97            messages.info(request, message)
98            return backup
99
100        except Exception:
101            redirect = reverse('horizon:project:volumes:index')
102            exceptions.handle(request,
103                              _('Unable to create volume backup.'),
104                              redirect=redirect)
105
106
107class RestoreBackupForm(forms.SelfHandlingForm):
108    volume_id = forms.ThemableChoiceField(label=_('Select Volume'),
109                                          required=False)
110    backup_id = forms.CharField(widget=forms.HiddenInput())
111    backup_name = forms.CharField(widget=forms.HiddenInput())
112    redirect_url = 'horizon:project:backups:index'
113
114    def __init__(self, request, *args, **kwargs):
115        super().__init__(request, *args, **kwargs)
116
117        try:
118            search_opts = {'status': 'available'}
119            volumes = api.cinder.volume_list(request, search_opts)
120        except Exception:
121            msg = _('Unable to lookup volume or backup information.')
122            redirect = reverse(self.redirect_url)
123            exceptions.handle(request, msg, redirect=redirect)
124            raise exceptions.Http302(redirect)
125
126        volumes.sort(key=operator.attrgetter('name', 'created_at'))
127        choices = [('', _('Create a New Volume'))]
128        choices.extend((volume.id, volume.name) for volume in volumes)
129        self.fields['volume_id'].choices = choices
130
131    def handle(self, request, data):
132        backup_id = data['backup_id']
133        backup_name = data['backup_name'] or None
134        volume_id = data['volume_id'] or None
135
136        try:
137            restore = api.cinder.volume_backup_restore(request,
138                                                       backup_id,
139                                                       volume_id)
140
141            # Needed for cases when a new volume is created.
142            volume_id = restore.volume_id
143
144            message = _('Request for restoring backup %(backup_name)s '
145                        'to volume with id: %(volume_id)s '
146                        'has been submitted.')
147            messages.info(request, message % {'backup_name': backup_name,
148                                              'volume_id': volume_id})
149            return restore
150        except Exception:
151            msg = _('Unable to restore backup.')
152            redirect = reverse(self.redirect_url)
153            exceptions.handle(request, msg, redirect=redirect)
154