summaryrefslogtreecommitdiffstats
path: root/lvm.py
blob: 165c5c459265afa26f9de558919e31112002d495 (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
# lvm.py - lvm probing control
#
# Jeremy Katz <katzj@redhat.com>
#
# Copyright 2002 Red Hat, Inc.
#
# This software may be freely redistributed under the terms of the GNU
# general public license.
#
# 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., 675 Mass Ave, Cambridge, MA 02139, USA.

import iutil
import os,sys
import string
import math
import isys

from flags import flags

import logging
log = logging.getLogger("anaconda")

from constants import *

MAX_LV_SLOTS=256

output = "/tmp/lvmout"

lvmDevicePresent = 0

def has_lvm():
    global lvmDevicePresent

    if not (os.access("/usr/sbin/lvm", os.X_OK) or
            os.access("/sbin/lvm", os.X_OK)):
        return

    f = open("/proc/devices", "r")
    lines = f.readlines()
    f.close()

    for line in lines:
        try:
            (dev, name) = line[:-1].split(' ', 2)
        except:
            continue
        if name == "device-mapper":
            lvmDevicePresent = 1
            break
    return lvmDevicePresent
# now check to see if lvm is available
has_lvm()
        

def vgscan():
    """Runs vgscan."""
    global lvmDevicePresent
        
    if flags.test or lvmDevicePresent == 0:
        return

    rc = iutil.execWithRedirect("lvm",
                                ["lvm", "vgscan", "-v"],
                                stdout = output,
                                stderr = output,
                                searchPath = 1)
    if rc:
        log.error("running vgscan failed: %s" %(rc,))
#        lvmDevicePresent = 0

def vgactivate(volgroup = None):
    """Activate volume groups by running vgchange -ay.

    volgroup - optional single volume group to activate
    """
    global lvmDevicePresent
    if flags.test or lvmDevicePresent == 0:
        return

    args = ["lvm", "vgchange", "-ay"]
    if volgroup:
        args.append(volgroup)
    rc = iutil.execWithRedirect(args[0], args,
                                stdout = output,
                                stderr = output,
                                searchPath = 1)
    if rc:
        log.error("running vgchange failed: %s" %(rc,))
#        lvmDevicePresent = 0

    # now make the device nodes
    args = ["lvm", "vgmknodes"]
    if volgroup:
        args.append(volgroup)
    rc = iutil.execWithRedirect(args[0], args,
                                stdout = output,
                                stderr = output,
                                searchPath = 1)
    if rc:
        log.error("running vgmknodes failed: %s" %(rc,))
#        lvmDevicePresent = 0

def vgdeactivate(volgroup = None):
    """Deactivate volume groups by running vgchange -an.

    volgroup - optional single volume group to deactivate
    """
    global lvmDevicePresent
    if flags.test or lvmDevicePresent == 0:
        return

    args = ["lvm", "vgchange", "-an"]
    if volgroup:
        args.append(volgroup)
    rc = iutil.execWithRedirect(args[0], args,
                                stdout = output,
                                stderr = output,
                                searchPath = 1)
    if rc:
        log.error("running vgchange failed: %s" %(rc,))
#        lvmDevicePresent = 0
    
    
def lvremove(lvname, vgname):
    """Removes a logical volume.

    lvname - name of logical volume to remove.
    vgname - name of volume group lv is in.
    """
    global lvmDevicePresent
    if flags.test or lvmDevicePresent == 0:
        return

    args = ["lvm", "lvremove", "-f"]
    dev = "/dev/%s/%s" %(vgname, lvname)
    args.append(dev)

    rc = iutil.execWithRedirect(args[0], args,
                                stdout = output,
                                stderr = output,
                                searchPath = 1)
    if rc:
        raise SystemError, "lvremove failed"


def vgremove(vgname):
    """Removes a volume group.  Deactivates the volume group first

    vgname - name of volume group.
    """
    global lvmDevicePresent
    if flags.test or lvmDevicePresent == 0:
        return

    # find the Physical Volumes which make up this Volume Group, so we
    # can prune and recreate them.
    pvs = []
    for pv in pvlist():
        if pv[1] == vgname:
            pvs.append(pv[0])

    # we'll try to deactivate... if it fails, we'll probably fail on
    # the removal too... but it's worth a shot
    try:
        vgdeactivate(vgname)
    except:
        pass

    args = ["lvm", "vgremove", vgname]

    log.info(string.join(args, ' '))
    rc = iutil.execWithRedirect(args[0], args,
                                stdout = output,
                                stderr = output,
                                searchPath = 1)
    if rc:
        raise SystemError, "vgremove failed"

    # now iterate all the PVs we've just freed up, so we reclaim the metadata
    # space.  This is an LVM bug, AFAICS.
    for pvname in pvs:
        args = ["lvm", "pvremove", "-ff", pvname]

        log.info(string.join(args, ' '))
        rc = iutil.execWithRedirect(args[0], args,
                                    stdout = output,
                                    stderr = output,
                                    searchPath = 1)

        if rc:
            raise SystemError, "pvremove failed"

        args = ["lvm", "pvcreate", "-ff", "-y", "-v", pvname]

        log.info(string.join(args, ' '))
        rc = iutil.execWithRedirect(args[0], args,
                                    stdout = output,
                                    stderr = output,
                                    searchPath = 1)

        if rc:
            raise SystemError, "pvcreate failed for %s" % (pvname,)

def lvlist():
    global lvmDevicePresent
    if lvmDevicePresent == 0:
        return []

    lvs = []
    # field names for "options" are in LVM2.2.01.01/lib/report/columns.h
    args = ["lvm", "lvdisplay", "-C", "--noheadings", "--units", "b",
            "--nosuffix", "--separator", ":", "--options",
            "vg_name,lv_name,lv_size,origin"
           ]
    lvscanout = iutil.execWithCapture(args[0], args, searchPath = 1,
                                      stderr = "/dev/tty6")
    for line in lvscanout.split("\n"):
        try:
            (vg, lv, size, origin) = line.strip().split(':')
            size = long(math.floor(long(size) / (1024 * 1024)))
            if origin == '':
                origin = None
        except:
            continue

        logmsg = "lv is %s/%s, size of %s" % (vg, lv, size)
        if origin:
            logmsg += ", snapshot from %s" % (origin,)
        log.info(logmsg)
        lvs.append( (vg, lv, size, origin) )

    return lvs

def pvlist():
    global lvmDevicePresent
    if lvmDevicePresent == 0:
        return []

    pvs = []
    args = ["lvm", "pvdisplay", "-C", "--noheadings", "--units", "b",
            "--nosuffix", "--separator", ":", "--options",
            "pv_name,vg_name,dev_size"
           ]
    scanout = iutil.execWithCapture(args[0], args, searchPath = 1,
                                    stderr = "/dev/tty6")
    for line in scanout.split("\n"):
        try:
            (dev, vg, size) = line.strip().split(':')
            size = long(math.floor(long(size) / (1024 * 1024)))
        except:
            continue
        log.info("pv is %s in vg %s, size is %s" %(dev, vg, size))
        pvs.append( (dev, vg, size) )

    return pvs
    
def vglist():
    global lvmDevicePresent
    if lvmDevicePresent == 0:
        return []

    vgs = []
    args = ["lvm", "vgdisplay", "-C", "--noheadings", "--units", "b",
            "--nosuffix", "--separator", ":", "--options",
            "vg_name,vg_size,vg_extent_size"
           ]
    scanout = iutil.execWithCapture(args[0], args, searchPath = 1,
                                    stderr = "/dev/tty6")
    for line in scanout.split("\n"):
        try:
            (vg, size, pesize) = line.strip().split(':')
            size = long(math.floor(long(size) / (1024 * 1024)))
            pesize = long(pesize)/1024
        except:
            continue
        log.info("vg %s, size is %s, pesize is %s" %(vg, size, pesize))
        vgs.append( (vg, size, pesize) )

    return vgs

def partialvgs():
    global lvmDevicePresent
    if lvmDevicePresent == 0:
        return []
    
    vgs = []
    args = ["lvm", "vgdisplay", "-C", "-P", "--noheadings", "--units", "b"]
    scanout = iutil.execWithCapture(args[0], args, searchPath = 1,
                                    stderr = "/dev/tty6")
    for line in scanout.split("\n"):
        try:
            (vg, numpv, numlv, numsn, attr, size, free) = line.strip()[:-1].split()
        except:
            continue
        if attr.find("p") != -1:
            log.info("vg %s, attr is %s" %(vg, attr))
            vgs.append(vg)

    return vgs

# FIXME: this is a hack.  we really need to have a --force option.
def unlinkConf():
    lvmroot = "/etc/lvm"
    if os.path.exists("%s/lvm.conf" %(lvmroot,)):
        os.unlink("%s/lvm.conf" %(lvmroot,))

def writeForceConf():
    """Write out an /etc/lvm/lvm.conf that doesn't do much (any?) filtering"""

    lvmroot = "/etc/lvm"
    try:
        os.unlink("/etc/lvm/.cache")
    except:
        pass
    if not os.path.isdir(lvmroot):
        os.mkdir(lvmroot)

    unlinkConf()

    f = open("%s/lvm.conf" %(lvmroot,), "w+")
    f.write("""
# anaconda hacked lvm.conf to avoid filtering breaking things
devices {
  sysfs_scan = 0
  md_component_detection = 1
}
""")

# FIXME: another hack.  we need to wipe the raid metadata since pvcreate
# doesn't
def wipeOtherMetadataFromPV(node):
    try:
        isys.wipeRaidSB(node)
    except Exception, e:
        log.critical("error wiping raidsb from %s: %s", node, e)
        
    

def getPossiblePhysicalExtents(floor=0):
    """Returns a list of integers representing the possible values for
       the physical extent of a volume group.  Value is in KB.

       floor - size (in KB) of smallest PE we care about.
    """

    possiblePE = []
    curpe = 8
    while curpe <= 16384*1024:
	if curpe >= floor:
	    possiblePE.append(curpe)
	curpe = curpe * 2

    return possiblePE

def clampLVSizeRequest(size, pe, roundup=0):
    """Given a size and a PE, returns the actual size of logical volumne.

    size - size (in MB) of logical volume request
    pe   - PE size (in KB)
    roundup - round sizes up or not
    """

    if roundup:
        func = math.ceil
    else:
        func = math.floor
    return (long(func((size*1024L)/pe))*pe)/1024

def clampPVSize(pvsize, pesize):
    """Given a PV size and a PE, returns the usable space of the PV.
    Takes into account both overhead of the physical volume and 'clamping'
    to the PE size.

    pvsize - size (in MB) of PV request
    pesize - PE size (in KB)
    """

    # we want Kbytes as a float for our math
    pvsize *= 1024.0
    return long((math.floor(pvsize / pesize) * pesize) / 1024)

def getMaxLVSize(pe):
    """Given a PE size in KB, returns maximum size (in MB) of a logical volume.

    pe - PE size in KB
    """
    return pe*64

def createSuggestedVGName(partitions):
    """Given list of partition requests, come up with a reasonable VG name

    partitions - list of requests
    """
    i = 0
    while 1:
	tmpname = "VolGroup%02d" % (i,)
	if not partitions.isVolumeGroupNameInUse(tmpname):
	    break

	i = i + 1
	if i>99:
	    tmpname = ""

    return tmpname
	    
def createSuggestedLVName(logreqs):
    """Given list of LV requests, come up with a reasonable LV name

    partitions - list of LV requests for this VG
    """
    i = 0

    lnames = []
    for lv in logreqs:
	lnames.append(lv.logicalVolumeName)
    
    while 1:
	tmpname = "LogVol%02d" % (i,)
	if (logreqs is None) or (tmpname not in lnames):
	    break

	i = i + 1
	if i>99:
	    tmpname = ""

    return tmpname
	    
def getVGUsedSpace(vgreq, requests, diskset):
    vgused = 0
    for request in requests.requests:
	if request.type == REQUEST_LV and request.volumeGroup == vgreq.uniqueID:
	    size = int(request.getActualSize(requests, diskset))
	    vgused = vgused + size


    return vgused

def getVGFreeSpace(vgreq, requests, diskset):
    used = getVGUsedSpace(vgreq, requests, diskset)
    log.debug("used space is %s" % (used,))
    
    total = vgreq.getActualSize(requests, diskset)
    log.debug("actual space is %s" % (total,))
    return total - used