summaryrefslogtreecommitdiff
path: root/virtinst/Storage.py
blob: e0b0ef172ca062da26c0479d4399d68c6f6bd3f3 (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
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
#
# Copyright 2008, 2013 Red Hat, Inc.
# Cole Robinson <crobinso@redhat.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free  Software Foundation; either version 2 of the License, or
# (at your option)  any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301 USA.
"""
Classes for building and installing libvirt storage xml

General workflow for the different storage objects:

    1. Storage Pool:

    Pool type options can be exposed to a user via the static function
    L{StoragePool.get_pool_types}. Any selection can be fed back into
    L{StoragePool.get_pool_class} to get the particular volume class to
    instantiate. From here, values can be set at init time or via
    properties post init.

    Different pool types have different options and
    requirements, so using getattr() is probably the best way to check
    for parameter availability.

    2) Storage Volume:

    There are a few options for determining what pool volume class to use:
        - Pass the pools type for L{StoragePool.get_volume_for_pool}
        - Pass the pool object or name to L{StorageVolume.get_volume_for_pool}

    These will give back the appropriate class to instantiate. For most cases,
    all that's needed is a name and capacity, the rest will be filled in.

@see: U{http://libvirt.org/storage.html}
"""

import os
import threading
import time
import logging

import libvirt
import urlgrabber

from virtinst.util import xml_escape as escape
from virtinst import util


DEFAULT_DEV_TARGET = "/dev"
DEFAULT_LVM_TARGET_BASE = "/dev/"
DEFAULT_DIR_TARGET_BASE = "/var/lib/libvirt/images/"
DEFAULT_SCSI_TARGET = "/dev/disk/by-path"
DEFAULT_MPATH_TARGET = "/dev/mapper"

# Pulled from libvirt, used for building on older versions
VIR_STORAGE_VOL_FILE = 0
VIR_STORAGE_VOL_BLOCK = 1


def _parse_pool_source_list(source_xml):
    def source_parser(node):
        ret_list = []

        child = node.children
        while child:
            if child.name == "source":
                val_dict = {}
                source = child.children

                while source:
                    if source.name == "name":
                        val_dict["source_name"] = source.content
                    elif source.name == "host":
                        val_dict["host"] = source.prop("name")
                    elif source.name == "format":
                        val_dict["format"] = source.prop("type")
                    elif source.name in ["device", "dir"]:
                        val_dict["source_path"] = source.prop("path")
                    source = source.next

                ret_list.append(val_dict)

            child = child.next

        for val_dict in ret_list:
            if (val_dict.get("format") == "lvm2" and
                val_dict.get("source_name") and
                not val_dict.get("target_path")):
                val_dict["target_path"] = (DEFAULT_LVM_TARGET_BASE +
                                           val_dict["source_name"])

        return ret_list

    return util.parse_node_helper(source_xml, "sources", source_parser)


class StorageObject(object):
    """
    Base class for building any libvirt storage object.

    Mostly meaningless to directly instantiate.
    """

    TYPE_POOL   = "pool"
    TYPE_VOLUME = "volume"

    def __init__(self, conn, object_type, name):
        """
        Initialize storage object parameters
        """
        if object_type not in [self.TYPE_POOL, self.TYPE_VOLUME]:
            raise ValueError(_("Unknown storage object type: %s") % type)
        self._object_type = object_type
        self._conn = conn
        self._name = None

        self.name = name

        # Initialize all optional properties
        self._perms = None


    ## Properties
    def get_object_type(self):
        # 'pool' or 'volume'
        return self._object_type
    object_type = property(get_object_type)

    def _get_conn(self):
        return self._conn
    conn = property(_get_conn)

    def get_name(self):
        return self._name
    def set_name(self, val):
        util.validate_name(_("Storage object"), val)

        # Check that name doesn't collide with other storage objects
        self._check_name_collision(val)
        self._name = val
    name = property(get_name, set_name, doc=_("Name for the storage object."))

    # Get/Set methods for use by some objects. Will register where applicable
    def get_perms(self):
        return self._perms
    def set_perms(self, val):
        if type(val) is not dict:
            raise ValueError(_("Permissions must be passed as a dict object"))
        for key in ["mode", "owner", "group"]:
            if not key in val:
                raise ValueError(_("Permissions must contain 'mode', 'owner' and 'group' keys."))
        self._perms = val


    # Validation helper functions
    def _validate_path(self, path):
        if not isinstance(path, str) or not path.startswith("/"):
            raise ValueError(_("'%s' is not an absolute path." % path))

    def _check_name_collision(self, name):
        ignore = name
        raise NotImplementedError()

    # XML Building
    def _get_storage_xml(self):
        """
        Returns the pool/volume specific xml blob
        """
        raise NotImplementedError()

    def _get_perms_xml(self):
        perms = self.get_perms()
        if not perms:
            return ""
        xml = "    <permissions>\n" + \
              "      <mode>0%o</mode>\n" % perms["mode"] + \
              "      <owner>%d</owner>\n" % perms["owner"] + \
              "      <group>%d</group>\n" % perms["group"]

        if "label" in perms:
            xml += "      <label>%s</label>\n" % perms["label"]

        xml += "    </permissions>\n"
        return xml


    def get_xml_config(self):
        """
        Construct the xml description of the storage object

        @returns: xml description
        @rtype: C{str}
        """
        if not hasattr(self, "type"):
            root_xml = "<%s>\n" % self.object_type
        else:
            _type = getattr(self, "type")
            root_xml = "<%s type='%s'>\n" % (self.object_type, _type)

        xml = "%s" % (root_xml) + \
              """  <name>%s</name>\n""" % (self.name) + \
              """%(stor_xml)s""" % {"stor_xml" : self._get_storage_xml()} + \
              """</%s>\n""" % (self.object_type)
        return xml




class StoragePool(StorageObject):
    """
    Base class for building and installing libvirt storage pool xml
    """

    # @group Types: TYPE_*
    TYPE_DIR     = "dir"
    TYPE_FS      = "fs"
    TYPE_NETFS   = "netfs"
    TYPE_LOGICAL = "logical"
    TYPE_DISK    = "disk"
    TYPE_ISCSI   = "iscsi"
    TYPE_SCSI    = "scsi"
    TYPE_MPATH   = "mpath"

    # Pool type descriptions for use in higher level programs
    _types = {}
    _types[TYPE_DIR]     = _("Filesystem Directory")
    _types[TYPE_FS]      = _("Pre-Formatted Block Device")
    _types[TYPE_NETFS]   = _("Network Exported Directory")
    _types[TYPE_LOGICAL] = _("LVM Volume Group")
    _types[TYPE_DISK]    = _("Physical Disk Device")
    _types[TYPE_ISCSI]   = _("iSCSI Target")
    _types[TYPE_SCSI]    = _("SCSI Host Adapter")
    _types[TYPE_MPATH]   = _("Multipath Device Enumerator")

    def get_pool_class(ptype):
        """
        Return class associated with passed pool type.

        @param ptype: Pool type
        @type ptype: member of I{Types}
        """
        if ptype not in StoragePool._types:
            raise ValueError(_("Unknown storage pool type: %s" % ptype))
        if ptype == StoragePool.TYPE_DIR:
            return DirectoryPool
        if ptype == StoragePool.TYPE_FS:
            return FilesystemPool
        if ptype == StoragePool.TYPE_NETFS:
            return NetworkFilesystemPool
        if ptype == StoragePool.TYPE_LOGICAL:
            return LogicalPool
        if ptype == StoragePool.TYPE_DISK:
            return DiskPool
        if ptype == StoragePool.TYPE_ISCSI:
            return iSCSIPool
        if ptype == StoragePool.TYPE_SCSI:
            return SCSIPool
        if ptype == StoragePool.TYPE_MPATH:
            return MultipathPool
    get_pool_class = staticmethod(get_pool_class)

    def get_volume_for_pool(pool_type):
        """Convenience method, returns volume class associated with pool_type"""
        pool_class = StoragePool.get_pool_class(pool_type)
        return pool_class.get_volume_class()
    get_volume_for_pool = staticmethod(get_volume_for_pool)

    def get_pool_types():
        """Return list of appropriate pool types"""
        return StoragePool._types.keys()
    get_pool_types = staticmethod(get_pool_types)

    def get_pool_type_desc(pool_type):
        """Return human readable description for passed pool type"""
        if pool_type in StoragePool._types:
            return StoragePool._types[pool_type]
        else:
            return "%s pool" % pool_type
    get_pool_type_desc = staticmethod(get_pool_type_desc)

    def pool_list_from_sources(conn, name, pool_type, host=None):
        """
        Return a list of StoragePool instances built from libvirt's pool
        source enumeration (if supported).

        @param conn: Libvirt connection
        @param name: Name for the new pool
        @param pool_type: Pool type string from I{Types}
        @param host: Option host string to poll for sources
        """
        if not conn.check_conn_support(conn.SUPPORT_CONN_FINDPOOLSOURCES):
            return []

        pool_class = StoragePool.get_pool_class(pool_type)
        pool_inst = pool_class(conn=conn, name=name)

        if host:
            source_xml = "<source><host name='%s'/></source>" % host
        else:
            source_xml = "<source/>"

        try:
            xml = conn.findStoragePoolSources(pool_type, source_xml, 0)
        except libvirt.libvirtError, e:
            if util.is_error_nosupport(e):
                return []
            raise

        retlist = []
        source_list = _parse_pool_source_list(xml)
        for source in source_list:
            pool_inst = pool_class(conn=conn, name=name)
            for key, val in source.items():

                if not hasattr(pool_inst, key):
                    continue

                setattr(pool_inst, key, val)

            retlist.append(pool_inst)

        return retlist
    pool_list_from_sources = staticmethod(pool_list_from_sources)

    def __init__(self, conn, name, type, target_path=None, uuid=None):
        # pylint: disable=W0622
        # Redefining built-in 'type', but it matches the XML so keep it

        StorageObject.__init__(self, object_type=StorageObject.TYPE_POOL,
                               name=name, conn=conn)

        if type not in self.get_pool_types():
            raise ValueError(_("Unknown storage pool type: %s" % type))
        self._type = type
        self._target_path = None
        self._host = None
        self._format = None
        self._source_path = None
        self._uuid = None

        if target_path is None:
            target_path = self._get_default_target_path()
        self.target_path = target_path

        if uuid:
            self.uuid = uuid

        # Initialize all optional properties
        self._host = None
        self._source_path = None
        self._random_uuid = util.generate_uuid(self.conn)

    # Properties used by all pools
    def get_type(self):
        return self._type
    type = property(get_type,
                    doc=_("Storage device type the pool will represent."))

    def get_target_path(self):
        return self._target_path
    def set_target_path(self, val):
        self._validate_path(val)
        self._target_path = os.path.abspath(val)

    # Get/Set methods for use by some pools. Will be registered when applicable
    def get_source_path(self):
        return self._source_path
    def set_source_path(self, val):
        self._validate_path(val)
        self._source_path = os.path.abspath(val)

    def get_host(self):
        return self._host
    def set_host(self, val):
        if not isinstance(val, str):
            raise ValueError(_("Host name must be a string"))
        self._host = val

    # uuid: uuid of the storage object. optional: generated if not set
    def get_uuid(self):
        return self._uuid
    def set_uuid(self, val):
        val = util.validate_uuid(val)
        self._uuid = val
    uuid = property(get_uuid, set_uuid)

    # Validation functions
    def _check_name_collision(self, name):
        pool = None
        try:
            pool = self.conn.storagePoolLookupByName(name)
        except libvirt.libvirtError:
            pass
        if pool:
            raise ValueError(_("Name '%s' already in use by another pool." %
                                name))

    def _get_default_target_path(self):
        raise NotImplementedError()

    # XML Building
    def _get_target_xml(self):
        raise NotImplementedError()

    def _get_source_xml(self):
        raise NotImplementedError()

    def _get_storage_xml(self):
        src_xml = ""
        if self._get_source_xml() != "":
            src_xml = "  <source>\n" + \
                      "%s" % (self._get_source_xml()) + \
                      "  </source>\n"
        tar_xml = "  <target>\n" + \
                  "%s" % (self._get_target_xml()) + \
                  "  </target>\n"

        return "  <uuid>%s</uuid>\n" % (self.uuid or self._random_uuid) + \
               "%s" % src_xml + \
               "%s" % tar_xml

    def install(self, meter=None, create=False, build=False, autostart=False):
        """
        Install storage pool xml.
        """
        xml = self.get_xml_config()
        logging.debug("Creating storage pool '%s' with xml:\n%s",
                      self.name, xml)

        if not meter:
            meter = urlgrabber.progress.BaseMeter()

        try:
            pool = self.conn.storagePoolDefineXML(xml, 0)
        except Exception, e:
            raise RuntimeError(_("Could not define storage pool: %s" % str(e)))

        errmsg = None
        if build:
            try:
                pool.build(libvirt.VIR_STORAGE_POOL_BUILD_NEW)
            except Exception, e:
                errmsg = _("Could not build storage pool: %s" % str(e))

        if create and not errmsg:
            try:
                pool.create(0)
            except Exception, e:
                errmsg = _("Could not start storage pool: %s" % str(e))

        if autostart and not errmsg:
            try:
                pool.setAutostart(True)
            except Exception, e:
                errmsg = _("Could not set pool autostart flag: %s" % str(e))

        if errmsg:
            # Try and clean up the leftover pool
            try:
                pool.undefine()
            except Exception, e:
                logging.debug("Error cleaning up pool after failure: " +
                              "%s" % str(e))
            raise RuntimeError(errmsg)

        return pool


class DirectoryPool(StoragePool):
    """
    Create a directory based storage pool
    """

    def get_volume_class():
        return FileVolume
    get_volume_class = staticmethod(get_volume_class)

    # Register applicable property methods from parent class
    perms = property(StorageObject.get_perms, StorageObject.set_perms)
    target_path = property(StoragePool.get_target_path,
                           StoragePool.set_target_path,
                           doc=_("Directory to use for the storage pool."))

    def __init__(self, conn, name, target_path=None, uuid=None, perms=None):
        StoragePool.__init__(self, name=name, type=StoragePool.TYPE_DIR,
                             target_path=target_path, uuid=uuid, conn=conn)
        if perms:
            self.perms = perms

    def _get_default_target_path(self):
        path = (DEFAULT_DIR_TARGET_BASE + self.name)
        return path

    def _get_target_xml(self):
        xml = "    <path>%s</path>\n" % escape(self.target_path) + \
              "%s" % self._get_perms_xml()
        return xml

    def _get_source_xml(self):
        return ""


class FilesystemPool(StoragePool):
    """
    Create a formatted partition based storage pool
    """

    def get_volume_class():
        return FileVolume
    get_volume_class = staticmethod(get_volume_class)

    formats = ["auto", "ext2", "ext3", "ext4", "ufs", "iso9660", "udf",
                "gfs", "gfs2", "vfat", "hfs+", "xfs"]

    # Register applicable property methods from parent class
    perms = property(StorageObject.get_perms, StorageObject.set_perms)
    source_path = property(StoragePool.get_source_path,
                           StoragePool.set_source_path,
                           doc=_("The existing device to mount for the pool."))
    target_path = property(StoragePool.get_target_path,
                           StoragePool.set_target_path,
                           doc=_("Location to mount the source device."))

    def __init__(self, conn, name, source_path=None, target_path=None,
                 format="auto", uuid=None, perms=None):
        # pylint: disable=W0622
        # Redefining built-in 'format', but it matches the XML so keep it

        StoragePool.__init__(self, name=name, type=StoragePool.TYPE_FS,
                             target_path=target_path, uuid=uuid, conn=conn)

        self.format = format

        if source_path:
            self.source_path = source_path
        if perms:
            self.perms = perms

    def get_format(self):
        return self._format
    def set_format(self, val):
        if not val in self.formats:
            raise ValueError(_("Unknown Filesystem format: %s" % val))
        self._format = val
    format = property(get_format, set_format,
                      doc=_("Filesystem type of the source device."))

    def _get_default_target_path(self):
        path = (DEFAULT_DIR_TARGET_BASE + self.name)
        return path

    def _get_target_xml(self):
        xml = "    <path>%s</path>\n" % escape(self.target_path) + \
              "%s" % self._get_perms_xml()
        return xml

    def _get_source_xml(self):
        if not self.source_path:
            raise RuntimeError(_("Device path is required"))
        xml = "    <format type='%s'/>\n" % self.format + \
              "    <device path='%s'/>\n" % escape(self.source_path)
        return xml


class NetworkFilesystemPool(StoragePool):
    """
    Create a network mounted filesystem storage pool
    """

    def get_volume_class():
        return FileVolume
    get_volume_class = staticmethod(get_volume_class)

    formats = ["auto", "nfs", "glusterfs"]

    # Register applicable property methods from parent class
    source_path = property(StoragePool.get_source_path,
                           StoragePool.set_source_path,
                           doc=_("Path on the host that is being shared."))
    host = property(StoragePool.get_host, StoragePool.set_host,
                    doc=_("Name of the host sharing the storage."))
    target_path = property(StoragePool.get_target_path,
                           StoragePool.set_target_path,
                           doc=_("Location to mount the source device."))

    def __init__(self, conn, name, source_path=None, host=None,
                 target_path=None, format="auto", uuid=None):
        # pylint: disable=W0622
        # Redefining built-in 'format', but it matches the XML so keep it

        StoragePool.__init__(self, name=name, type=StoragePool.TYPE_NETFS,
                             uuid=uuid, target_path=target_path, conn=conn)

        self.format = format

        if source_path:
            self.source_path = source_path
        if host:
            self.host = host

    def get_format(self):
        return self._format
    def set_format(self, val):
        if not val in self.formats:
            raise ValueError(_("Unknown Network Filesystem format: %s" % val))
        self._format = val
    format = property(get_format, set_format,
                      doc=_("Type of network filesystem."))

    def _get_default_target_path(self):
        path = (DEFAULT_DIR_TARGET_BASE + self.name)
        return path

    def _get_target_xml(self):
        xml = "    <path>%s</path>\n" % escape(self.target_path)
        return xml

    def _get_source_xml(self):
        if not self.host:
            raise RuntimeError(_("Hostname is required"))
        if not self.source_path:
            raise RuntimeError(_("Host path is required"))
        xml = """    <format type="%s"/>\n""" % self.format + \
              """    <host name="%s"/>\n""" % self.host + \
              """    <dir path="%s"/>\n""" % escape(self.source_path)
        return xml


class LogicalPool(StoragePool):
    """
    Create a logical (lvm volume group) storage pool
    """
    def get_volume_class():
        return LogicalVolume
    get_volume_class = staticmethod(get_volume_class)

    # Register applicable property methods from parent class
    perms = property(StorageObject.get_perms, StorageObject.set_perms)
    target_path = property(StoragePool.get_target_path,
                           StoragePool.set_target_path,
                           doc=_("Location of the existing LVM volume group."))

    def __init__(self, conn, name, target_path=None, uuid=None, perms=None,
                 source_path=None, source_name=None):
        StoragePool.__init__(self, name=name, type=StoragePool.TYPE_LOGICAL,
                             target_path=target_path, uuid=uuid, conn=conn)

        self._source_name = None

        if perms:
            self.perms = perms
        if source_path:
            self.source_path = source_path
        if source_name:
            self.source_name = source_name

    # Need to overwrite storage path checks, since this optionally be a list
    # of devices
    def get_source_path(self):
        return self._source_path
    def set_source_path(self, val):
        if not val:
            self._source_path = None
            return

        if type(val) != list:
            StoragePool.set_source_path(self, val)
        else:
            self._source_path = val
    source_path = property(get_source_path, set_source_path,
                           doc=_("Optional device(s) to build new LVM volume "
                                 "on."))

    def get_source_name(self):
        if self._source_name:
            return self._source_name

        # If a source name isn't explictly set, try to determine it from
        # existing parameters
        srcname = self.name

        if (self.target_path and
            self.target_path.startswith(DEFAULT_LVM_TARGET_BASE)):
            # If there is a target path, parse it for an expected VG
            # location, and pull the name from there
            vg = self.target_path[len(DEFAULT_LVM_TARGET_BASE):]
            srcname = vg.split("/", 1)[0]

        return srcname

    def set_source_name(self, val):
        self._source_name = val
    source_name = property(get_source_name, set_source_name,
                           doc=_("Name of the Volume Group"))

    def _make_source_name(self):
        srcname = self.name

        if self.source_path:
            # Building a pool, so just use pool name
            return srcname

    def _get_default_target_path(self):
        return DEFAULT_LVM_TARGET_BASE + self.name

    def _get_target_xml(self):
        xml = "    <path>%s</path>\n" % escape(self.target_path) + \
              "%s" % self._get_perms_xml()
        return xml

    def _get_source_xml(self):
        sources = self.source_path
        if type(sources) != list:
            sources = sources and [sources] or []

        xml = ""
        for s in sources:
            xml += "    <device path='%s'/>\n" % s
        if self.source_name:
            xml += "    <name>%s</name>\n" % self.source_name
        return xml

    def install(self, meter=None, create=False, build=False, autostart=False):
        if build and not self.source_path:
            raise ValueError(_("Must explicitly specify source path if "
                               "building pool"))
        return StoragePool.install(self, meter=meter, create=create,
                                   build=build, autostart=autostart)


class DiskPool(StoragePool):
    """
    Create a storage pool from a physical disk
    """
    def get_volume_class():
        return DiskVolume
    get_volume_class = staticmethod(get_volume_class)

    # Register applicable property methods from parent class
    source_path = property(StoragePool.get_source_path,
                           StoragePool.set_source_path,
                           doc=_("Path to the existing disk device."))
    target_path = property(StoragePool.get_target_path,
                           StoragePool.set_target_path,
                           doc=_("Root location for identifying new storage"
                                 " volumes."))

    formats = ["auto", "bsd", "dos", "dvh", "gpt", "mac", "pc98", "sun"]

    def __init__(self, conn, name, source_path=None, target_path=None,
                 format="auto", uuid=None):
        # pylint: disable=W0622
        # Redefining built-in 'format', but it matches the XML so keep it

        StoragePool.__init__(self, name=name, type=StoragePool.TYPE_DISK,
                             uuid=uuid, target_path=target_path, conn=conn)
        self.format = format
        if source_path:
            self.source_path = source_path

    def get_format(self):
        return self._format
    def set_format(self, val):
        if not val in self.formats:
            raise ValueError(_("Unknown Disk format: %s" % val))
        self._format = val
    format = property(get_format, set_format,
                      doc=_("Format of the source device's partition table."))

    def _get_default_target_path(self):
        return DEFAULT_DEV_TARGET

    def _get_target_xml(self):
        xml = "   <path>%s</path>\n" % escape(self.target_path)
        return xml

    def _get_source_xml(self):
        if not self.source_path:
            raise RuntimeError(_("Host path is required"))

        xml = ""
        # There is no explicit "auto" type for disk pools, but leaving out
        # the format type seems to do the job for existing formatted disks
        if self.format != "auto":
            xml = """    <format type="%s"/>\n""" % self.format
        xml += """    <device path="%s"/>\n""" % escape(self.source_path)
        return xml

    def install(self, meter=None, create=False, build=False, autostart=False):
        if self.format == "auto" and build:
            raise ValueError(_("Must explicitly specify disk format if "
                               "formatting disk device."))
        return StoragePool.install(self, meter=meter, create=create,
                                   build=build, autostart=autostart)


class iSCSIPool(StoragePool):
    """
    Create an iSCSI based storage pool
    """

    host = property(StoragePool.get_host, StoragePool.set_host,
                    doc=_("Name of the host sharing the storage."))
    target_path = property(StoragePool.get_target_path,
                           StoragePool.set_target_path,
                           doc=_("Root location for identifying new storage"
                                 " volumes."))

    def get_volume_class():
        raise NotImplementedError(_("iSCSI volume creation is not supported."))
    get_volume_class = staticmethod(get_volume_class)

    def __init__(self, conn, name, source_path=None, host=None,
                 target_path=None, uuid=None):
        StoragePool.__init__(self, name=name, type=StoragePool.TYPE_ISCSI,
                             uuid=uuid, target_path=target_path, conn=conn)

        if source_path:
            self.source_path = source_path
        if host:
            self.host = host

        self._iqn = None

    # Need to overwrite pool *_source_path since iscsi device isn't
    # a fully qualified path
    def get_source_path(self):
        return self._source_path
    def set_source_path(self, val):
        self._source_path = val
    source_path = property(get_source_path, set_source_path,
                           doc=_("Path on the host that is being shared."))

    def _get_iqn(self):
        return self._iqn
    def _set_iqn(self, val):
        self._iqn = val
    iqn = property(_get_iqn, _set_iqn,
                        doc=_("iSCSI initiator qualified name"))

    def _get_default_target_path(self):
        return DEFAULT_SCSI_TARGET

    def _get_target_xml(self):
        xml = "    <path>%s</path>\n" % escape(self.target_path)
        return xml

    def _get_source_xml(self):
        if not self.host:
            raise RuntimeError(_("Hostname is required"))
        if not self.source_path:
            raise RuntimeError(_("Host path is required"))

        iqn_xml = ""
        if self.iqn:
            iqn_xml += """    <initiator>\n"""
            iqn_xml += """      <iqn name="%s"/>\n""" % escape(self.iqn)
            iqn_xml += """    </initiator>\n"""

        xml  = """    <host name="%s"/>\n""" % self.host
        xml += """    <device path="%s"/>\n""" % escape(self.source_path)
        xml += iqn_xml

        return xml


class SCSIPool(StoragePool):
    """
    Create a SCSI based storage pool
    """

    target_path = property(StoragePool.get_target_path,
                           StoragePool.set_target_path,
                           doc=_("Root location for identifying new storage"
                                 " volumes."))

    def get_volume_class():
        raise NotImplementedError(_("SCSI volume creation is not supported."))
    get_volume_class = staticmethod(get_volume_class)

    def __init__(self, conn, name, source_path=None,
                 target_path=None, uuid=None):
        StoragePool.__init__(self, name=name, type=StoragePool.TYPE_SCSI,
                             uuid=uuid, target_path=target_path, conn=conn)

        if source_path:
            self.source_path = source_path

    # Need to overwrite pool *_source_path since iscsi device isn't
    # a fully qualified path
    def get_source_path(self):
        return self._source_path
    def set_source_path(self, val):
        self._source_path = val
    source_path = property(get_source_path, set_source_path,
                           doc=_("Name of the scsi adapter (ex. host2)"))

    def _get_default_target_path(self):
        return DEFAULT_SCSI_TARGET

    def _get_target_xml(self):
        xml = "    <path>%s</path>\n" % escape(self.target_path)
        return xml

    def _get_source_xml(self):
        if not self.source_path:
            raise RuntimeError(_("Adapter name is required"))
        xml = """    <adapter name="%s"/>\n""" % escape(self.source_path)
        return xml


class MultipathPool(StoragePool):
    """
    Create a Multipath based storage pool
    """

    target_path = property(StoragePool.get_target_path,
                           StoragePool.set_target_path,
                           doc=_("Root location for identifying new storage"
                                 " volumes."))

    def get_volume_class():
        raise NotImplementedError(_("Multipath volume creation is not "
                                    "supported."))
    get_volume_class = staticmethod(get_volume_class)

    def __init__(self, conn, name, target_path=None, uuid=None):
        StoragePool.__init__(self, name=name, type=StoragePool.TYPE_MPATH,
                             uuid=uuid, target_path=target_path, conn=conn)

    def _get_default_target_path(self):
        return DEFAULT_MPATH_TARGET

    def _get_target_xml(self):
        xml = "    <path>%s</path>\n" % escape(self.target_path)
        return xml

    def _get_source_xml(self):
        return ""


##########################
# Storage Volume classes #
##########################

class StorageVolume(StorageObject):
    """
    Base class for building and installing libvirt storage volume xml
    """

    formats = []

    # File vs. Block for the Volume class
    _file_type = None

    def __init__(self, conn, name, capacity, pool_name=None, pool=None,
                 allocation=0):
        """
        @param name: Name for the new storage volume
        @param capacity: Total size of the new volume (in bytes)
        @param conn: optional connection instance to lookup pool_name on
        @param pool_name: optional pool_name to install on
        @param pool: virStoragePool object to install on
        @param allocation: amount of storage to actually allocate (default 0)
        """
        if pool is None:
            if pool_name is None:
                raise ValueError(_("One of pool or pool_name must be "
                                   "specified."))
            pool = StorageVolume.lookup_pool_by_name(pool_name=pool_name,
                                                     conn=conn)
        self._pool = None
        self.pool = pool

        StorageObject.__init__(self, conn,
                               object_type=StorageObject.TYPE_VOLUME,
                               name=name)
        self._allocation = None
        self._capacity = None
        self._format = None
        self._input_vol = None

        self.allocation = allocation
        self.capacity = capacity

        # Indicate that the volume installation has finished. Used to
        # definitively tell the storage progress thread to stop polling.
        self._install_finished = True

    def get_volume_for_pool(pool_object=None, pool_name=None, conn=None):
        """
        Returns volume class associated with passed pool_object/name
        """
        pool_object = StorageVolume.lookup_pool_by_name(pool_object=pool_object,
                                                        pool_name=pool_name,
                                                        conn=conn)
        return StoragePool.get_volume_for_pool(util.xpath(
            pool_object.XMLDesc(0), "/pool/@type"))
    get_volume_for_pool = staticmethod(get_volume_for_pool)

    def find_free_name(name, pool_object=None, pool_name=None, conn=None,
                       suffix="", collidelist=None, start_num=0):
        """
        Finds a name similar (or equal) to passed 'name' that is not in use
        by another pool

        This function scans the list of existing Volumes on the passed or
        looked up pool object for a collision with the passed name. If the
        name is in use, it append "-1" to the name and tries again, then "-2",
        continuing to 100000 (which will hopefully never be reached.") If
        suffix is specified, attach it to the (potentially incremented) name
        before checking for collision.

        Ex name="test", suffix=".img" -> name-3.img

        @param collidelist: An extra list of names to check for collision
        @type collidelist: C{list}
        @returns: A free name
        @rtype: C{str}
        """
        collidelist = collidelist or []
        pool_object = StorageVolume.lookup_pool_by_name(
                                                    pool_object=pool_object,
                                                    pool_name=pool_name,
                                                    conn=conn)
        pool_object.refresh(0)

        return util.generate_name(name, pool_object.storageVolLookupByName,
                                   suffix, collidelist=collidelist,
                                   start_num=start_num)
    find_free_name = staticmethod(find_free_name)

    def lookup_pool_by_name(pool_object=None, pool_name=None, conn=None):
        """
        Returns pool object determined from passed parameters.

        Largely a convenience function for the other static functions.
        """
        if pool_object is None and pool_name is None:
            raise ValueError(_("Must specify pool_object or pool_name"))

        if pool_name is not None and pool_object is None:
            if conn is None:
                raise ValueError(_("'conn' must be specified with 'pool_name'"))
            if not conn.check_conn_support(conn.SUPPORT_CONN_STORAGE):
                raise ValueError(_("Connection does not support storage "
                                   "management."))
            try:
                pool_object = conn.storagePoolLookupByName(pool_name)
            except Exception, e:
                raise ValueError(_("Couldn't find storage pool '%s': %s" %
                                   (pool_name, str(e))))

        if not isinstance(pool_object, libvirt.virStoragePool):
            raise ValueError(_("pool_object must be a virStoragePool"))

        return pool_object
    lookup_pool_by_name = staticmethod(lookup_pool_by_name)

    # Properties used by all volumes
    def get_file_type(self):
        return self._file_type
    file_type = property(get_file_type)

    def get_capacity(self):
        return self._capacity
    def set_capacity(self, val):
        if type(val) not in (int, float, long) or val < 0:
            raise ValueError(_("Capacity must be a positive number"))
        newcap = int(val)
        origcap = self.capacity
        origall = self.allocation
        self._capacity = newcap
        if self.allocation is not None and (newcap < self.allocation):
            self._allocation = newcap

        ret = self.is_size_conflict()
        if ret[0]:
            self._capacity = origcap
            self._allocation = origall
            raise ValueError(ret[1])
        elif ret[1]:
            logging.warn(ret[1])
    capacity = property(get_capacity, set_capacity)

    def get_allocation(self):
        return self._allocation
    def set_allocation(self, val):
        if type(val) not in (int, float, long) or val < 0:
            raise ValueError(_("Allocation must be a non-negative number"))
        newall = int(val)
        if self.capacity is not None and newall > self.capacity:
            logging.debug("Capping allocation at capacity.")
            newall = self.capacity
        origall = self._allocation
        self._allocation = newall

        ret = self.is_size_conflict()
        if ret[0]:
            self._allocation = origall
            raise ValueError(ret[1])
        elif ret[1]:
            logging.warn(ret[1])
    allocation = property(get_allocation, set_allocation)

    def get_pool(self):
        return self._pool
    def set_pool(self, newpool):
        if not isinstance(newpool, libvirt.virStoragePool):
            raise ValueError(_("'pool' must be a virStoragePool instance."))
        if newpool.info()[0] != libvirt.VIR_STORAGE_POOL_RUNNING:
            raise ValueError(_("pool '%s' must be active." % newpool.name()))
        self._pool = newpool
    pool = property(get_pool, set_pool)

    def get_input_vol(self):
        return self._input_vol
    def set_input_vol(self, vol):
        if vol is None:
            self._input_vol = None
            return

        if not isinstance(vol, libvirt.virStorageVol):
            raise ValueError(_("input_vol must be a virStorageVol"))

        if not self.conn.check_pool_support(self.conn,
                    self.conn.SUPPORT_STORAGE_CREATEVOLFROM):
            raise ValueError(_("Creating storage from an existing volume is"
                               " not supported by this libvirt version."))
        self._input_vol = vol
    input_vol = property(get_input_vol, set_input_vol,
                         doc=_("virStorageVolume pointer to clone/use as "
                               "input."))

    # Property functions used by more than one child class
    def get_format(self):
        return self._format
    def set_format(self, val):
        if val not in self.formats:
            raise ValueError(_("'%s' is not a valid format.") % val)
        self._format = val

    def _check_name_collision(self, name):
        vol = None
        try:
            vol = self.pool.storageVolLookupByName(name)
        except libvirt.libvirtError:
            pass
        if vol:
            raise ValueError(_("Name '%s' already in use by another volume." %
                                name))

    def _check_target_collision(self, path):
        col = None
        try:
            col = self.conn.storageVolLookupByPath(path)
        except libvirt.libvirtError:
            pass
        if col:
            return True
        return False

    # xml building functions
    def _get_target_xml(self):
        raise NotImplementedError()

    def _get_source_xml(self):
        raise NotImplementedError()

    def _get_storage_xml(self):
        src_xml = ""
        if self._get_source_xml() != "":
            src_xml = "  <source>\n" + \
                      "%s" % (self._get_source_xml()) + \
                      "  </source>\n"
        tar_xml = "  <target>\n" + \
                  "%s" % (self._get_target_xml()) + \
                  "  </target>\n"
        return "  <capacity>%d</capacity>\n" % self.capacity + \
               "  <allocation>%d</allocation>\n" % self.allocation + \
               "%s" % src_xml + \
               "%s" % tar_xml

    def install(self, meter=None):
        """
        Build and install storage volume from xml
        """
        xml = self.get_xml_config()
        logging.debug("Creating storage volume '%s' with xml:\n%s",
                      self.name, xml)

        t = threading.Thread(target=self._progress_thread,
                             name="Checking storage allocation",
                             args=(meter,))
        t.setDaemon(True)

        if not meter:
            meter = urlgrabber.progress.BaseMeter()

        try:
            self._install_finished = False
            t.start()
            meter.start(size=self.capacity,
                        text=_("Allocating '%s'") % self.name)

            if self.input_vol:
                vol = self.pool.createXMLFrom(xml, self.input_vol, 0)
            else:
                vol = self.pool.createXML(xml, 0)

            self._install_finished = True
            t.join()
            meter.end(self.capacity)
            logging.debug("Storage volume '%s' install complete.",
                          self.name)
            return vol
        except libvirt.libvirtError, e:
            if util.is_error_nosupport(e):
                raise RuntimeError("Libvirt version does not support "
                                   "storage cloning.")
            raise
        except Exception, e:
            raise RuntimeError("Couldn't create storage volume "
                               "'%s': '%s'" % (self.name, str(e)))

    def _progress_thread(self, meter):
        lookup_attempts = 10
        vol = None

        if not meter:
            return

        while lookup_attempts > 0:
            try:
                vol = self.pool.storageVolLookupByName(self.name)
                break
            except:
                lookup_attempts -= 1
                time.sleep(.2)
                if self._install_finished:
                    break
                else:
                    continue
            break

        if vol is None:
            logging.debug("Couldn't lookup storage volume in prog thread.")
            return

        while not self._install_finished:
            ignore, ignore, alloc = vol.info()
            meter.update(alloc)
            time.sleep(1)


    def is_size_conflict(self):
        """
        Report if requested size exceeds its pool's available amount

        @returns: 2 element tuple:
            1. True if collision is fatal, false otherwise
            2. String message if some collision was encountered.
        @rtype: 2 element C{tuple}: (C{bool}, C{str})
        """
        # pool info is [pool state, capacity, allocation, available]
        avail = self.pool.info()[3]
        if self.allocation > avail:
            return (True, _("There is not enough free space on the storage "
                            "pool to create the volume. "
                            "(%d M requested allocation > %d M available)" %
                            ((self.allocation / (1024 * 1024)),
                             (avail / (1024 * 1024)))))
        elif self.capacity > avail:
            return (False, _("The requested volume capacity will exceed the "
                             "available pool space when the volume is fully "
                             "allocated. "
                             "(%d M requested capacity > %d M available)" %
                             ((self.capacity / (1024 * 1024)),
                              (avail / (1024 * 1024)))))
        return (False, "")


class FileVolume(StorageVolume):
    """
    Build and install xml for use on pools which use file based storage
    """
    _file_type = VIR_STORAGE_VOL_FILE

    formats = ["raw", "bochs", "cloop", "cow", "dmg", "iso", "qcow",
               "qcow2", "qed", "vmdk", "vpc"]
    create_formats = ["raw", "cow", "qcow", "qcow2", "qed", "vmdk", "vpc"]

    # Register applicable property methods from parent class
    perms = property(StorageObject.get_perms, StorageObject.set_perms)
    format = property(StorageVolume.get_format, StorageVolume.set_format)

    def __init__(self, conn, name, capacity,
                 pool=None, pool_name=None,
                 format="raw", allocation=None, perms=None):
        # pylint: disable=W0622
        # Redefining built-in 'format', but it matches the XML so keep it

        StorageVolume.__init__(self, conn, name=name,
                               pool=pool, pool_name=pool_name,
                               allocation=allocation, capacity=capacity)
        self.format = format
        if perms:
            self.perms = perms

    def _get_target_xml(self):
        return "    <format type='%s'/>\n" % self.format + \
               "%s" % self._get_perms_xml()

    def _get_source_xml(self):
        return ""


class DiskVolume(StorageVolume):
    """
    Build and install xml volumes for use on physical disk pools
    """
    _file_type = VIR_STORAGE_VOL_BLOCK

    # Register applicable property methods from parent class
    perms = property(StorageObject.get_perms, StorageObject.set_perms)

    def __init__(self, conn, name, capacity,
                  pool=None, pool_name=None,
                 allocation=None, perms=None):
        StorageVolume.__init__(self, conn, name=name,
                               pool=pool, pool_name=pool_name,
                               allocation=allocation, capacity=capacity)
        if perms:
            self.perms = perms

    def _get_target_xml(self):
        return "%s" % self._get_perms_xml()

    def _get_source_xml(self):
        return ""


class LogicalVolume(StorageVolume):
    """
    Build and install logical volumes for lvm pools
    """
    _file_type = VIR_STORAGE_VOL_BLOCK

    # Register applicable property methods from parent class
    perms = property(StorageObject.get_perms, StorageObject.set_perms)

    def __init__(self, conn,
                 name, capacity, pool=None, pool_name=None,
                 allocation=None, perms=None):
        if allocation and allocation != capacity:
            logging.warn(_("Sparse logical volumes are not supported, "
                           "setting allocation equal to capacity"))
        StorageVolume.__init__(self, conn, name=name,
                               pool=pool, pool_name=pool_name,
                               allocation=capacity, capacity=capacity)
        if perms:
            self.perms = perms

    def set_capacity(self, capacity):
        super(LogicalVolume, self).set_capacity(capacity)
        self.allocation = capacity
    capacity = property(StorageVolume.get_capacity, set_capacity)

    def set_allocation(self, allocation):
        if allocation != self.capacity:
            logging.warn(_("Sparse logical volumes are not supported, "
                           "setting allocation equal to capacity"))
        super(LogicalVolume, self).set_allocation(self.capacity)
    capacity = property(StorageVolume.get_allocation, set_allocation)


    def _get_target_xml(self):
        return "%s" % self._get_perms_xml()

    def _get_source_xml(self):
        return ""


class CloneVolume(StorageVolume):
    """
    Build and install a volume that is a clone of an existing volume
    """

    format = property(StorageVolume.get_format, StorageVolume.set_format)

    def __init__(self, conn, name, input_vol):
        if not isinstance(input_vol, libvirt.virStorageVol):
            raise ValueError(_("input_vol must be a virStorageVol"))

        pool = input_vol.storagePoolLookupByVolume()

        # Populate some basic info
        xml  = input_vol.XMLDesc(0)
        typ  = input_vol.info()[0]
        cap  = int(util.xpath(xml, "/volume/capacity"))
        alc  = int(util.xpath(xml, "/volume/allocation"))
        fmt  = util.xpath(xml, "/volume/target/format/@type")

        StorageVolume.__init__(self, conn, name=name, pool=pool,
                               pool_name=pool.name(),
                               allocation=alc, capacity=cap)

        self.input_vol = input_vol
        self._file_type = typ
        self._format = fmt

    def _get_target_xml(self):
        return ""
    def _get_source_xml(self):
        return ""

    def get_xml_config(self):
        xml  = self.input_vol.XMLDesc(0)
        newxml = util.set_xml_path(xml, "/volume/name", self.name)
        return newxml

# class iSCSIVolume(StorageVolume):
#    """
#    Build and install xml for use on iSCSI device pools
#    """
#    _file_type = VIR_STORAGE_VOL_BLOCK
#
#    def __init__(self, *args, **kwargs):
#        raise NotImplementedError