contents.py 17 KB

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