-
Notifications
You must be signed in to change notification settings - Fork 478
/
forms.py
1913 lines (1661 loc) · 69.8 KB
/
forms.py
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
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#+
# Copyright 2010 iXsystems, Inc.
# All rights reserved
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted providing that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
# STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
# IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
#####################################################################
from collections import OrderedDict
from datetime import datetime, time
from decimal import Decimal
from os import popen, access, stat, mkdir, rmdir
from stat import S_ISDIR
import logging
import os
import re
import tempfile
from django.contrib.auth.models import User, UNUSABLE_PASSWORD
from django.contrib.formtools.wizard.views import SessionWizardView
from django.core.files.storage import FileSystemStorage
from django.db import transaction
from django.forms import FileField
from django.http import HttpResponse, QueryDict
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext_lazy as _, ungettext
from dojango import forms
from dojango.forms import CheckboxSelectMultiple
from freenasUI import choices
from freenasUI.common import humanize_number_si
from freenasUI.common.forms import ModelForm, Form
from freenasUI.common.system import mount, umount
from freenasUI.freeadmin.forms import (
CronMultiple, UserField, GroupField, WarningSelect
)
from freenasUI.freeadmin.views import JsonResp
from freenasUI.middleware import zfs
from freenasUI.middleware.exceptions import MiddlewareError
from freenasUI.middleware.notifier import notifier, GELI_KEYPATH
from freenasUI.services.exceptions import ServiceFailed
from freenasUI.services.models import iSCSITargetExtent, services
from freenasUI.storage import models
from freenasUI.storage.widgets import UnixPermissionField
attrs_dict = {'class': 'required', 'maxHeight': 200}
log = logging.getLogger('storage.forms')
DEDUP_WARNING = _("Enabling dedup may have drastic performance implications,"
"<br /> as well as impact your ability to access your data.<br /> "
"Consider using compression instead.")
class Disk(object):
dev = None
dtype = None
number = None
size = None
def __init__(self, devname, size, serial=None):
reg = re.search(r'^(.*?)([0-9]+)', devname)
if reg:
self.dtype, number = reg.groups()
self.number = int(number)
self.size = size
self.serial = serial
self.human_size = humanize_number_si(size)
self.dev = devname
def __lt__(self, other):
if self.human_size == other.human_size:
if self.dtype == other.dtype:
return self.number < other.number
return self.dtype < other.dtype
return self.size > other.size
def __repr__(self):
return u'<Disk: %s>' % str(self)
def __str__(self):
extra = ' %s' % (self.serial,) if self.serial else ''
return u'%s (%s)%s' % (self.dev, humanize_number_si(self.size), extra)
def __iter__(self):
yield self.dev
yield str(self)
def _clean_quota_fields(form, attrs, prefix):
cdata = form.cleaned_data
for field in map(lambda x: prefix + x, attrs):
if field not in cdata:
cdata[field] = ''
r = re.compile(r'^(?P<number>[\.0-9]+)(?P<suffix>[KMGT]?)$', re.I)
msg = _(u"Enter positive number (optionally suffixed by K, M, G, T), "
"or, 0")
for attr in attrs:
formfield = '%s%s' % (prefix, attr)
match = r.match(cdata[formfield])
if not match and cdata[formfield] != "0":
form._errors[formfield] = form.error_class([msg])
del cdata[formfield]
elif match:
number, suffix = match.groups()
try:
Decimal(number)
except:
form._errors[formfield] = form.error_class([
_("%s is not a valid number") % (number, ),
])
del cdata[formfield]
return cdata
class VolumeWizardForm(forms.Form):
volume_name = forms.CharField(
max_length=30,
label=_('Volume name'),
required=False)
volume_fstype = forms.ChoiceField(
choices=((x, x) for x in ('UFS', 'ZFS')),
widget=forms.RadioSelect(attrs=attrs_dict),
label=_('Filesystem type'))
volume_disks = forms.MultipleChoiceField(
choices=(),
widget=forms.SelectMultiple(attrs=attrs_dict),
label='Member disks',
required=False)
group_type = forms.ChoiceField(
choices=(),
widget=forms.RadioSelect(attrs=attrs_dict),
required=False)
force4khack = forms.BooleanField(
required=False,
initial=False,
help_text=_('Force 4096 bytes sector size'))
encryption = forms.BooleanField(
required=False,
initial=False,
help_text=_('Whole disk encryption'))
encryption_inirand = forms.BooleanField(
initial=False,
required=False,
)
dedup = forms.ChoiceField(label=_('ZFS Deduplication'),
choices=choices.ZFS_DEDUP,
initial="off",
)
ufspathen = forms.BooleanField(
initial=False,
label=_('Specify custom path'),
required=False)
ufspath = forms.CharField(
max_length=1024,
label=_('Path'),
required=False)
def __init__(self, *args, **kwargs):
super(VolumeWizardForm, self).__init__(*args, **kwargs)
self.fields['volume_disks'].choices = self._populate_disk_choices()
qs = models.Volume.objects.filter(vol_fstype='ZFS')
if qs.exists():
self.fields['volume_add'] = forms.ChoiceField(
label=_('Volume add'),
required=False)
self.fields['volume_add'].choices = [('', '-----')] + \
[
("%s|%s" % (x.vol_name, x.vol_encrypt > 0), x.vol_name)
for x in qs
]
self.fields['volume_add'].widget.attrs['onChange'] = (
'wizardcheckings(true);')
self.fields['volume_fstype'].widget.attrs['onClick'] = (
'wizardcheckings();')
self.fields['encryption'].widget.attrs['onClick'] = (
'wizardcheckings();')
self.fields['ufspathen'].widget.attrs['onClick'] = (
'toggleGeneric("id_ufspathen", ["id_ufspath"], true);')
if not self.data.get("ufspathen", False):
self.fields['ufspath'].widget.attrs['disabled'] = 'disabled'
self.fields['ufspath'].widget.attrs['promptMessage'] = _("Leaving this"
" blank will give the volume a default path of "
"/mnt/${VOLUME_NAME}")
grouptype_choices = (
('mirror', 'mirror'),
('stripe', 'stripe'),
)
fstype = self.data.get("volume_fstype", None)
if "volume_disks" in self.data:
disks = self.data.getlist("volume_disks")
else:
disks = []
if fstype == "UFS":
l = len(disks) - 1
if l >= 2 and (((l - 1) & l) == 0):
grouptype_choices += (
('raid3', 'RAID-3'),
)
elif fstype == "ZFS":
if len(disks) >= 3:
grouptype_choices += (('raidz', 'RAID-Z'), )
if len(disks) >= 4:
grouptype_choices += ( ('raidz2', 'RAID-Z2'), )
if len(disks) >= 5:
grouptype_choices += ( ('raidz3', 'RAID-Z3'), )
self.fields['group_type'].choices = grouptype_choices
def _populate_disk_choices(self):
disks = []
# Grab disk list
# Root device already ruled out
for disk, info in notifier().get_disks().items():
disks.append(Disk(info['devname'], info['capacity'],
serial=info.get('ident')))
# Exclude what's already added
used_disks = []
for v in models.Volume.objects.all():
used_disks.extend(v.get_disks())
qs = iSCSITargetExtent.objects.filter(iscsi_target_extent_type='Disk')
used_disks.extend([i.get_device()[5:] for i in qs])
for d in list(disks):
if d.dev in used_disks:
disks.remove(d)
choices = sorted(disks)
choices = [tuple(d) for d in choices]
return choices
def clean_volume_name(self):
vname = self.cleaned_data['volume_name']
if vname and not re.search(r'^[a-z][-_.a-z0-9]*$', vname, re.I):
raise forms.ValidationError(_("The volume name must start with "
"letters and may include numbers, \"-\", \"_\" and \".\" ."))
if models.Volume.objects.filter(vol_name=vname).exists():
raise forms.ValidationError(_("A volume with that name already "
"exists."))
return vname
def clean_group_type(self):
len_disks = len(self.cleaned_data['volume_disks'])
if 'volume_disks' not in self.cleaned_data or \
len_disks > 1 and \
self.cleaned_data['group_type'] in (None, ''):
raise forms.ValidationError(_("This field is required."))
if len_disks == 1:
if self.cleaned_data.get("volume_fstype") == 'ZFS':
return 'stripe'
else:
# UFS middleware expects no group_type for single disk volume
return ''
return self.cleaned_data['group_type']
def clean_ufspath(self):
ufspath = self.cleaned_data['ufspath']
if not ufspath:
return None
if not access(ufspath, 0):
raise forms.ValidationError(_("Path does not exist."))
st = stat(ufspath)
if not S_ISDIR(st.st_mode):
raise forms.ValidationError(_("Path is not a directory."))
return ufspath
def clean(self):
cleaned_data = self.cleaned_data
volume_name = cleaned_data.get("volume_name", "")
disks = cleaned_data.get("volume_disks", [])
if volume_name and cleaned_data.get("volume_add"):
self._errors['__all__'] = self.error_class([
_("You cannot select an existing ZFS volume and specify a new "
"volume name"),
])
elif not(volume_name or cleaned_data.get("volume_add")):
self._errors['__all__'] = self.error_class([
_("You must specify a new volume name or select an existing "
"ZFS volume to append a virtual device"),
])
elif not volume_name:
volume_name = cleaned_data.get("volume_add", '').split('|')[0]
if cleaned_data.get("volume_add"):
cleaned_data["volume_add"] = cleaned_data.get("volume_add").split("|")[0]
zpool = notifier().zpool_parse(cleaned_data.get("volume_add"))
force_vdev = True if self.data.get("force_vdev") == 'on' else False
for vdev in zpool.data:
if not self.cleaned_data.get('group_type'):
continue
errors = []
if vdev.type != self.cleaned_data.get('group_type'):
#and not force_vdev:
self.fields['force_vdev'] = forms.BooleanField(
required=True,
label=_("Force Volume Add"),
initial=False,
)
if not force_vdev:
errors.append(
_("You are trying to add a virtual device of type "
"'%(addtype)s' in a pool that has a virtual "
"device of type '%(vdevtype)s'") % {
'addtype': self.cleaned_data.get('group_type'),
'vdevtype': vdev.type,
}
)
if len(disks) != len(list(iter(vdev))):
self.fields['force_vdev'] = forms.BooleanField(
required=True,
label=_("Force Volume Add"),
initial=False,
)
if not force_vdev:
errors.append(
_("You are trying to add a virtual device consisting"
" of %(addnum)s device(s) in a pool that has a "
"virtual device consisted of %(vdevnum)s device(s)"
) % {
'addnum': len(disks),
'vdevnum': len(list(iter(vdev))),
}
)
if errors:
self._errors['force_vdev'] = self.error_class(errors)
break
if cleaned_data.get("volume_fstype") not in ('ZFS', 'UFS'):
msg = _(u"You must select a filesystem")
self._errors["volume_fstype"] = self.error_class([msg])
cleaned_data.pop("volume_fstype", None)
if len(disks) == 0 and models.Volume.objects.filter(
vol_name=volume_name).count() == 0:
msg = _(u"This field is required")
self._errors["volume_disks"] = self.error_class([msg])
del cleaned_data["volume_disks"]
if (cleaned_data.get("volume_fstype") == 'ZFS' and \
models.Volume.objects.filter(vol_name=volume_name).exclude(
vol_fstype='ZFS').count() > 0
) or (
cleaned_data.get("volume_fstype") == 'UFS' and \
models.Volume.objects.filter(
vol_name=volume_name).count() > 0
):
msg = _(u"You already have a volume with same name")
self._errors["volume_name"] = self.error_class([msg])
del cleaned_data["volume_name"]
if cleaned_data.get("volume_fstype", None) == 'ZFS':
if volume_name in ('log',):
msg = _(u"\"log\" is a reserved word and thus cannot be used")
self._errors["volume_name"] = self.error_class([msg])
cleaned_data.pop("volume_name", None)
elif re.search(r'^c[0-9].*', volume_name) or \
re.search(r'^mirror.*', volume_name) or \
re.search(r'^spare.*', volume_name) or \
re.search(r'^raidz.*', volume_name):
msg = _(u"The volume name may NOT start with c[0-9], mirror, "
"raidz or spare")
self._errors["volume_name"] = self.error_class([msg])
cleaned_data.pop("volume_name", None)
elif cleaned_data.get("volume_fstype") == 'UFS' and volume_name:
if len(volume_name) > 9:
msg = _(u"UFS volume names cannot be higher than 9 characters")
self._errors["volume_name"] = self.error_class([msg])
cleaned_data.pop("volume_name", None)
elif not re.search(r'^[a-z0-9]+$', volume_name, re.I):
msg = _(u"UFS volume names can only contain alphanumeric "
"characters")
self._errors["volume_name"] = self.error_class([msg])
cleaned_data.pop("volume_name", None)
return cleaned_data
def done(self, request):
# Construct and fill forms into database.
volume_name = self.cleaned_data.get("volume_name") or \
self.cleaned_data.get("volume_add")
volume_fstype = self.cleaned_data['volume_fstype']
disk_list = self.cleaned_data['volume_disks']
group_type = self.cleaned_data.get('group_type')
force4khack = self.cleaned_data.get("force4khack", False)
init_rand = self.cleaned_data.get("encryption_inirand", False)
if self.cleaned_data.get("encryption", False):
volume_encrypt = 1
else:
volume_encrypt = 0
dedup = self.cleaned_data.get("dedup", False)
ufspath = self.cleaned_data['ufspath']
mp_options = "rw"
mp_path = None
with transaction.commit_on_success():
vols = models.Volume.objects.filter(vol_name=volume_name,
vol_fstype='ZFS')
if vols.count() == 1:
volume = vols[0]
add = True
else:
add = False
volume = models.Volume(vol_name=volume_name,
vol_fstype=volume_fstype, vol_encrypt=volume_encrypt)
volume.save()
mp_path = ufspath if ufspath else '/mnt/' + volume_name
if volume_fstype == 'UFS':
mp_options = 'rw,nfsv4acls'
mp = models.MountPoint(mp_volume=volume, mp_path=mp_path,
mp_options=mp_options)
mp.save()
self.volume = volume
zpoolfields = re.compile(r'zpool_(.+)')
grouped = OrderedDict()
grouped['root'] = {'type': group_type, 'disks': disk_list}
for i, gtype in request.POST.items():
if zpoolfields.match(i):
if gtype == 'none':
continue
disk = zpoolfields.search(i).group(1)
if gtype in grouped:
# if this is a log vdev we need to mirror it for safety
if gtype == 'log':
grouped[gtype]['type'] = 'log mirror'
grouped[gtype]['disks'].append(disk)
else:
grouped[gtype] = {'type': gtype, 'disks': [disk, ]}
if len(disk_list) > 0 and add:
notifier().zfs_volume_attach_group(volume, grouped['root'],
force4khack=force4khack)
if add:
for grp_type in grouped:
if grp_type in ('log', 'cache', 'spare'):
notifier().zfs_volume_attach_group(volume,
grouped.get(grp_type),
force4khack=force4khack)
else:
notifier().init(
"volume",
volume,
groups=grouped,
force4khack=force4khack,
path=ufspath,
init_rand=init_rand,
)
if dedup:
notifier().zfs_set_option(volume.vol_name, "dedup", dedup)
if volume.vol_fstype == 'ZFS':
models.Scrub.objects.create(scrub_volume=volume)
if volume.vol_encrypt >= 2 and add:
#FIXME: ask current passphrase to the user
notifier().geli_passphrase(volume, None)
volume.vol_encrypt = 1
volume.save()
if mp_path in ('/etc', '/var', '/usr'):
device = '/dev/ufs/' + volume_name
mp = '/mnt/' + volume_name
if not access(mp, 0):
mkdir(mp, 755)
mount(device, mp)
popen("/usr/local/bin/rsync -avz '%s/*' '%s/'" % (
mp_path, mp)
).close()
umount(mp)
if access(mp, 0):
rmdir(mp)
else:
# This must be outside transaction block to make sure the changes
# are committed before the call of ix-fstab
notifier().reload("disk")
# For scrub cronjob
if volume.vol_fstype == 'ZFS':
notifier().restart("cron")
class VolumeImportForm(forms.Form):
volume_name = forms.CharField(max_length=30, label=_('Volume name'))
volume_disks = forms.ChoiceField(choices=(),
widget=forms.Select(attrs=attrs_dict),
label=_('Member disk'))
volume_fstype = forms.ChoiceField(
choices=((x, x) for x in ('UFS', 'NTFS', 'MSDOSFS', 'EXT2FS')),
widget=forms.RadioSelect(attrs=attrs_dict),
label='File System type')
def __init__(self, *args, **kwargs):
super(VolumeImportForm, self).__init__(*args, **kwargs)
self.fields['volume_disks'].choices = self._populate_disk_choices()
def _populate_disk_choices(self):
used_disks = []
for v in models.Volume.objects.all():
used_disks.extend(v.get_disks())
qs = iSCSITargetExtent.objects.filter(iscsi_target_extent_type='Disk')
diskids = [i[0] for i in qs.values_list('iscsi_target_extent_path')]
used_disks.extend([d.disk_name for d in models.Disk.objects.filter(
id__in=diskids)])
n = notifier()
# Grab partition list
# NOTE: This approach may fail if device nodes are not accessible.
_parts = n.get_partitions()
for name, part in _parts.items():
for i in used_disks:
if re.search(r'^%s([ps]|$)' % i, part['devname']) is not None:
del _parts[name]
continue
parts = []
for name, part in _parts.items():
parts.append(Disk(part['devname'], part['capacity']))
choices = sorted(parts)
choices = [tuple(p) for p in choices]
return choices
def clean(self):
cleaned_data = self.cleaned_data
volume_name = cleaned_data.get("volume_name")
if models.Volume.objects.filter(vol_name=volume_name).count() > 0:
msg = _(u"You already have a volume with same name")
self._errors["volume_name"] = self.error_class([msg])
del cleaned_data["volume_name"]
devpath = "/dev/%s" % (cleaned_data.get('volume_disks', []), )
isvalid = notifier().precheck_partition(devpath,
cleaned_data.get('volume_fstype', ''))
if not isvalid:
msg = _(u"The selected disks were not verified for this import "
"rules.")
self._errors["volume_name"] = self.error_class([msg])
if "volume_name" in cleaned_data:
del cleaned_data["volume_name"]
if "volume_name" in cleaned_data:
dolabel = notifier().label_disk(cleaned_data["volume_name"],
devpath, cleaned_data['volume_fstype'])
if not dolabel:
msg = _(u"An error occurred while labeling the disk.")
self._errors["volume_name"] = self.error_class([msg])
cleaned_data.pop("volume_name", None)
return cleaned_data
def done(self, request):
# Construct and fill forms into database.
volume_name = self.cleaned_data['volume_name']
volume_fstype = self.cleaned_data['volume_fstype']
volume = models.Volume(vol_name=volume_name, vol_fstype=volume_fstype)
volume.save()
self.volume = volume
mp = models.MountPoint(mp_volume=volume, mp_path='/mnt/' + volume_name,
mp_options='rw')
mp.save()
notifier().start("ix-fstab")
notifier().mount_volume(volume)
#notifier().reload("disk")
def show_descrypt_condition(wizard):
cleaned_data = wizard.get_cleaned_data_for_step('0') or {}
if cleaned_data.get("step") == "decrypt":
return True
else:
return False
class AutoImportWizard(SessionWizardView):
file_storage = FileSystemStorage(location='/var/tmp/firmware')
def get_template_names(self):
return [
'storage/autoimport_wizard_%s.html' % self.get_step_index(),
'storage/autoimport_wizard.html',
]
def process_step(self, form):
proc = super(AutoImportWizard, self).process_step(form)
"""
We execute the form done method if there is one, for each step
"""
if hasattr(form, 'done'):
retval = form.done(request=self.request,
form_list=self.form_list,
wizard=self)
if self.get_step_index() == self.steps.count - 1:
self.retval = retval
return proc
def render_to_response(self, context, **kwargs):
response = super(AutoImportWizard, self).render_to_response(
context,
**kwargs
)
# This is required for the workaround dojo.io.frame for file upload
if not self.request.is_ajax():
return HttpResponse(
"<html><body><textarea>"
+ response.rendered_content +
"</textarea></boby></html>")
return response
def done(self, form_list, **kwargs):
cdata = self.get_cleaned_data_for_step('1') or {}
enc_disks = cdata.get("disks", [])
key = cdata.get("key")
passphrase = cdata.get("passphrase")
passfile = None
if key and passphrase:
encrypt = 2
passfile = tempfile.mktemp(dir='/tmp/')
with open(passfile, 'w') as f:
os.chmod(passfile, 600)
f.write(passphrase)
elif key:
encrypt = 1
else:
encrypt = 0
cdata = self.get_cleaned_data_for_step('2') or {}
vol = cdata['volume']
volume_name = vol['label']
group_type = vol['group_type']
if vol['type'] == 'geom':
volume_fstype = 'UFS'
elif vol['type'] == 'zfs':
volume_fstype = 'ZFS'
try:
with transaction.commit_on_success():
volume = models.Volume(
vol_name=volume_name,
vol_fstype=volume_fstype,
vol_encrypt=encrypt)
volume.save()
if encrypt > 0:
if not os.path.exists(GELI_KEYPATH):
os.mkdir(GELI_KEYPATH)
key.seek(0)
keydata = key.read()
with open(volume.get_geli_keyfile(), 'wb') as f:
f.write(keydata)
self.volume = volume
mp = models.MountPoint(mp_volume=volume,
mp_path='/mnt/' + volume_name,
mp_options='rw')
mp.save()
if vol['type'] != 'zfs':
notifier().label_disk(volume_name,
"%s/%s" % (group_type, volume_name),
'UFS')
else:
volume.vol_guid = vol['id']
volume.save()
models.Scrub.objects.create(scrub_volume=volume)
if vol['type'] == 'zfs' and not notifier().zfs_import(
vol['label'], vol['id']):
raise MiddlewareError(_('The volume "%s" failed to import, '
'for futher details check pool status') % vol['label'])
for disk in enc_disks:
notifier().geli_setkey(
"/dev/%s" % disk,
volume.get_geli_keyfile(),
passphrase=passfile
)
if disk.startswith("gptid"):
diskname = notifier().identifier_to_device(
"{uuid}%s" % disk.replace("gptid/", "")
)
else:
diskname = disk
ed = models.EncryptedDisk()
ed.encrypted_volume = volume
ed.encrypted_disk = models.Disk.objects.filter(disk_name=diskname, disk_enabled=True)[0]
ed.encrypted_provider = disk
ed.save()
except:
if passfile:
os.unlink(passfile)
raise
notifier().reload("disk")
return JsonResp(self.request, message=unicode(_("Volume imported")))
class AutoImportChoiceForm(forms.Form):
step = forms.ChoiceField(
choices=(
('import', _("No: Skip to import")),
('decrypt', _("Yes: Decrypt disks")),
),
label=_("Encrypted ZFS volume?"),
widget=forms.RadioSelect(),
initial="import",
)
def done(self, *args, **kwargs):
# Detach all unused geli providers before proceeding
# This makes sure do not import pools without proper key
_notifier = notifier()
for dev, name in notifier().geli_get_all_providers():
_notifier.geli_detach(dev)
class AutoImportDecryptForm(forms.Form):
disks = forms.MultipleChoiceField(
choices=(),
)
key = FileField(
label=_("Encryption Key"),
)
passphrase = forms.CharField(
label=_("Passphrase"),
required=False,
widget=forms.widgets.PasswordInput(),
)
def __init__(self, *args, **kwargs):
super(AutoImportDecryptForm, self).__init__(*args, **kwargs)
self.fields['disks'].choices=self._populate_disk_choices()
def _populate_disk_choices(self):
return notifier().geli_get_all_providers()
def clean(self):
key = self.cleaned_data.get("key")
if not key:
return self.cleaned_data
disks = self.cleaned_data.get("disks")
if not disks:
return self.cleaned_data
passphrase = self.cleaned_data.get("passphrase")
if passphrase:
passfile = tempfile.mktemp(dir='/tmp/')
with open(passfile, 'w') as f:
os.chmod(passfile, 600)
f.write(passphrase)
passphrase = passfile
keyfile = tempfile.mktemp(dir='/var/tmp/firmware')
with open(keyfile, 'wb') as f:
os.chmod(keyfile, 600)
f.write(key.read())
_notifier = notifier()
failed = []
for disk in disks:
if not _notifier.geli_attach_single(
disk,
keyfile,
passphrase=passphrase
):
failed.append(disk)
if failed:
self._errors['__all__'] = self.error_class([
_("The following disks failed to attach: %s") % (
', '.join(failed),
)
])
os.unlink(keyfile)
if passphrase:
os.unlink(passphrase)
return self.cleaned_data
class VolumeAutoImportForm(forms.Form):
volume_disks = forms.ChoiceField(
choices=(),
widget=forms.Select(attrs=attrs_dict),
label=_('Volume'))
def __init__(self, *args, **kwargs):
super(VolumeAutoImportForm, self).__init__(*args, **kwargs)
self.fields['volume_disks'].choices = self._populate_disk_choices()
def _populate_disk_choices(self):
diskchoices = dict()
used_disks = []
for v in models.Volume.objects.all():
used_disks.extend(v.get_disks())
# Grab partition list
# NOTE: This approach may fail if device nodes are not accessible.
vols = notifier().detect_volumes()
for vol in list(vols):
for vdev in vol['disks']['vdevs']:
for disk in vdev['disks']:
if filter(lambda x: x is not None and \
re.search(r'^%s([ps]|$)' % disk['name'], x),
used_disks):
vols.remove(vol)
break
else:
continue
break
for vol in vols:
if vol.get("id", None):
devname = "%s [%s, id=%s]" % (
vol['label'],
vol['type'],
vol['id'])
else:
devname = "%s [%s]" % (vol['label'], vol['type'])
diskchoices[vol['label']] = "%s" % (devname,)
choices = diskchoices.items()
return choices
def clean(self):
cleaned_data = self.cleaned_data
vols = notifier().detect_volumes()
for vol in vols:
if vol['label'] == cleaned_data.get('volume_disks'):
cleaned_data['volume'] = vol
break
if cleaned_data.get('volume', None) == None:
self._errors['__all__'] = self.error_class([
_("You must select a volume."),
])
else:
if models.Volume.objects.filter(
vol_name=cleaned_data['volume']['label']).count() > 0:
msg = _(u"You already have a volume with same name")
self._errors["volume_disks"] = self.error_class([msg])
del cleaned_data["volume_disks"]
if cleaned_data['volume']['type'] == 'geom':
if cleaned_data['volume']['group_type'] == 'mirror':
dev = "/dev/mirror/%s" % (cleaned_data['volume']['label'])
elif cleaned_data['volume']['group_type'] == 'stripe':
dev = "/dev/stripe/%s" % (cleaned_data['volume']['label'])
elif cleaned_data['volume']['group_type'] == 'raid3':
dev = "/dev/raid3/%s" % (cleaned_data['volume']['label'])
else:
raise NotImplementedError
isvalid = notifier().precheck_partition(dev, 'UFS')
if not isvalid:
msg = _(u"The selected disks were not verified for this "
"import rules.")
self._errors["volume_disks"] = self.error_class([msg])
if "volume_disks" in cleaned_data:
del cleaned_data["volume_disks"]
elif cleaned_data['volume']['type'] != 'zfs':
raise NotImplementedError
return cleaned_data
class DiskFormPartial(ModelForm):
class Meta:
model = models.Disk
exclude = (
'disk_transfermode', # This option isn't used anywhere
)
def __init__(self, *args, **kwargs):
super(DiskFormPartial, self).__init__(*args, **kwargs)
instance = getattr(self, 'instance', None)
if instance and instance.id:
self._original_smart_en = self.instance.disk_togglesmart
self._original_smart_opts = self.instance.disk_smartoptions
self.fields['disk_name'].widget.attrs['readonly'] = True
self.fields['disk_name'].widget.attrs['class'] = ('dijitDisabled'
' dijitTextBoxDisabled dijitValidationTextBoxDisabled')
self.fields['disk_serial'].widget.attrs['readonly'] = True
self.fields['disk_serial'].widget.attrs['class'] = ('dijitDisabled'
' dijitTextBoxDisabled dijitValidationTextBoxDisabled')
def clean_disk_name(self):
return self.instance.disk_name
def save(self, *args, **kwargs):
obj = super(DiskFormPartial, self).save(*args, **kwargs)
# Commit ataidle changes, if any
if (
obj.disk_hddstandby != obj._original_state['disk_hddstandby'] or
obj.disk_advpowermgmt != obj._original_state['disk_advpowermgmt'] or
obj.disk_acousticlevel != obj._original_state['disk_acousticlevel']
):
notifier().start_ataidle(obj.disk_name)
if (
obj.disk_togglesmart != self._original_smart_en or
obj.disk_smartoptions != self._original_smart_opts
):
started = notifier().restart("smartd")
if started is False and \
services.objects.get(srv_service='smartd').srv_enable:
raise ServiceFailed(
"smartd",
_("The SMART service failed to restart.")
)
return obj
class ZFSDataset_CreateForm(Form):
dataset_name = forms.CharField(max_length=128,
label=_('Dataset Name'))
dataset_compression = forms.ChoiceField(
choices=choices.ZFS_CompressionChoices,
widget=forms.Select(attrs=attrs_dict),
label=_('Compression level'))
dataset_atime = forms.ChoiceField(
choices=choices.ZFS_AtimeChoices,
widget=forms.RadioSelect(attrs=attrs_dict),
label=_('Enable atime'))
dataset_refquota = forms.CharField(
max_length=128,
initial=0,
label=_('Quota for this dataset'),
help_text=_('0=Unlimited; example: 1g'))
dataset_quota = forms.CharField(
max_length=128,
initial=0,
label=_('Quota for this dataset and all children'),
help_text=_('0=Unlimited; example: 1g'))
dataset_refreserv = forms.CharField(
max_length=128,
initial=0,
label=_('Reserved space for this dataset'),
help_text=_('0=None; example: 1g'))
dataset_reserv = forms.CharField(
max_length=128,
initial=0,
label=_('Reserved space for this dataset and all children'),
help_text=_('0=None; example: 1g'))
dataset_dedup = forms.ChoiceField(label=_('ZFS Deduplication'),
choices=choices.ZFS_DEDUP_INHERIT,
widget=WarningSelect(text=DEDUP_WARNING),
initial="inherit",
)