summaryrefslogtreecommitdiffstats
path: root/lvm.py
blob: 02422c21c9d16ca170d127e4f2fe8aba8367b6a3 (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
# 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

from flags import flags
from rhpl.log import log

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("running vgscan failed: %s.  disabling lvm" %(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("running vgchange failed: %s.  disabling lvm" %(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("running vgmknodes failed: %s.  disabling lvm" %(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("running vgchange failed: %s.  disabling lvm" %(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

    # 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]

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

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

    lvs = []
    args = ["lvm", "lvdisplay", "-C", "--noheadings", "--units", "b"]
    lvscanout = iutil.execWithCapture(args[0], args, searchPath = 1)
    for line in lvscanout.split("\n"):
        try:
            (lv, vg, attr, size) = line.strip()[:-1].split()
        except:
            continue
        size = size[:-1]
        log("lv is %s/%s, size of %s" %(vg, lv, size))
        lvs.append( (vg, lv, size) )

    return lvs

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

    pvs = []
    args = ["lvm", "pvdisplay", "-C", "--noheadings", "--units", "b"]
    scanout = iutil.execWithCapture(args[0], args, searchPath = 1)
    for line in scanout.split("\n"):
        try:
            (dev, vg, format, attr, size, free) = line.strip()[:-1].split()
        except:
            continue
        size = size[:-1]
        log("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"]
    scanout = iutil.execWithCapture(args[0], args, searchPath = 1)
    for line in scanout.split("\n"):
        try:
            (vg, numpv, numlv, numsn, attr, size, free) = line.strip()[:-1].split()
        except:
            continue
        size = size[:-1]
        log("vg %s, size is %s" %(vg, size))
        vgs.append( (vg, size) )

    return vgs

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:
	factor = 1
    else:
	factor = 0
    if ((size*1024L) % pe) == 0:
	return size
    else:
	return ((long((size*1024L)/pe)+factor)*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)
    """

    # calculate the number of physical extents.  this is size / pesize
    # with an appropriate factor for kb/mb matchup
    numpes = math.floor(pvsize * 1024 / pesize)

    # now, calculate our "real" overhead.  4 bytes for each PE + 128K
    overhead = (4 * numpes / 1024) + 128

    # now, heuristically, the max of ceil(pesize + 2*overhead) and
    # ceil(2*overhead) is greater than the real overhead, so we won't
    # get people in a situation where they overcommit the vg
    one = math.ceil(pesize + 2 * overhead)
    two = math.ceil(2 * overhead)

    # now we have to do more unit conversion since our overhead in in KB
    if one > two:
        usable = pvsize - math.ceil(one / 1024.0)
    else:
        usable = pvsize - math.ceil(two / 1024.0)

    # finally, clamp to being at a pesize boundary
    return (long(usable*1024/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)
    
    return vgreq.getActualSize(requests, diskset) - used