5 # Check the free space available on a writable DVD
6 # Should always exit with 0 status, otherwise it indicates a serious error.
7 # (wrong number of arguments, Python exception...)
9 # called: dvd-handler <dvd-device-name> operation args
11 # operations used by Bacula:
14 # Scan the device and report the available space. It returns:
15 # Prints on the first output line the free space available in bytes.
16 # If an error occurs, prints a negative number (-errno), followed,
17 # on the second line, by an error message.
20 # Write a part file to disk.
21 # This operation needs two additional arguments.
22 # The first (op) indicates to
24 # 1 -- first write to a blank disk
25 # 2 -- blank or truncate a disk
27 # The second is the filename to write
29 # operations available but not used by Bacula:
31 # test Scan the device and report the information found.
32 # This operation needs no further arguments.
33 # prepare Prepare a DVD+/-RW for being used by Bacula.
34 # Note: This is only useful if you already have some
35 # non-Bacula data on a medium, and you want to use
36 # it with Bacula. Don't run this on blank media, it
54 # Configurable values:
56 dvdrwmediainfo = "@DVDRWMEDIAINFO@"
57 growcmd = "@GROWISOFS@"
58 dvdrwformat = "@DVDRWFORMAT@"
60 margin = 10485760 # 10 mb security margin
62 # Comment the following line if you want the tray to be reloaded
64 growcmd += " -use-the-force-luke=notray"
66 # end of configurable values
68 ###############################################################################
70 # This class represents DVD disk informations.
71 # When instantiated, it needs a device name.
72 # Status information about the device and the disk loaded is collected only when
73 # asked for (for example dvd-freespace doesn't need to know the media type, and
74 # dvd-writepart doesn't not always need to know the free space).
76 # The following methods are implemented:
77 # __init__ we need that...
78 # __repr__ this seems to be a good idea to have.
79 # Quite minimalistic implementation, though.
80 # __str__ For casts to string. Return the current disk information
81 # is_empty Returns TRUE if the disk is empty, blank... this needs more
82 # work, especially concerning non-RW media and blank vs. no
83 # filesystem considerations. Here, we should also look for
84 # other filesystems - probably we don't want to silently
85 # overwrite UDF or ext2 or anything not mentioned in fstab...
86 # (NB: I don't think it is a problem)
87 # free Returns the available free space.
88 # write Writes one part file to disk, either starting a new file
89 # system on disk, or appending to it.
90 # This method should also prepare a blank disk so that a
91 # certain part of the disk is used to allow detection of a
92 # used disk by all / more disk drives.
93 # prepare Blank the device
95 ###############################################################################
96 def __init__(self, devicename):
97 self.device = devicename
98 self.disktype = "none"
99 self.diskmode = "none"
100 self.diskstatus = "none"
101 self.hardwaredevice = "none"
103 self.next_session = -1
106 self.freespace_collected = 0
107 self.mediumtype_collected = 0
109 self.growcmd += " -quiet"
111 if self.is4gbsupported():
112 self.growcmd += " -use-the-force-luke=4gms"
114 self.growparams = " -A 'Bacula Data' -input-charset=default -iso-level 3 -pad " + \
115 "-p 'dvd-handler / growisofs' -sysid 'BACULADATA' -R"
120 return "disk(" + self.device + ") # This is an instance of class disk"
123 if not self.freespace_collected:
124 self.collect_freespace();
125 if not self.mediumtype_collected:
126 self.collect_mediumtype();
128 self.me = "Class disk, initialized with device '" + self.device + "'\n"
129 self.me += "type = '" + self.disktype + "' mode='" + self.diskmode + "' status = '" + self.diskstatus + "'\n"
130 self.me += " next_session = " + str(self.next_session) + " capacity = " + str(self.capacity) + "\n"
131 self.me += "Hardware device is '" + self.hardwaredevice + "'\n"
132 self.me += "growcmd = '" + self.growcmd + "'\ngrowparams = '" + self.growparams + "'\n"
135 ## Check if we want to allow growisofs to cross the 4gb boundary
136 def is4gbsupported(self):
137 processi = popen2.Popen4("uname -s -r")
138 status = processi.wait()
139 if not os.WIFEXITED(status):
141 if os.WEXITSTATUS(status) != 0:
143 strres = processi.fromchild.readline()[0:-1]
144 version = re.search(r"Linux (\d+)\.(\d+)\.(\d+)", strres)
145 if not version: # Non-Linux: allow
148 if (int(version.group(1)) > 2) or (int(version.group(2)) > 6) or ((int(version.group(1)) == 2) and (int(version.group(2)) == 6) and (int(version.group(3)) >= 8)):
153 def collect_freespace(self): # Collects current free space
154 self.cmd = self.growcmd + " -F " + self.device
155 processi = popen2.Popen4(self.cmd)
156 status = processi.wait()
157 if not os.WIFEXITED(status):
158 raise DVDError(0, "growisofs process did not exit correctly.")
159 result = processi.fromchild.read()
160 if os.WEXITSTATUS(status) != 0:
161 if (os.WEXITSTATUS(status) & 0x7F) == errno.ENOSPC:
162 # Kludge to force dvd-handler to return a free space of 0
163 self.next_session = 1
165 self.freespace_collected = 1
168 raise DVDError(os.WEXITSTATUS(status), "growisofs returned with an error " + result + ". Please check your are using a patched version of dvd+rw-tools.")
169 next_sess = re.search(r"\snext_session=(\d+)\s", result, re.MULTILINE)
170 capa = re.search(r"\scapacity=(\d+)\s", result, re.MULTILINE)
172 if next_sess and capa:
173 self.next_session = long(next_sess.group(1))
174 self.capacity = long(capa.group(1))
176 # testing cheat (emulate 4GB boundary at 100MB)
177 #if self.next_session > 100000000:
178 # self.capacity = self.next_session
180 raise DVDError(0, "Cannot get next_session and capacity from growisofs.\nReturned: " + result)
182 self.freespace_collected = 1
185 def collect_mediumtype(self): # Collects current medium type
187 cmd = self.dvdrwmediainfo + " " + self.device
188 processi = popen2.Popen4(cmd)
189 status = processi.wait()
190 if not os.WIFEXITED(status):
191 raise DVDError(0, self.dvdrwmediainfo + " process did not exit correctly.")
192 if os.WEXITSTATUS(status) != 0:
193 raise DVDError(0, "Cannot get media info from " + self.dvdrwmediainfo)
195 result = processi.fromchild.read()
197 hardware = re.search(r"INQUIRY:\s+(.*)\n", result, re.MULTILINE)
198 mediatype = re.search(r"\sMounted Media:\s+([0-9A-F]{2})h, (\S*)\s", result, re.MULTILINE)
199 mediamode = re.search(r"\sMounted Media:\s+[0-9A-F]{2}h, \S* (.*)\n", result, re.MULTILINE)
200 status = re.search(r"\sDisc status:\s+(.*)\n", result, re.MULTILINE)
203 self.hardwaredevice = hardware.group(1)
206 self.disktype = mediatype.group(2)
208 raise DVDError(0, "Media type not found in " + self.dvdrwmediainfo + " output")
210 if self.disktype == "DVD-RW":
212 self.diskmode = mediamode.group(1)
214 raise DVDError(0, "Media mode not found for DVD-RW in " + self.dvdrwmediainfo + " output")
217 self.diskstatus = status.group(1)
219 raise DVDError(0, "Disc status not found in " + self.dvdrwmediainfo + " output")
222 self.mediumtype_collected = 1
226 if not self.freespace_collected:
227 self.collect_freespace();
229 return 0 == self.next_session
232 if not self.mediumtype_collected:
233 self.collect_mediumtype();
234 return "DVD-RW" == self.disktype or "DVD+RW" == self.disktype or "DVD-RAM" == self.disktype
236 def is_plus_RW(self):
237 if not self.mediumtype_collected:
238 self.collect_mediumtype();
239 return "DVD+RW" == self.disktype
241 def is_minus_RW(self):
242 if not self.mediumtype_collected:
243 self.collect_mediumtype();
244 return "DVD-RW" == self.disktype
246 def is_restricted_overwrite(self):
247 if not self.mediumtype_collected:
248 self.collect_mediumtype();
249 return self.diskmode == "Restricted Overwrite"
252 if not self.mediumtype_collected:
253 self.collect_mediumtype();
255 return self.diskstatus == "blank"
258 if not self.freespace_collected:
259 self.collect_freespace();
261 fr = self.capacity-self.next_session-self.margin
267 def term_handler(self, signum, frame):
268 print 'dvd-handler: Signal term_handler called with signal', signum
270 print "dvd-handler: Sending SIGTERM to pid", self.pid
271 os.kill(self.pid, signal.SIGTERM)
273 print "dvd-handler: Sending SIGKILL to pid", self.pid
274 os.kill(self.pid, signal.SIGKILL)
277 def write(self, newvol, partfile):
278 # Blank DVD+RW when there is no data on it
279 if newvol and self.is_plus_RW() and self.is_blank():
280 print "DVD+RW looks brand-new, blank it to fix some DVD-writers bugs."
282 print "Done, now writing the part file."
284 if newvol and self.is_minus_RW() and (not self.is_restricted_overwrite()):
285 print "DVD-RW is in " + self.diskmode + " mode, reformating it to Restricted Overwrite"
286 self.reformat_minus_RW()
287 print "Done, now writing the part file."
289 cmd = self.growcmd + self.growparams
291 # Ignore any existing iso9660 filesystem - used for truncate
293 cmd += " -use-the-force-luke=tty"
297 cmd += self.device + " " + str(partfile)
298 print "Running " + cmd
299 oldsig = signal.signal(signal.SIGTERM, self.term_handler)
300 proc = popen2.Popen4(cmd)
304 line = proc.fromchild.readline()
307 line = proc.fromchild.readline()
312 signal.signal(signal.SIGTERM, oldsig)
313 if not os.WIFEXITED(status):
314 raise DVDError(0, cmd + " process did not exit correctly, signal/status " + str(status))
315 if os.WEXITSTATUS(status) != 0:
316 raise DVDError(os.WEXITSTATUS(status), cmd + " exited with status " + str(os.WEXITSTATUS(status)) + ", signal/status " + str(status))
320 raise DVDError(0, "I won't prepare a non-rewritable medium")
322 # Blank DVD+RW when there is no data on it
323 if self.is_plus_RW() and self.is_blank():
324 print "DVD+RW looks brand-new, blank it to fix some DVD-writers bugs."
326 return # It has been completely blanked: Medium is ready to be used by Bacula
328 if self.is_minus_RW() and (not self.is_restricted_overwrite()):
329 print "DVD-RW is in " + self.diskmode + " mode, reformating it to Restricted Overwrite"
330 self.reformat_minus_RW()
331 return # Reformated: Medium is ready to be used by Bacula
333 # TODO: Check if /dev/fd/0 and /dev/zero exists, otherwise, run self.blank()
334 if not os.path.exists("/dev/fd/0") or not os.path.exists("/dev/zero"):
335 print "/dev/fd/0 or /dev/zero doesn't exist, blank the medium completely."
339 cmd = self.dd + " if=/dev/zero bs=1024 count=512 | " + self.growcmd + " -Z " + self.device + "=/dev/fd/0"
340 print "Running " + cmd
341 oldsig = signal.signal(signal.SIGTERM, self.term_handler)
342 proc = popen2.Popen4(cmd)
346 line = proc.fromchild.readline()
349 line = proc.fromchild.readline()
354 signal.signal(signal.SIGTERM, oldsig)
355 if os.WEXITSTATUS(status) != 0:
356 raise DVDError(os.WEXITSTATUS(status), cmd + " exited with status " + str(os.WEXITSTATUS(status)) + ", signal/status " + str(status))
359 cmd = self.growcmd + " -Z " + self.device + "=/dev/zero"
360 print "Running " + cmd
361 oldsig = signal.signal(signal.SIGTERM, self.term_handler)
362 proc = popen2.Popen4(cmd)
366 line = proc.fromchild.readline()
369 line = proc.fromchild.readline()
374 signal.signal(signal.SIGTERM, oldsig)
375 if os.WEXITSTATUS(status) != 0:
376 raise DVDError(os.WEXITSTATUS(status), cmd + " exited with status " + str(os.WEXITSTATUS(status)) + ", signal/status " + str(status))
378 def reformat_minus_RW(self):
379 cmd = self.dvdrwformat + " -force " + self.device
380 print "Running " + cmd
381 oldsig = signal.signal(signal.SIGTERM, self.term_handler)
382 proc = popen2.Popen4(cmd)
386 line = proc.fromchild.readline()
389 line = proc.fromchild.readline()
394 signal.signal(signal.SIGTERM, oldsig)
395 if os.WEXITSTATUS(status) != 0:
396 raise DVDError(os.WEXITSTATUS(status), cmd + " exited with status " + str(os.WEXITSTATUS(status)) + ", signal/status " + str(status))
398 # class disk ends here.
400 class DVDError(Exception):
401 def __init__(self, errno, value):
404 if self.value[-1] == '\n':
405 self.value = self.value[0:-1]
407 return str(self.value) + " || errno = " + str(self.errno) + " (" + os.strerror(self.errno & 0x7F) + ")"
410 print "Wrong number of arguments."
414 dvd-handler DEVICE test
415 dvd-handler DEVICE free
416 dvd-handler DEVICE write APPEND FILE
417 dvd-handler DEVICE prepare
419 where DEVICE is a device name like /dev/sr0 or /dev/dvd.
422 test Scan the device and report the information found.
423 This operation needs no further arguments.
424 free Scan the device and report the available space.
425 write Write a part file to disk.
426 This operation needs two additional arguments.
427 The first indicates to append (0), restart the
428 disk (1) or restart existing disk (2). The second
429 is the file to write.
430 prepare Prepare a DVD+/-RW for being used by Bacula.
431 Note: This is only useful if you already have some
432 non-Bacula data on a medium, and you want to use
433 it with Bacula. Don't run this on blank media, it
438 if len(sys.argv) < 3:
441 dvd = disk(sys.argv[1])
443 if "free" == sys.argv[2]:
444 if len(sys.argv) == 3:
455 print "No Error reported."
457 print "Wrong number of arguments for free operation. Wanted 3 got", len(sys.argv)
459 elif "prepare" == sys.argv[2]:
460 if len(sys.argv) == 3:
464 print "Error while preparing medium: ", str(e)
466 sys.exit(e.errno & 0x7F)
468 sys.exit(errno.EPIPE)
470 print "Medium prepared successfully."
472 print "Wrong number of arguments for prepare operation. Wanted 3 got", len(sys.argv)
474 elif "test" == sys.argv[2]:
477 print "Blank disk: " + str(dvd.is_blank()) + " ReWritable disk: " + str(dvd.is_RW())
478 print "Free space: " + str(dvd.free())
480 print "Error while getting informations: ", str(e)
481 elif "write" == sys.argv[2]:
482 if len(sys.argv) == 5:
484 dvd.write(long(sys.argv[3]), sys.argv[4])
486 print "Error while writing part file: ", str(e)
488 sys.exit(e.errno & 0x7F)
490 sys.exit(errno.EPIPE)
492 print "Part file " + sys.argv[4] + " successfully written to disk."
494 print "Wrong number of arguments for write operation. Wanted 5 got", len(sys.argv)
498 print "No operation - use test, free, prepare or write."
499 print "THIS MIGHT BE A CASE OF DEBUGGING BACULA OR AN ERROR!"