dvd-handler 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  1. #!/usr/bin/python
  2. #
  3. # Check the free space available on a writable DVD
  4. # Should always exit with 0 status, otherwise it indicates a serious error.
  5. # (wrong number of arguments, Python exception...)
  6. #
  7. # called: dvd-handler <dvd-device-name> operation args
  8. #
  9. # operations used by Bacula:
  10. #
  11. # free (no arguments)
  12. # Scan the device and report the available space. It returns:
  13. # Prints on the first output line the free space available in bytes.
  14. # If an error occurs, prints a negative number (-errno), followed,
  15. # on the second line, by an error message.
  16. #
  17. # write op filename
  18. # Write a part file to disk.
  19. # This operation needs two additional arguments.
  20. # The first (op) indicates to
  21. # 0 -- append
  22. # 1 -- first write to a blank disk
  23. # 2 -- blank or truncate a disk
  24. #
  25. # The second is the filename to write
  26. #
  27. # operations available but not used by Bacula:
  28. #
  29. # test Scan the device and report the information found.
  30. # This operation needs no further arguments.
  31. # prepare Prepare a DVD+/-RW for being used by Bacula.
  32. # Note: This is only useful if you already have some
  33. # non-Bacula data on a medium, and you want to use
  34. # it with Bacula. Don't run this on blank media, it
  35. # is useless.
  36. #
  37. #
  38. # $Id$
  39. #
  40. import popen2
  41. import os
  42. import os.path
  43. import errno
  44. import sys
  45. import re
  46. import signal
  47. import time
  48. import array
  49. class disk:
  50. # Configurable values:
  51. dvdrwmediainfo = "dvd+rw-mediainfo"
  52. growcmd = "growisofs"
  53. dvdrwformat = "dvd+rw-format"
  54. dd = "/bin/dd"
  55. margin = 10485760 # 10 mb security margin
  56. # Comment the following line if you want the tray to be reloaded
  57. # when writing ends.
  58. growcmd += " -use-the-force-luke=notray"
  59. # end of configurable values
  60. ###############################################################################
  61. #
  62. # This class represents DVD disk informations.
  63. # When instantiated, it needs a device name.
  64. # Status information about the device and the disk loaded is collected only when
  65. # asked for (for example dvd-freespace doesn't need to know the media type, and
  66. # dvd-writepart doesn't not always need to know the free space).
  67. #
  68. # The following methods are implemented:
  69. # __init__ we need that...
  70. # __repr__ this seems to be a good idea to have.
  71. # Quite minimalistic implementation, though.
  72. # __str__ For casts to string. Return the current disk information
  73. # is_empty Returns TRUE if the disk is empty, blank... this needs more
  74. # work, especially concerning non-RW media and blank vs. no
  75. # filesystem considerations. Here, we should also look for
  76. # other filesystems - probably we don't want to silently
  77. # overwrite UDF or ext2 or anything not mentioned in fstab...
  78. # (NB: I don't think it is a problem)
  79. # free Returns the available free space.
  80. # write Writes one part file to disk, either starting a new file
  81. # system on disk, or appending to it.
  82. # This method should also prepare a blank disk so that a
  83. # certain part of the disk is used to allow detection of a
  84. # used disk by all / more disk drives.
  85. # prepare Blank the device
  86. #
  87. ###############################################################################
  88. def __init__(self, devicename):
  89. self.device = devicename
  90. self.disktype = "none"
  91. self.diskmode = "none"
  92. self.diskstatus = "none"
  93. self.hardwaredevice = "none"
  94. self.pid = 0
  95. self.next_session = -1
  96. self.capacity = -1
  97. self.freespace_collected = 0
  98. self.mediumtype_collected = 0
  99. self.growcmd += " -quiet"
  100. if self.is4gbsupported():
  101. self.growcmd += " -use-the-force-luke=4gms"
  102. self.growparams = " -A 'Bacula Data' -input-charset=default -iso-level 3 -pad " + \
  103. "-p 'dvd-handler / growisofs' -sysid 'BACULADATA' -R"
  104. return
  105. def __repr__(self):
  106. return "disk(" + self.device + ") # This is an instance of class disk"
  107. def __str__(self):
  108. if not self.freespace_collected:
  109. self.collect_freespace();
  110. if not self.mediumtype_collected:
  111. self.collect_mediumtype();
  112. self.me = "Class disk, initialized with device '" + self.device + "'\n"
  113. self.me += "type = '" + self.disktype + "' mode='" + self.diskmode + "' status = '" + self.diskstatus + "'\n"
  114. self.me += " next_session = " + str(self.next_session) + " capacity = " + str(self.capacity) + "\n"
  115. self.me += "Hardware device is '" + self.hardwaredevice + "'\n"
  116. self.me += "growcmd = '" + self.growcmd + "'\ngrowparams = '" + self.growparams + "'\n"
  117. return self.me
  118. ## Check if we want to allow growisofs to cross the 4gb boundary
  119. def is4gbsupported(self):
  120. processi = popen2.Popen4("uname -s -r")
  121. status = processi.wait()
  122. if not os.WIFEXITED(status):
  123. return 1
  124. if os.WEXITSTATUS(status) != 0:
  125. return 1
  126. strres = processi.fromchild.readline()[0:-1]
  127. version = re.search(r"Linux (\d+)\.(\d+)\.(\d+)", strres)
  128. if not version: # Non-Linux: allow
  129. return 1
  130. 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)):
  131. return 1
  132. else:
  133. return 0
  134. def collect_freespace(self): # Collects current free space
  135. self.cmd = self.growcmd + " -F " + self.device
  136. processi = popen2.Popen4(self.cmd)
  137. status = processi.wait()
  138. if not os.WIFEXITED(status):
  139. raise DVDError(0, "growisofs process did not exit correctly.")
  140. result = processi.fromchild.read()
  141. if os.WEXITSTATUS(status) != 0:
  142. if (os.WEXITSTATUS(status) & 0x7F) == errno.ENOSPC:
  143. # Kludge to force dvd-handler to return a free space of 0
  144. self.next_session = 1
  145. self.capacity = 1
  146. self.freespace_collected = 1
  147. return
  148. else:
  149. raise DVDError(os.WEXITSTATUS(status), "growisofs returned with an error " + result + ". Please check your are using a patched version of dvd+rw-tools.")
  150. next_sess = re.search(r"\snext_session=(\d+)\s", result, re.MULTILINE)
  151. capa = re.search(r"\scapacity=(\d+)\s", result, re.MULTILINE)
  152. if next_sess and capa:
  153. self.next_session = long(next_sess.group(1))
  154. self.capacity = long(capa.group(1))
  155. # testing cheat (emulate 4GB boundary at 100MB)
  156. #if self.next_session > 100000000:
  157. # self.capacity = self.next_session
  158. else:
  159. raise DVDError(0, "Cannot get next_session and capacity from growisofs.\nReturned: " + result)
  160. self.freespace_collected = 1
  161. return
  162. def collect_mediumtype(self): # Collects current medium type
  163. self.lasterror = ""
  164. cmd = self.dvdrwmediainfo + " " + self.device
  165. processi = popen2.Popen4(cmd)
  166. status = processi.wait()
  167. if not os.WIFEXITED(status):
  168. raise DVDError(0, self.dvdrwmediainfo + " process did not exit correctly.")
  169. if os.WEXITSTATUS(status) != 0:
  170. raise DVDError(0, "Cannot get media info from " + self.dvdrwmediainfo)
  171. return
  172. result = processi.fromchild.read()
  173. hardware = re.search(r"INQUIRY:\s+(.*)\n", result, re.MULTILINE)
  174. mediatype = re.search(r"\sMounted Media:\s+([0-9A-F]{2})h, (\S*)\s", result, re.MULTILINE)
  175. mediamode = re.search(r"\sMounted Media:\s+[0-9A-F]{2}h, \S* (.*)\n", result, re.MULTILINE)
  176. status = re.search(r"\sDisc status:\s+(.*)\n", result, re.MULTILINE)
  177. if hardware:
  178. self.hardwaredevice = hardware.group(1)
  179. if mediatype:
  180. self.disktype = mediatype.group(2)
  181. else:
  182. raise DVDError(0, "Media type not found in " + self.dvdrwmediainfo + " output")
  183. if self.disktype == "DVD-RW":
  184. if mediamode:
  185. self.diskmode = mediamode.group(1)
  186. else:
  187. raise DVDError(0, "Media mode not found for DVD-RW in " + self.dvdrwmediainfo + " output")
  188. if status:
  189. self.diskstatus = status.group(1)
  190. else:
  191. raise DVDError(0, "Disc status not found in " + self.dvdrwmediainfo + " output")
  192. self.mediumtype_collected = 1
  193. return
  194. def is_empty(self):
  195. if not self.freespace_collected:
  196. self.collect_freespace();
  197. return 0 == self.next_session
  198. def is_RW(self):
  199. if not self.mediumtype_collected:
  200. self.collect_mediumtype();
  201. return "DVD-RW" == self.disktype or "DVD+RW" == self.disktype or "DVD-RAM" == self.disktype
  202. def is_plus_RW(self):
  203. if not self.mediumtype_collected:
  204. self.collect_mediumtype();
  205. return "DVD+RW" == self.disktype
  206. def is_minus_RW(self):
  207. if not self.mediumtype_collected:
  208. self.collect_mediumtype();
  209. return "DVD-RW" == self.disktype
  210. def is_restricted_overwrite(self):
  211. if not self.mediumtype_collected:
  212. self.collect_mediumtype();
  213. return self.diskmode == "Restricted Overwrite"
  214. def is_blank(self):
  215. if not self.mediumtype_collected:
  216. self.collect_mediumtype();
  217. return self.diskstatus == "blank"
  218. def free(self):
  219. if not self.freespace_collected:
  220. self.collect_freespace();
  221. fr = self.capacity-self.next_session-self.margin
  222. if fr < 0:
  223. return 0
  224. else:
  225. return fr
  226. def term_handler(self, signum, frame):
  227. print 'dvd-handler: Signal term_handler called with signal', signum
  228. if self.pid != 0:
  229. print "dvd-handler: Sending SIGTERM to pid", self.pid
  230. os.kill(self.pid, signal.SIGTERM)
  231. time.sleep(10)
  232. print "dvd-handler: Sending SIGKILL to pid", self.pid
  233. os.kill(self.pid, signal.SIGKILL)
  234. sys.exit(1)
  235. def write(self, newvol, partfile):
  236. # Blank DVD+RW when there is no data on it
  237. if newvol and self.is_plus_RW() and self.is_blank():
  238. print "DVD+RW looks brand-new, blank it to fix some DVD-writers bugs."
  239. self.blank()
  240. print "Done, now writing the part file."
  241. if newvol and self.is_minus_RW() and (not self.is_restricted_overwrite()):
  242. print "DVD-RW is in " + self.diskmode + " mode, reformating it to Restricted Overwrite"
  243. self.reformat_minus_RW()
  244. print "Done, now writing the part file."
  245. cmd = self.growcmd + self.growparams
  246. if newvol:
  247. # Ignore any existing iso9660 filesystem - used for truncate
  248. if newvol == 2:
  249. cmd += " -use-the-force-luke=tty"
  250. cmd += " -Z "
  251. else:
  252. cmd += " -M "
  253. cmd += self.device + " " + str(partfile)
  254. print "Running " + cmd
  255. oldsig = signal.signal(signal.SIGTERM, self.term_handler)
  256. proc = popen2.Popen4(cmd)
  257. self.pid = proc.pid
  258. status = proc.poll()
  259. while status == -1:
  260. line = proc.fromchild.readline()
  261. while len(line) > 0:
  262. print line,
  263. line = proc.fromchild.readline()
  264. time.sleep(1)
  265. status = proc.poll()
  266. self.pid = 0
  267. print
  268. signal.signal(signal.SIGTERM, oldsig)
  269. if not os.WIFEXITED(status):
  270. raise DVDError(0, cmd + " process did not exit correctly, signal/status " + str(status))
  271. if os.WEXITSTATUS(status) != 0:
  272. raise DVDError(os.WEXITSTATUS(status), cmd + " exited with status " + str(os.WEXITSTATUS(status)) + ", signal/status " + str(status))
  273. def prepare(self):
  274. if not self.is_RW():
  275. raise DVDError(0, "I won't prepare a non-rewritable medium")
  276. # Blank DVD+RW when there is no data on it
  277. if self.is_plus_RW() and self.is_blank():
  278. print "DVD+RW looks brand-new, blank it to fix some DVD-writers bugs."
  279. self.blank()
  280. return # It has been completely blanked: Medium is ready to be used by Bacula
  281. if self.is_minus_RW() and (not self.is_restricted_overwrite()):
  282. print "DVD-RW is in " + self.diskmode + " mode, reformating it to Restricted Overwrite"
  283. self.reformat_minus_RW()
  284. return # Reformated: Medium is ready to be used by Bacula
  285. # TODO: Check if /dev/fd/0 and /dev/zero exists, otherwise, run self.blank()
  286. if not os.path.exists("/dev/fd/0") or not os.path.exists("/dev/zero"):
  287. print "/dev/fd/0 or /dev/zero doesn't exist, blank the medium completely."
  288. self.blank()
  289. return
  290. cmd = self.dd + " if=/dev/zero bs=1024 count=512 | " + self.growcmd + " -Z " + self.device + "=/dev/fd/0"
  291. print "Running " + cmd
  292. oldsig = signal.signal(signal.SIGTERM, self.term_handler)
  293. proc = popen2.Popen4(cmd)
  294. self.pid = proc.pid
  295. status = proc.poll()
  296. while status == -1:
  297. line = proc.fromchild.readline()
  298. while len(line) > 0:
  299. print line,
  300. line = proc.fromchild.readline()
  301. time.sleep(1)
  302. status = proc.poll()
  303. self.pid = 0
  304. print
  305. signal.signal(signal.SIGTERM, oldsig)
  306. if os.WEXITSTATUS(status) != 0:
  307. raise DVDError(os.WEXITSTATUS(status), cmd + " exited with status " + str(os.WEXITSTATUS(status)) + ", signal/status " + str(status))
  308. def blank(self):
  309. cmd = self.growcmd + " -Z " + self.device + "=/dev/zero"
  310. print "Running " + cmd
  311. oldsig = signal.signal(signal.SIGTERM, self.term_handler)
  312. proc = popen2.Popen4(cmd)
  313. self.pid = proc.pid
  314. status = proc.poll()
  315. while status == -1:
  316. line = proc.fromchild.readline()
  317. while len(line) > 0:
  318. print line,
  319. line = proc.fromchild.readline()
  320. time.sleep(1)
  321. status = proc.poll()
  322. self.pid = 0
  323. print
  324. signal.signal(signal.SIGTERM, oldsig)
  325. if os.WEXITSTATUS(status) != 0:
  326. raise DVDError(os.WEXITSTATUS(status), cmd + " exited with status " + str(os.WEXITSTATUS(status)) + ", signal/status " + str(status))
  327. def reformat_minus_RW(self):
  328. cmd = self.dvdrwformat + " -force " + self.device
  329. print "Running " + cmd
  330. oldsig = signal.signal(signal.SIGTERM, self.term_handler)
  331. proc = popen2.Popen4(cmd)
  332. self.pid = proc.pid
  333. status = proc.poll()
  334. while status == -1:
  335. line = proc.fromchild.readline()
  336. while len(line) > 0:
  337. print line,
  338. line = proc.fromchild.readline()
  339. time.sleep(1)
  340. status = proc.poll()
  341. self.pid = 0
  342. print
  343. signal.signal(signal.SIGTERM, oldsig)
  344. if os.WEXITSTATUS(status) != 0:
  345. raise DVDError(os.WEXITSTATUS(status), cmd + " exited with status " + str(os.WEXITSTATUS(status)) + ", signal/status " + str(status))
  346. # class disk ends here.
  347. class DVDError(Exception):
  348. def __init__(self, errno, value):
  349. self.errno = errno
  350. self.value = value
  351. if self.value[-1] == '\n':
  352. self.value = self.value[0:-1]
  353. def __str__(self):
  354. return str(self.value) + " || errno = " + str(self.errno) + " (" + os.strerror(self.errno & 0x7F) + ")"
  355. def usage():
  356. print "Wrong number of arguments."
  357. print """
  358. Usage:
  359. dvd-handler DEVICE test
  360. dvd-handler DEVICE free
  361. dvd-handler DEVICE write APPEND FILE
  362. dvd-handler DEVICE prepare
  363. where DEVICE is a device name like /dev/sr0 or /dev/dvd.
  364. Operations:
  365. test Scan the device and report the information found.
  366. This operation needs no further arguments.
  367. free Scan the device and report the available space.
  368. write Write a part file to disk.
  369. This operation needs two additional arguments.
  370. The first indicates to append (0), restart the
  371. disk (1) or restart existing disk (2). The second
  372. is the file to write.
  373. prepare Prepare a DVD+/-RW for being used by Bacula.
  374. Note: This is only useful if you already have some
  375. non-Bacula data on a medium, and you want to use
  376. it with Bacula. Don't run this on blank media, it
  377. is useless.
  378. """
  379. sys.exit(1)
  380. if len(sys.argv) < 3:
  381. usage()
  382. dvd = disk(sys.argv[1])
  383. if "free" == sys.argv[2]:
  384. if len(sys.argv) == 3:
  385. try:
  386. free = dvd.free()
  387. except DVDError, e:
  388. if e.errno != 0:
  389. print -e.errno
  390. else:
  391. print errno.EPIPE
  392. print str(e)
  393. else:
  394. print free
  395. print "No Error reported."
  396. else:
  397. print "Wrong number of arguments for free operation. Wanted 3 got", len(sys.argv)
  398. usage()
  399. elif "prepare" == sys.argv[2]:
  400. if len(sys.argv) == 3:
  401. try:
  402. dvd.prepare()
  403. except DVDError, e:
  404. print "Error while preparing medium: ", str(e)
  405. if e.errno != 0:
  406. sys.exit(e.errno & 0x7F)
  407. else:
  408. sys.exit(errno.EPIPE)
  409. else:
  410. print "Medium prepared successfully."
  411. else:
  412. print "Wrong number of arguments for prepare operation. Wanted 3 got", len(sys.argv)
  413. usage()
  414. elif "test" == sys.argv[2]:
  415. try:
  416. print str(dvd)
  417. print "Blank disk: " + str(dvd.is_blank()) + " ReWritable disk: " + str(dvd.is_RW())
  418. print "Free space: " + str(dvd.free())
  419. except DVDError, e:
  420. print "Error while getting informations: ", str(e)
  421. elif "write" == sys.argv[2]:
  422. if len(sys.argv) == 5:
  423. try:
  424. dvd.write(long(sys.argv[3]), sys.argv[4])
  425. except DVDError, e:
  426. print "Error while writing part file: ", str(e)
  427. if e.errno != 0:
  428. sys.exit(e.errno & 0x7F)
  429. else:
  430. sys.exit(errno.EPIPE)
  431. else:
  432. print "Part file " + sys.argv[4] + " successfully written to disk."
  433. else:
  434. print "Wrong number of arguments for write operation. Wanted 5 got", len(sys.argv)
  435. usage()
  436. sys.exit(1)
  437. else:
  438. print "No operation - use test, free, prepare or write."
  439. print "THIS MIGHT BE A CASE OF DEBUGGING BACULA OR AN ERROR!"
  440. sys.exit(0)