contents.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  1. """
  2. Helper code for contents generation.
  3. @contact: Debian FTPMaster <ftpmaster@debian.org>
  4. @copyright: 2011 Torsten Werner <twerner@debian.org>
  5. @license: GNU General Public License version 2 or later
  6. """
  7. ################################################################################
  8. # This program is free software; you can redistribute it and/or modify
  9. # it under the terms of the GNU General Public License as published by
  10. # the Free Software Foundation; either version 2 of the License, or
  11. # (at your option) any later version.
  12. # This program is distributed in the hope that it will be useful,
  13. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. # GNU General Public License for more details.
  16. # You should have received a copy of the GNU General Public License
  17. # along with this program; if not, write to the Free Software
  18. # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  19. ################################################################################
  20. from daklib.dbconn import *
  21. from daklib.config import Config
  22. from daklib.filewriter import BinaryContentsFileWriter, SourceContentsFileWriter
  23. from .dakmultiprocessing import DakProcessPool
  24. from shutil import rmtree
  25. from tempfile import mkdtemp
  26. import subprocess
  27. import os.path
  28. import sqlalchemy.sql as sql
  29. class BinaryContentsWriter(object):
  30. '''
  31. BinaryContentsWriter writes the Contents-$arch.gz files.
  32. '''
  33. def __init__(self, suite, architecture, overridetype, component):
  34. self.suite = suite
  35. self.architecture = architecture
  36. self.overridetype = overridetype
  37. self.component = component
  38. self.session = suite.session()
  39. def query(self):
  40. '''
  41. Returns a query object that is doing most of the work.
  42. '''
  43. overridesuite = self.suite
  44. if self.suite.overridesuite is not None:
  45. overridesuite = get_suite(self.suite.overridesuite, self.session)
  46. params = {
  47. 'suite': self.suite.suite_id,
  48. 'overridesuite': overridesuite.suite_id,
  49. 'component': self.component.component_id,
  50. 'arch': self.architecture.arch_id,
  51. 'type_id': self.overridetype.overridetype_id,
  52. 'type': self.overridetype.overridetype,
  53. }
  54. if self.suite.separate_contents_architecture_all:
  55. sql_arch_part = 'architecture = :arch'
  56. else:
  57. sql_arch_part = '(architecture = :arch_all or architecture = :arch)'
  58. params['arch_all'] = get_architecture('all', self.session).arch_id
  59. sql_create_temp = '''
  60. create temp table newest_binaries (
  61. id integer primary key,
  62. package text);
  63. create index newest_binaries_by_package on newest_binaries (package);
  64. insert into newest_binaries (id, package)
  65. select distinct on (package) id, package from binaries
  66. where type = :type and
  67. %s and
  68. id in (select bin from bin_associations where suite = :suite)
  69. order by package, version desc;''' % sql_arch_part
  70. self.session.execute(sql_create_temp, params=params)
  71. query = sql.text('''
  72. with
  73. unique_override as
  74. (select o.package, s.section
  75. from override o, section s
  76. where o.suite = :overridesuite and o.type = :type_id and o.section = s.id and
  77. o.component = :component)
  78. select bc.file, string_agg(o.section || '/' || b.package, ',' order by b.package) as pkglist
  79. from newest_binaries b, bin_contents bc, unique_override o
  80. where b.id = bc.binary_id and o.package = b.package
  81. group by bc.file''')
  82. return self.session.query("file", "pkglist").from_statement(query). \
  83. params(params)
  84. def formatline(self, filename, package_list):
  85. '''
  86. Returns a formatted string for the filename argument.
  87. '''
  88. return "%-55s %s\n" % (filename, package_list)
  89. def fetch(self):
  90. '''
  91. Yields a new line of the Contents-$arch.gz file in filename order.
  92. '''
  93. for filename, package_list in self.query().yield_per(100):
  94. yield self.formatline(filename, package_list)
  95. # end transaction to return connection to pool
  96. self.session.rollback()
  97. def get_list(self):
  98. '''
  99. Returns a list of lines for the Contents-$arch.gz file.
  100. '''
  101. return [item for item in self.fetch()]
  102. def writer(self):
  103. '''
  104. Returns a writer object.
  105. '''
  106. values = {
  107. 'archive': self.suite.archive.path,
  108. 'suite': self.suite.suite_name,
  109. 'component': self.component.component_name,
  110. 'debtype': self.overridetype.overridetype,
  111. 'architecture': self.architecture.arch_string,
  112. }
  113. return BinaryContentsFileWriter(**values)
  114. def write_file(self):
  115. '''
  116. Write the output file.
  117. '''
  118. writer = self.writer()
  119. file = writer.open()
  120. for item in self.fetch():
  121. file.write(item)
  122. writer.close()
  123. class SourceContentsWriter(object):
  124. '''
  125. SourceContentsWriter writes the Contents-source.gz files.
  126. '''
  127. def __init__(self, suite, component):
  128. self.suite = suite
  129. self.component = component
  130. self.session = suite.session()
  131. def query(self):
  132. '''
  133. Returns a query object that is doing most of the work.
  134. '''
  135. params = {
  136. 'suite_id': self.suite.suite_id,
  137. 'component_id': self.component.component_id,
  138. }
  139. sql_create_temp = '''
  140. create temp table newest_sources (
  141. id integer primary key,
  142. source text);
  143. create index sources_binaries_by_source on newest_sources (source);
  144. insert into newest_sources (id, source)
  145. select distinct on (source) s.id, s.source from source s
  146. join files_archive_map af on s.file = af.file_id
  147. where s.id in (select source from src_associations where suite = :suite_id)
  148. and af.component_id = :component_id
  149. order by source, version desc;'''
  150. self.session.execute(sql_create_temp, params=params)
  151. query = sql.text('''
  152. select sc.file, string_agg(s.source, ',' order by s.source) as pkglist
  153. from newest_sources s, src_contents sc
  154. where s.id = sc.source_id group by sc.file''')
  155. return self.session.query("file", "pkglist").from_statement(query). \
  156. params(params)
  157. def formatline(self, filename, package_list):
  158. '''
  159. Returns a formatted string for the filename argument.
  160. '''
  161. return "%s\t%s\n" % (filename, package_list)
  162. def fetch(self):
  163. '''
  164. Yields a new line of the Contents-source.gz file in filename order.
  165. '''
  166. for filename, package_list in self.query().yield_per(100):
  167. yield self.formatline(filename, package_list)
  168. # end transaction to return connection to pool
  169. self.session.rollback()
  170. def get_list(self):
  171. '''
  172. Returns a list of lines for the Contents-source.gz file.
  173. '''
  174. return [item for item in self.fetch()]
  175. def writer(self):
  176. '''
  177. Returns a writer object.
  178. '''
  179. values = {
  180. 'archive': self.suite.archive.path,
  181. 'suite': self.suite.suite_name,
  182. 'component': self.component.component_name
  183. }
  184. return SourceContentsFileWriter(**values)
  185. def write_file(self):
  186. '''
  187. Write the output file.
  188. '''
  189. writer = self.writer()
  190. file = writer.open()
  191. for item in self.fetch():
  192. file.write(item)
  193. writer.close()
  194. def binary_helper(suite_id, arch_id, overridetype_id, component_id):
  195. '''
  196. This function is called in a new subprocess and multiprocessing wants a top
  197. level function.
  198. '''
  199. session = DBConn().session(work_mem=1000)
  200. suite = Suite.get(suite_id, session)
  201. architecture = Architecture.get(arch_id, session)
  202. overridetype = OverrideType.get(overridetype_id, session)
  203. component = Component.get(component_id, session)
  204. log_message = [suite.suite_name, architecture.arch_string,
  205. overridetype.overridetype, component.component_name]
  206. contents_writer = BinaryContentsWriter(suite, architecture, overridetype, component)
  207. contents_writer.write_file()
  208. session.close()
  209. return log_message
  210. def source_helper(suite_id, component_id):
  211. '''
  212. This function is called in a new subprocess and multiprocessing wants a top
  213. level function.
  214. '''
  215. session = DBConn().session(work_mem=1000)
  216. suite = Suite.get(suite_id, session)
  217. component = Component.get(component_id, session)
  218. log_message = [suite.suite_name, 'source', component.component_name]
  219. contents_writer = SourceContentsWriter(suite, component)
  220. contents_writer.write_file()
  221. session.close()
  222. return log_message
  223. class ContentsWriter(object):
  224. '''
  225. Loop over all suites, architectures, overridetypes, and components to write
  226. all contents files.
  227. '''
  228. @classmethod
  229. def log_result(class_, result):
  230. '''
  231. Writes a result message to the logfile.
  232. '''
  233. class_.logger.log(list(result))
  234. @classmethod
  235. def write_all(class_, logger, archive_names=None, suite_names=None, component_names=None, force=False):
  236. '''
  237. Writes all Contents files for suites in list suite_names which defaults
  238. to all 'touchable' suites if not specified explicitely. Untouchable
  239. suites will be included if the force argument is set to True.
  240. '''
  241. pool = DakProcessPool()
  242. class_.logger = logger
  243. session = DBConn().session()
  244. suite_query = session.query(Suite)
  245. if archive_names:
  246. suite_query = suite_query.join(Suite.archive).filter(Archive.archive_name.in_(archive_names))
  247. if suite_names:
  248. suite_query = suite_query.filter(Suite.suite_name.in_(suite_names))
  249. component_query = session.query(Component)
  250. if component_names:
  251. component_query = component_query.filter(Component.component_name.in_(component_names))
  252. if not force:
  253. suite_query = suite_query.filter(Suite.untouchable == False) # noqa:E712
  254. deb_id = get_override_type('deb', session).overridetype_id
  255. udeb_id = get_override_type('udeb', session).overridetype_id
  256. # Lock tables so that nobody can change things underneath us
  257. session.execute("LOCK TABLE bin_contents IN SHARE MODE")
  258. session.execute("LOCK TABLE src_contents IN SHARE MODE")
  259. for suite in suite_query:
  260. suite_id = suite.suite_id
  261. skip_arch_all = True
  262. if suite.separate_contents_architecture_all:
  263. skip_arch_all = False
  264. for component in component_query:
  265. component_id = component.component_id
  266. # handle source packages
  267. pool.apply_async(source_helper, (suite_id, component_id),
  268. callback=class_.log_result)
  269. for architecture in suite.get_architectures(skipsrc=True, skipall=skip_arch_all):
  270. arch_id = architecture.arch_id
  271. # handle 'deb' packages
  272. pool.apply_async(binary_helper, (suite_id, arch_id, deb_id, component_id),
  273. callback=class_.log_result)
  274. # handle 'udeb' packages
  275. pool.apply_async(binary_helper, (suite_id, arch_id, udeb_id, component_id),
  276. callback=class_.log_result)
  277. pool.close()
  278. pool.join()
  279. session.close()
  280. class BinaryContentsScanner(object):
  281. '''
  282. BinaryContentsScanner provides a threadsafe method scan() to scan the
  283. contents of a DBBinary object.
  284. '''
  285. def __init__(self, binary_id):
  286. '''
  287. The argument binary_id is the id of the DBBinary object that
  288. should be scanned.
  289. '''
  290. self.binary_id = binary_id
  291. def scan(self):
  292. '''
  293. This method does the actual scan and fills in the associated BinContents
  294. property. It commits any changes to the database. The argument dummy_arg
  295. is ignored but needed by our threadpool implementation.
  296. '''
  297. session = DBConn().session()
  298. binary = session.query(DBBinary).get(self.binary_id)
  299. fileset = set(binary.scan_contents())
  300. if len(fileset) == 0:
  301. fileset.add('EMPTY_PACKAGE')
  302. for filename in fileset:
  303. binary.contents.append(BinContents(file=filename))
  304. session.commit()
  305. session.close()
  306. @classmethod
  307. def scan_all(class_, limit=None):
  308. '''
  309. The class method scan_all() scans all binaries using multiple threads.
  310. The number of binaries to be scanned can be limited with the limit
  311. argument. Returns the number of processed and remaining packages as a
  312. dict.
  313. '''
  314. pool = DakProcessPool()
  315. session = DBConn().session()
  316. query = session.query(DBBinary).filter(DBBinary.contents == None) # noqa:E711
  317. remaining = query.count
  318. if limit is not None:
  319. query = query.limit(limit)
  320. processed = query.count()
  321. for binary in query.yield_per(100):
  322. pool.apply_async(binary_scan_helper, (binary.binary_id, ))
  323. pool.close()
  324. pool.join()
  325. remaining = remaining()
  326. session.close()
  327. return {'processed': processed, 'remaining': remaining}
  328. def binary_scan_helper(binary_id):
  329. '''
  330. This function runs in a subprocess.
  331. '''
  332. try:
  333. scanner = BinaryContentsScanner(binary_id)
  334. scanner.scan()
  335. except Exception as e:
  336. print("binary_scan_helper raised an exception: %s" % (e))
  337. class UnpackedSource(object):
  338. '''
  339. UnpackedSource extracts a source package into a temporary location and
  340. gives you some convinient function for accessing it.
  341. '''
  342. def __init__(self, dscfilename, tmpbasedir=None):
  343. '''
  344. The dscfilename is a name of a DSC file that will be extracted.
  345. '''
  346. basedir = tmpbasedir if tmpbasedir else Config()['Dir::TempPath']
  347. temp_directory = mkdtemp(dir=basedir)
  348. self.root_directory = os.path.join(temp_directory, 'root')
  349. command = ('dpkg-source', '--no-copy', '--no-check', '-q', '-x',
  350. dscfilename, self.root_directory)
  351. subprocess.check_call(command)
  352. def get_root_directory(self):
  353. '''
  354. Returns the name of the package's root directory which is the directory
  355. where the debian subdirectory is located.
  356. '''
  357. return self.root_directory
  358. def get_all_filenames(self):
  359. '''
  360. Returns an iterator over all filenames. The filenames will be relative
  361. to the root directory.
  362. '''
  363. skip = len(self.root_directory) + 1
  364. for root, _, files in os.walk(self.root_directory):
  365. for name in files:
  366. yield os.path.join(root[skip:], name)
  367. def cleanup(self):
  368. '''
  369. Removes all temporary files.
  370. '''
  371. if self.root_directory is None:
  372. return
  373. parent_directory = os.path.dirname(self.root_directory)
  374. rmtree(parent_directory)
  375. self.root_directory = None
  376. def __del__(self):
  377. '''
  378. Enforce cleanup.
  379. '''
  380. self.cleanup()
  381. class SourceContentsScanner(object):
  382. '''
  383. SourceContentsScanner provides a method scan() to scan the contents of a
  384. DBSource object.
  385. '''
  386. def __init__(self, source_id):
  387. '''
  388. The argument source_id is the id of the DBSource object that
  389. should be scanned.
  390. '''
  391. self.source_id = source_id
  392. def scan(self):
  393. '''
  394. This method does the actual scan and fills in the associated SrcContents
  395. property. It commits any changes to the database.
  396. '''
  397. session = DBConn().session()
  398. source = session.query(DBSource).get(self.source_id)
  399. fileset = set(source.scan_contents())
  400. for filename in fileset:
  401. source.contents.append(SrcContents(file=filename))
  402. session.commit()
  403. session.close()
  404. @classmethod
  405. def scan_all(class_, limit=None):
  406. '''
  407. The class method scan_all() scans all source using multiple processes.
  408. The number of sources to be scanned can be limited with the limit
  409. argument. Returns the number of processed and remaining packages as a
  410. dict.
  411. '''
  412. pool = DakProcessPool()
  413. session = DBConn().session()
  414. query = session.query(DBSource).filter(DBSource.contents == None) # noqa:E711
  415. remaining = query.count
  416. if limit is not None:
  417. query = query.limit(limit)
  418. processed = query.count()
  419. for source in query.yield_per(100):
  420. pool.apply_async(source_scan_helper, (source.source_id, ))
  421. pool.close()
  422. pool.join()
  423. remaining = remaining()
  424. session.close()
  425. return {'processed': processed, 'remaining': remaining}
  426. def source_scan_helper(source_id):
  427. '''
  428. This function runs in a subprocess.
  429. '''
  430. try:
  431. scanner = SourceContentsScanner(source_id)
  432. scanner.scan()
  433. except Exception as e:
  434. print("source_scan_helper raised an exception: %s" % (e))