contents.py 17 KB

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