summaryrefslogtreecommitdiffstats
path: root/fstab.py
blob: 1818dcab26e8afc6c59b6b3e2e9e4c27c7450124 (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
# this owns partitioning, fstab generation, disk scanning, raid, etc
#
# a fstab is returned as a list of:
#	( mntpoint, device, fsystem, doFormat, size, (file) )
# tuples, sorted by mntpoint; note that device may be a raid device; the file 
# value is optional, and if it exists it names a file which will be created 
# on the (already existant!) device and loopback mounted
#
# the swap information is stored as ( device, format ) tuples
#
# raid lists are stored as ( raiddevice, raidlevel, [ device list ] )
#
# we always store as much of the fstab within the disk druid structure
# as we can -- Don't Duplicate Data.

	    #self.todo.setLiloLocation(("raid", liloBoot))
	    #self.todo.instClass.addToSkipList("lilo")

import isys
import iutil
import os

def _(str):
    return str

class Fstab:

    def rescanPartitions(self):
	if self.ddruid:
	    self.closeDrives()

        fstab = []
	for (mntpoint, dev, fstype, reformat, size) in self.cachedFstab:
            fstab.append ((dev, mntpoint))

	self.ddruid = self.fsedit(0, self.driveList(), fstab, self.zeroMbr,
				  self.readOnly)
	del self.cachedFstab

    def closeDrives(self):
	# we expect a rescanPartitions() after this!!!
	self.cachedFstab = self.mountList(skipExtra = 1)
	self.ddruid = None

    def setReadonly(self, readOnly):
	self.readOnly = readOnly

    def savePartitions(self):
	self.ddruid.save()

    def runDruid(self):
	self.ddruid.edit()
	# yikes! this needs to be smarter
	self.beenSaved = 0

    def updateFsCache(self):
	realFs = {}
	for (partition, mount, fsystem, size) in self.ddruid.getFstab():
	    realFs[(partition, mount)] = 1
	for ((partition, mount)) in self.fsCache.keys():
	    if not realFs.has_key((partition, mount)):
		del self.fsCache[(partition, mount)]

    def setFormatFilesystem(self, device, format):
	for (partition, mount, fsystem, size) in self.ddruid.getFstab():
	    if partition == device:
		self.fsCache[(partition, mount)] = (format,)

    def partitionList(self):
	return self.ddruid.partitionList()

    def driveList(self):
	drives = isys.hardDriveList().keys()
	drives.sort (isys.compareDrives)
	return drives

    def drivesByName(self):
	return isys.hardDriveList()

    def swapList(self):
	fstab = []
	for (partition, mount, fsystem, size) in self.ddruid.getFstab():
	    if fsystem != "swap": continue

	    fstab.append((partition, 1))
	return fstab

    def turnOnSwap(self):
	# we could be smarter about this
	if self.swapOn: return
	self.swapOn = 1

	for (device, doFormat) in self.swapList():
	    w = self.waitWindow(_("Formatting"),
			  _("Formatting swap space on /dev/%s...") % (device,))

	    file = '/tmp/' + device
	    isys.makeDevInode(device, file)

	    rc = iutil.execWithRedirect ("/usr/sbin/mkswap",
					 [ "mkswap", '-v1', '/tmp/' + device ],
					 stdout = None, stderr = None,
					 searchPath = 1)
	    w.pop()

	    if rc:
		self.waitWindow("Error creating swap on device " + device)
	    else:
		isys.swapon (file)

	    os.unlink(file)

    def createRaidTab(self, file, devPrefix, createDevices = 0):
        (devices, raid) = self.ddruid.partitionList()
	if not raid: return

	deviceDict = {}
	for (device, name, type, start, size) in devices:
	    deviceDict[name] = device

	rt = open(file, "w")
	for (mntpoint, device, fstype, raidType, start, size, makeup) in raid:

	    if createDevices:
		isys.makeDevInode(device, devPrefix + '/' + device)

	    rt.write("raiddev		    %s/%s\n" % (devPrefix, device,))
	    rt.write("raid-level		    %d\n" % (raidType,))
	    rt.write("nr-raid-disks		    %d\n" % (len(makeup),))
	    rt.write("chunk-size		    64k\n")
	    rt.write("persistent-superblock	    1\n");
	    rt.write("#nr-spare-disks	    0\n")
	    i = 0
	    for subDevName in makeup:
		isys.makeDevInode(deviceDict[subDevName], '%s/%s' % 
			    (devPrefix, deviceDict[subDevName]))
		rt.write("    device	    %s/%s\n" % 
		    (devPrefix, deviceDict[subDevName],))
		rt.write("    raid-disk     %d\n" % (i,))
		i = i + 1

	rt.write("\n")
	rt.close()

    def umountFilesystems(self):
	if (not self.setupFilesystems): return 

	isys.umount(self.instPath + '/proc')

	for (mntpoint, device, fsystem, doFormat, size) in self.mountList():
            if fsystem != "swap":
		try:
		    mntPoint = self.instPath + n
		    self.log("unmounting " + mntPoint)
                    isys.umount(mntPoint)
		except SystemError, (errno, msg):
		    self.messageWindow(_("Error"), 
			_("Error unmounting %s: %s") % (device, msg))


    def makeFilesystems(self):
	# let's make the RAID devices first -- the fstab will then proceed
	# naturally
        (devices, raid) = self.ddruid.partitionList()

	if raid:
	    self.createRaidTab("/tmp/raidtab", "/tmp", createDevices = 1)

	    w = self.waitWindow(_("Creating"), _("Creating RAID devices..."))

	    for (mntpoint, device, fsType, raidType, start, size, makeup) in raid:
                iutil.execWithRedirect ("/usr/sbin/mkraid", 
			[ 'mkraid', '--really-force', '--configfile', 
			  '/tmp/raidtab', '/tmp/' + device ])

	    w.pop()
        
	    # XXX remove extraneous inodes here

        if not self.setupFilesystems: return

        arch = iutil.getArch ()

        if arch == "alpha":
            if '/boot' in keys:
                kernelPart = '/boot'
            else:
                kernelPart = '/'
        
	for (mntpoint, device, fsystem, doFormat, size) in self.mountList():
	    if not doFormat: continue
	    isys.makeDevInode(device, '/tmp/' + device)
            if fsystem == "ext2":
                args = [ "mke2fs", '/tmp/' + device ]
                # FORCE the partition that MILO has to read
                # to have 1024 block size.  It's the only
                # thing that our milo seems to read.
                if arch == "alpha" and mntpoint == kernelPart:
                    args = args + ["-b", "1024"]
                # set up raid options for md devices.
                if device[:2] == 'md':
                    for (rmnt, rdevice, fsType, raidType, start, size, makeup) in raid:
                        if rdevice == device:
                            rtype = raidType
                            rdisks = len (makeup)
                    if rtype == 5:
                        rdisks = rdisks - 1
                        args = args + [ '-R', 'stride=%d' % (rdisks * 16) ]
                    elif rtype == 0:
                        args = args + [ '-R', 'stride=%d' % (rdisks * 16) ]                        
                        
                if self.badBlockCheck:
                    args.append ("-c")

		w = self.waitWindow(_("Formatting"),
			      _("Formatting %s filesystem...") % (mntpoint,))

		if self.serial:
		    messages = "/tmp/mke2fs.log"
		else:
		    messages = "/dev/tty5"
                iutil.execWithRedirect ("/usr/sbin/mke2fs",
                                        args,
                                        stdout = messages, stderr = messages,
                                        searchPath = 1)
		w.pop()
            else:
                pass

            os.remove('/tmp/' + device)

    def mountFilesystems(self, instPath):
	if (not self.setupFilesystems): return 

	for (mntpoint, device, fsystem, doFormat, size) in self.mountList():
            if fsystem == "swap":
		continue
	    elif fsystem == "ext2":
		try:
		    iutil.mkdirChain(instPath + mntpoint)
		    isys.makeDevInode(device, '/tmp/' + device)
		    isys.mount('/tmp/' + device, 
				instPath + mntpoint)
		    os.remove( '/tmp/' + device);
		except SystemError, (errno, msg):
		    self.intf.messageWindow(_("Error"), 
			_("Error mounting %s: %s") % (device, msg))

        try:
            os.mkdir (instPath + '/proc')
        except:
            pass
            
	isys.mount('/proc', instPath + '/proc', 'proc')

    def write(self, prefix, fdDevice = "/dev/fd0"):
	format = "%-23s %-23s %-7s %-15s %d %d\n";

	f = open (prefix + "/etc/fstab", "w")
	for (mntpoint, dev, fs, reformat, size) in self.mountList():
	    iutil.mkdirChain(prefix + mntpoint)
	    if (mntpoint == '/'):
		f.write (format % ( '/dev/' + dev, mntpoint, fs, 'defaults', 1, 1))
	    else:
                if (fs == "ext2"):
                    f.write (format % ( '/dev/' + dev, mntpoint, fs, 'defaults', 1, 2))
                elif fs == "iso9660":
                    f.write (format % ( '/dev/' + dev, mntpoint, fs, 'noauto,owner,ro', 0, 0))
                else:
                    f.write (format % ( '/dev/' + dev, mntpoint, fs, 'defaults', 0, 0))
	f.write (format % (fdDevice, "/mnt/floppy", 'ext2', 'noauto,owner', 0, 0))
	f.write (format % ("none", "/proc", 'proc', 'defaults', 0, 0))
	f.write (format % ("none", "/dev/pts", 'devpts', 'gid=5,mode=620', 0, 0))

	for (partition, doFormat) in self.swapList():
	    f.write (format % ("/dev/" + partition, 'swap', 'swap', 
			       'defaults', 0, 0))

	f.close ()
        # touch mtab
        open (prefix + "/etc/mtab", "w+")
        f.close ()

	self.createRaidTab(prefix + "/etc/raidtab", "/dev")

    def addMount(self, partition, mount, fsystem, doFormat = 0, size = 0):
	self.extraFilesystems.append(mount, partition, fsystem, doFormat,
				     size)

    def mountList(self, skipExtra = 0):
	def sortMounts(one, two):
	    mountOne = one[0]
	    mountTwo = two[0]
	    if (mountOne < mountTwo):
		return -1
	    elif (mountOne == mountTwo):
		return 0
	    return 1

	fstab = []
	for (partition, mount, fsystem, size) in self.ddruid.getFstab():
	    if fsystem == "swap": continue

	    if not self.fsCache.has_key((partition, mount)):
		self.fsCache[(partition, mount)] = (0, )
	    (doFormat,) = self.fsCache[(partition, mount)]
	    fstab.append((mount, partition, fsystem, doFormat, size ))

	if not skipExtra:
	    for n in self.extraFilesystems:
		fstab.append(n)

	fstab.sort(sortMounts)

	return fstab

    def saveDruidPartitions(self):
	if self.beenSaved: return
	self.ddruid.save()
	self.beenSaved = 1

    def setBadBlockCheck(self, state):
	self.badBlockCheck = state

    def getBadBlockCheck(self):
	return self.badBlockCheck

    def __init__(self, fsedit, setupFilesystems, serial, zeroMbr, 
		 readOnly, waitWindow, messageWindow):
	self.fsedit = fsedit
	self.fsCache = {}
	self.swapOn = 0
	self.beenSaved = 1
	self.setupFilesystems = setupFilesystems
	self.serial = serial
	self.zeroMbr = zeroMbr
	self.readOnly = readOnly
	self.waitWindow = waitWindow
	self.messageWindow = messageWindow
	self.badBlockCheck = 0
	self.extraFilesystems = []
	self.ddruid = self.fsedit(0, self.driveList(), [], 
			     zeroMbr, readOnly)

class GuiFstab(Fstab):

    def runDruid(self, callback):
        self.ddruid.setCallback (callback)

        bin = self.GtkFrame (None, _obj = self.ddruid.getWindow ())
        bin.set_shadow_type (self.SHADOW_NONE)
        self.ddruid.edit ()
	return bin

    def runDruidFinished(self):
	self.ddruid.next ()
	self.updateFsCache()
	# yikes! this needs to be smarter
	self.beenSaved = 0

    def __init__(self, setupFilesystems, serial, zeroMbr, readOnly, waitWindow,
		 messageWindow):
	from gnomepyfsedit import fsedit        
	from gtk import *

	Fstab.__init__(self, fsedit, setupFilesystems, serial, zeroMbr, 
		       readOnly, waitWindow, messageWindow)

	self.GtkFrame = GtkFrame
	self.SHADOW_NONE = SHADOW_NONE

class NewtFstab(Fstab):

    def __init__(self, setupFilesystems, serial, zeroMbr, readOnly, waitWindow,
		 messageWindow):
	from newtpyfsedit import fsedit        

	Fstab.__init__(self, fsedit, setupFilesystems, serial, zeroMbr, 
		       readOnly, waitWindow, messageWindow)