archive.py 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321
  1. # Copyright (C) 2012, Ansgar Burchardt <ansgar@debian.org>
  2. #
  3. # This program is free software; you can redistribute it and/or modify
  4. # it under the terms of the GNU General Public License as published by
  5. # the Free Software Foundation; either version 2 of the License, or
  6. # (at your option) any later version.
  7. #
  8. # This program is distributed in the hope that it will be useful,
  9. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. # GNU General Public License for more details.
  12. #
  13. # You should have received a copy of the GNU General Public License along
  14. # with this program; if not, write to the Free Software Foundation, Inc.,
  15. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  16. """module to manipulate the archive
  17. This module provides classes to manipulate the archive.
  18. """
  19. from daklib.dbconn import *
  20. import daklib.checks as checks
  21. from daklib.config import Config
  22. from daklib.externalsignature import check_upload_for_external_signature_request
  23. import daklib.upload
  24. import daklib.utils
  25. from daklib.fstransactions import FilesystemTransaction
  26. from daklib.regexes import re_changelog_versions, re_bin_only_nmu
  27. import os
  28. import shutil
  29. from collections.abc import Callable, Iterable
  30. from sqlalchemy.orm.exc import NoResultFound
  31. from sqlalchemy.orm import object_session
  32. from typing import Optional, TYPE_CHECKING, Union
  33. import sqlalchemy.exc
  34. import subprocess
  35. import traceback
  36. if TYPE_CHECKING:
  37. import daklib.packagelist
  38. class ArchiveException(Exception):
  39. pass
  40. class HashMismatchException(ArchiveException):
  41. pass
  42. class ArchiveTransaction:
  43. """manipulate the archive in a transaction
  44. """
  45. def __init__(self):
  46. self.fs = FilesystemTransaction()
  47. self.session = DBConn().session()
  48. def get_file(self, hashed_file: daklib.upload.HashedFile, source_name: str, check_hashes: bool = True) -> PoolFile:
  49. """Look for file `hashed_file` in database
  50. :param hashed_file: file to look for in the database
  51. :param source_name: source package name
  52. :param check_hashes: check size and hashes match
  53. :return: database entry for the file
  54. :raises KeyError: file was not found in the database
  55. :raises HashMismatchException: hash mismatch
  56. """
  57. poolname = os.path.join(daklib.utils.poolify(source_name), hashed_file.filename)
  58. try:
  59. poolfile = self.session.query(PoolFile).filter_by(filename=poolname).one()
  60. if check_hashes and (poolfile.filesize != hashed_file.size
  61. or poolfile.md5sum != hashed_file.md5sum
  62. or poolfile.sha1sum != hashed_file.sha1sum
  63. or poolfile.sha256sum != hashed_file.sha256sum):
  64. raise HashMismatchException('{0}: Does not match file already existing in the pool.'.format(hashed_file.filename))
  65. return poolfile
  66. except NoResultFound:
  67. raise KeyError('{0} not found in database.'.format(poolname))
  68. def _install_file(self, directory, hashed_file, archive, component, source_name) -> PoolFile:
  69. """Install a file
  70. Will not give an error when the file is already present.
  71. :return: database object for the new file
  72. """
  73. session = self.session
  74. poolname = os.path.join(daklib.utils.poolify(source_name), hashed_file.filename)
  75. try:
  76. poolfile = self.get_file(hashed_file, source_name)
  77. except KeyError:
  78. poolfile = PoolFile(filename=poolname, filesize=hashed_file.size)
  79. poolfile.md5sum = hashed_file.md5sum
  80. poolfile.sha1sum = hashed_file.sha1sum
  81. poolfile.sha256sum = hashed_file.sha256sum
  82. session.add(poolfile)
  83. session.flush()
  84. try:
  85. session.query(ArchiveFile).filter_by(archive=archive, component=component, file=poolfile).one()
  86. except NoResultFound:
  87. archive_file = ArchiveFile(archive, component, poolfile)
  88. session.add(archive_file)
  89. session.flush()
  90. path = os.path.join(archive.path, 'pool', component.component_name, poolname)
  91. hashed_file_path = os.path.join(directory, hashed_file.input_filename)
  92. self.fs.copy(hashed_file_path, path, link=False, mode=archive.mode)
  93. return poolfile
  94. def install_binary(self, directory: str, binary: daklib.upload.Binary, suite: Suite, component: Component, allow_tainted: bool = False, fingerprint: Optional[Fingerprint] = None, source_suites=None, extra_source_archives: Optional[Iterable[Archive]] = None) -> DBBinary:
  95. """Install a binary package
  96. :param directory: directory the binary package is located in
  97. :param binary: binary package to install
  98. :param suite: target suite
  99. :param component: target component
  100. :param allow_tainted: allow to copy additional files from tainted archives
  101. :param fingerprint: optional fingerprint
  102. :param source_suites: suites to copy the source from if they are not
  103. in `suite` or :const:`True` to allow copying from any
  104. suite.
  105. Can be a SQLAlchemy subquery for :class:`Suite` or :const:`True`.
  106. :param extra_source_archives: extra archives to copy Built-Using sources from
  107. :return: database object for the new package
  108. """
  109. session = self.session
  110. control = binary.control
  111. maintainer = get_or_set_maintainer(control['Maintainer'], session)
  112. architecture = get_architecture(control['Architecture'], session)
  113. (source_name, source_version) = binary.source
  114. source_query = session.query(DBSource).filter_by(source=source_name, version=source_version)
  115. source = source_query.filter(DBSource.suites.contains(suite)).first()
  116. if source is None:
  117. if source_suites is not True:
  118. source_query = source_query.join(DBSource.suites) \
  119. .filter(Suite.suite_id == source_suites.c.id)
  120. source = source_query.first()
  121. if source is None:
  122. raise ArchiveException('{0}: trying to install to {1}, but could not find source ({2} {3})'.
  123. format(binary.hashed_file.filename, suite.suite_name, source_name, source_version))
  124. self.copy_source(source, suite, source.poolfile.component)
  125. db_file = self._install_file(directory, binary.hashed_file, suite.archive, component, source_name)
  126. unique = dict(
  127. package=control['Package'],
  128. version=control['Version'],
  129. architecture=architecture,
  130. )
  131. rest = dict(
  132. source=source,
  133. maintainer=maintainer,
  134. poolfile=db_file,
  135. binarytype=binary.type,
  136. )
  137. # Other attributes that are ignored for purposes of equality with
  138. # an existing source
  139. rest2 = dict(
  140. fingerprint=fingerprint,
  141. )
  142. try:
  143. db_binary = session.query(DBBinary).filter_by(**unique).one()
  144. for key, value in rest.items():
  145. if getattr(db_binary, key) != value:
  146. raise ArchiveException('{0}: Does not match binary in database.'.format(binary.hashed_file.filename))
  147. except NoResultFound:
  148. db_binary = DBBinary(**unique)
  149. for key, value in rest.items():
  150. setattr(db_binary, key, value)
  151. for key, value in rest2.items():
  152. setattr(db_binary, key, value)
  153. session.add(db_binary)
  154. session.flush()
  155. import_metadata_into_db(db_binary, session)
  156. self._add_built_using(db_binary, binary.hashed_file.filename, control, suite, extra_archives=extra_source_archives)
  157. if suite not in db_binary.suites:
  158. db_binary.suites.append(suite)
  159. session.flush()
  160. return db_binary
  161. def _ensure_extra_source_exists(self, filename: str, source: DBSource, archive: Archive, extra_archives: Optional[Iterable[Archive]] = None):
  162. """ensure source exists in the given archive
  163. This is intended to be used to check that Built-Using sources exist.
  164. :param filename: filename to use in error messages
  165. :param source: source to look for
  166. :param archive: archive to look in
  167. :param extra_archives: list of archives to copy the source package from
  168. if it is not yet present in `archive`
  169. """
  170. session = self.session
  171. db_file = session.query(ArchiveFile).filter_by(file=source.poolfile, archive=archive).first()
  172. if db_file is not None:
  173. return True
  174. # Try to copy file from one extra archive
  175. if extra_archives is None:
  176. extra_archives = []
  177. db_file = session.query(ArchiveFile).filter_by(file=source.poolfile).filter(ArchiveFile.archive_id.in_([a.archive_id for a in extra_archives])).first()
  178. if db_file is None:
  179. raise ArchiveException('{0}: Built-Using refers to package {1} (= {2}) not in target archive {3}.'.format(filename, source.source, source.version, archive.archive_name))
  180. source_archive = db_file.archive
  181. for dsc_file in source.srcfiles:
  182. af = session.query(ArchiveFile).filter_by(file=dsc_file.poolfile, archive=source_archive, component=db_file.component).one()
  183. # We were given an explicit list of archives so it is okay to copy from tainted archives.
  184. self._copy_file(af.file, archive, db_file.component, allow_tainted=True)
  185. def _add_built_using(self, db_binary, filename, control, suite, extra_archives=None) -> None:
  186. """Add Built-Using sources to ``db_binary.extra_sources``
  187. """
  188. session = self.session
  189. for bu_source_name, bu_source_version in daklib.utils.parse_built_using(control):
  190. bu_source = session.query(DBSource).filter_by(source=bu_source_name, version=bu_source_version).first()
  191. if bu_source is None:
  192. raise ArchiveException('{0}: Built-Using refers to non-existing source package {1} (= {2})'.format(filename, bu_source_name, bu_source_version))
  193. self._ensure_extra_source_exists(filename, bu_source, suite.archive, extra_archives=extra_archives)
  194. db_binary.extra_sources.append(bu_source)
  195. def install_source_to_archive(self, directory, source, archive, component, changed_by, allow_tainted=False, fingerprint=None) -> DBSource:
  196. """Install source package to archive"""
  197. session = self.session
  198. control = source.dsc
  199. maintainer = get_or_set_maintainer(control['Maintainer'], session)
  200. source_name = control['Source']
  201. ### Add source package to database
  202. # We need to install the .dsc first as the DBSource object refers to it.
  203. db_file_dsc = self._install_file(directory, source._dsc_file, archive, component, source_name)
  204. unique = dict(
  205. source=source_name,
  206. version=control['Version'],
  207. )
  208. rest = dict(
  209. maintainer=maintainer,
  210. poolfile=db_file_dsc,
  211. dm_upload_allowed=(control.get('DM-Upload-Allowed', 'no') == 'yes'),
  212. )
  213. # Other attributes that are ignored for purposes of equality with
  214. # an existing source
  215. rest2 = dict(
  216. changedby=changed_by,
  217. fingerprint=fingerprint,
  218. )
  219. created = False
  220. try:
  221. db_source = session.query(DBSource).filter_by(**unique).one()
  222. for key, value in rest.items():
  223. if getattr(db_source, key) != value:
  224. raise ArchiveException('{0}: Does not match source in database.'.format(source._dsc_file.filename))
  225. except NoResultFound:
  226. created = True
  227. db_source = DBSource(**unique)
  228. for key, value in rest.items():
  229. setattr(db_source, key, value)
  230. for key, value in rest2.items():
  231. setattr(db_source, key, value)
  232. session.add(db_source)
  233. session.flush()
  234. # Add .dsc file. Other files will be added later.
  235. db_dsc_file = DSCFile()
  236. db_dsc_file.source = db_source
  237. db_dsc_file.poolfile = db_file_dsc
  238. session.add(db_dsc_file)
  239. session.flush()
  240. if not created:
  241. for f in db_source.srcfiles:
  242. self._copy_file(f.poolfile, archive, component, allow_tainted=allow_tainted)
  243. return db_source
  244. ### Now add remaining files and copy them to the archive.
  245. for hashed_file in source.files.values():
  246. hashed_file_path = os.path.join(directory, hashed_file.input_filename)
  247. if os.path.exists(hashed_file_path):
  248. db_file = self._install_file(directory, hashed_file, archive, component, source_name)
  249. session.add(db_file)
  250. else:
  251. db_file = self.get_file(hashed_file, source_name)
  252. self._copy_file(db_file, archive, component, allow_tainted=allow_tainted)
  253. db_dsc_file = DSCFile()
  254. db_dsc_file.source = db_source
  255. db_dsc_file.poolfile = db_file
  256. session.add(db_dsc_file)
  257. session.flush()
  258. # Importing is safe as we only arrive here when we did not find the source already installed earlier.
  259. import_metadata_into_db(db_source, session)
  260. # Uploaders are the maintainer and co-maintainers from the Uploaders field
  261. db_source.uploaders.append(maintainer)
  262. if 'Uploaders' in control:
  263. from daklib.textutils import split_uploaders
  264. for u in split_uploaders(control['Uploaders']):
  265. db_source.uploaders.append(get_or_set_maintainer(u, session))
  266. session.flush()
  267. return db_source
  268. def install_source(self, directory: str, source: daklib.upload.Source, suite: Suite, component: Component, changed_by: Maintainer, allow_tainted: bool = False, fingerprint: Optional[Fingerprint] = None) -> DBSource:
  269. """Install a source package
  270. :param directory: directory the source package is located in
  271. :param source: source package to install
  272. :param suite: target suite
  273. :param component: target component
  274. :param changed_by: person who prepared this version of the package
  275. :param allow_tainted: allow to copy additional files from tainted archives
  276. :param fingerprint: optional fingerprint
  277. :return: database object for the new source
  278. """
  279. db_source = self.install_source_to_archive(directory, source, suite.archive, component, changed_by, allow_tainted, fingerprint)
  280. if suite in db_source.suites:
  281. return db_source
  282. db_source.suites.append(suite)
  283. self.session.flush()
  284. return db_source
  285. def _copy_file(self, db_file: PoolFile, archive: Archive, component: Component, allow_tainted: bool = False) -> None:
  286. """Copy a file to the given archive and component
  287. :param db_file: file to copy
  288. :param archive: target archive
  289. :param component: target component
  290. :param allow_tainted: allow to copy from tainted archives (such as NEW)
  291. """
  292. session = self.session
  293. if session.query(ArchiveFile).filter_by(archive=archive, component=component, file=db_file).first() is None:
  294. query = session.query(ArchiveFile).filter_by(file=db_file)
  295. if not allow_tainted:
  296. query = query.join(Archive).filter(Archive.tainted == False) # noqa:E712
  297. source_af = query.first()
  298. if source_af is None:
  299. raise ArchiveException('cp: Could not find {0} in any archive.'.format(db_file.filename))
  300. target_af = ArchiveFile(archive, component, db_file)
  301. session.add(target_af)
  302. session.flush()
  303. self.fs.copy(source_af.path, target_af.path, link=False, mode=archive.mode)
  304. def copy_binary(self, db_binary: DBBinary, suite: Suite, component: Component, allow_tainted: bool = False, extra_archives: Optional[Iterable[Archive]] = None) -> None:
  305. """Copy a binary package to the given suite and component
  306. :param db_binary: binary to copy
  307. :param suite: target suite
  308. :param component: target component
  309. :param allow_tainted: allow to copy from tainted archives (such as NEW)
  310. :param extra_archives: extra archives to copy Built-Using sources from
  311. """
  312. session = self.session
  313. archive = suite.archive
  314. if archive.tainted:
  315. allow_tainted = True
  316. filename = db_binary.poolfile.filename
  317. # make sure source is present in target archive
  318. db_source = db_binary.source
  319. if session.query(ArchiveFile).filter_by(archive=archive, file=db_source.poolfile).first() is None:
  320. raise ArchiveException('{0}: cannot copy to {1}: source is not present in target archive'.format(filename, suite.suite_name))
  321. # make sure built-using packages are present in target archive
  322. for db_source in db_binary.extra_sources:
  323. self._ensure_extra_source_exists(filename, db_source, archive, extra_archives=extra_archives)
  324. # copy binary
  325. db_file = db_binary.poolfile
  326. self._copy_file(db_file, suite.archive, component, allow_tainted=allow_tainted)
  327. if suite not in db_binary.suites:
  328. db_binary.suites.append(suite)
  329. self.session.flush()
  330. def copy_source(self, db_source: DBSource, suite: Suite, component: Component, allow_tainted: bool = False) -> None:
  331. """Copy a source package to the given suite and component
  332. :param db_source: source to copy
  333. :param suite: target suite
  334. :param component: target component
  335. :param allow_tainted: allow to copy from tainted archives (such as NEW)
  336. """
  337. archive = suite.archive
  338. if archive.tainted:
  339. allow_tainted = True
  340. for db_dsc_file in db_source.srcfiles:
  341. self._copy_file(db_dsc_file.poolfile, archive, component, allow_tainted=allow_tainted)
  342. if suite not in db_source.suites:
  343. db_source.suites.append(suite)
  344. self.session.flush()
  345. def remove_file(self, db_file: PoolFile, archive: Archive, component: Component) -> None:
  346. """Remove a file from a given archive and component
  347. :param db_file: file to remove
  348. :param archive: archive to remove the file from
  349. :param component: component to remove the file from
  350. """
  351. af = self.session.query(ArchiveFile).filter_by(file=db_file, archive=archive, component=component)
  352. self.fs.unlink(af.path)
  353. self.session.delete(af)
  354. def remove_binary(self, binary: DBBinary, suite: Suite) -> None:
  355. """Remove a binary from a given suite and component
  356. :param binary: binary to remove
  357. :param suite: suite to remove the package from
  358. """
  359. binary.suites.remove(suite)
  360. self.session.flush()
  361. def remove_source(self, source: DBSource, suite: Suite) -> None:
  362. """Remove a source from a given suite and component
  363. :param source: source to remove
  364. :param suite: suite to remove the package from
  365. :raises ArchiveException: source package is still referenced by other
  366. binaries in the suite
  367. """
  368. session = self.session
  369. query = session.query(DBBinary).filter_by(source=source) \
  370. .filter(DBBinary.suites.contains(suite))
  371. if query.first() is not None:
  372. raise ArchiveException('src:{0} is still used by binaries in suite {1}'.format(source.source, suite.suite_name))
  373. source.suites.remove(suite)
  374. session.flush()
  375. def commit(self) -> None:
  376. """commit changes"""
  377. try:
  378. self.session.commit()
  379. self.fs.commit()
  380. finally:
  381. self.session.rollback()
  382. self.fs.rollback()
  383. def rollback(self) -> None:
  384. """rollback changes"""
  385. self.session.rollback()
  386. self.fs.rollback()
  387. def flush(self) -> None:
  388. """flush underlying database session"""
  389. self.session.flush()
  390. def __enter__(self):
  391. return self
  392. def __exit__(self, type, value, traceback):
  393. if type is None:
  394. self.commit()
  395. else:
  396. self.rollback()
  397. return None
  398. def source_component_from_package_list(package_list: 'daklib.packagelist.PackageList', suite: Suite) -> Optional[Component]:
  399. """Get component for a source package
  400. This function will look at the Package-List field to determine the
  401. component the source package belongs to. This is the first component
  402. the source package provides binaries for (first with respect to the
  403. ordering of components).
  404. It the source package has no Package-List field, None is returned.
  405. :param package_list: package list of the source to get the override for
  406. :param suite: suite to consider for binaries produced
  407. :return: component for the given source or :const:`None`
  408. """
  409. if package_list.fallback:
  410. return None
  411. session = object_session(suite)
  412. packages = package_list.packages_for_suite(suite)
  413. components = set(p.component for p in packages)
  414. query = session.query(Component).order_by(Component.ordering) \
  415. .filter(Component.component_name.in_(components))
  416. return query.first()
  417. class ArchiveUpload:
  418. """handle an upload
  419. This class can be used in a with-statement::
  420. with ArchiveUpload(...) as upload:
  421. ...
  422. Doing so will automatically run any required cleanup and also rollback the
  423. transaction if it was not committed.
  424. """
  425. def __init__(self, directory: str, changes, keyrings):
  426. self.transaction: ArchiveTransaction = ArchiveTransaction()
  427. """transaction used to handle the upload"""
  428. self.session = self.transaction.session
  429. """database session"""
  430. self.original_directory: str = directory
  431. self.original_changes = changes
  432. self.changes: Optional[daklib.upload.Changes] = None
  433. """upload to process"""
  434. self.directory: str = None
  435. """directory with temporary copy of files. set by :meth:`prepare`"""
  436. self.keyrings = keyrings
  437. self.fingerprint: Fingerprint = self.session.query(Fingerprint).filter_by(fingerprint=changes.primary_fingerprint).one()
  438. """fingerprint of the key used to sign the upload"""
  439. self.reject_reasons: list[str] = []
  440. """reasons why the upload cannot by accepted"""
  441. self.warnings: list[str] = []
  442. """warnings
  443. .. note::
  444. Not used yet.
  445. """
  446. self.final_suites = None
  447. self.new: bool = False
  448. """upload is NEW. set by :meth:`check`"""
  449. self._checked: bool = False
  450. """checks passes. set by :meth:`check`"""
  451. self._new_queue = self.session.query(PolicyQueue).filter_by(queue_name='new').one()
  452. self._new = self._new_queue.suite
  453. def warn(self, message: str) -> None:
  454. """add a warning message
  455. Adds a warning message that can later be seen in :attr:`warnings`
  456. :param message: warning message
  457. """
  458. self.warnings.append(message)
  459. def prepare(self):
  460. """prepare upload for further processing
  461. This copies the files involved to a temporary directory. If you use
  462. this method directly, you have to remove the directory given by the
  463. :attr:`directory` attribute later on your own.
  464. Instead of using the method directly, you can also use a with-statement::
  465. with ArchiveUpload(...) as upload:
  466. ...
  467. This will automatically handle any required cleanup.
  468. """
  469. assert self.directory is None
  470. assert self.original_changes.valid_signature
  471. cnf = Config()
  472. session = self.transaction.session
  473. group = cnf.get('Dinstall::UnprivGroup') or None
  474. self.directory = daklib.utils.temp_dirname(parent=cnf.get('Dir::TempPath'),
  475. mode=0o2750, group=group)
  476. with FilesystemTransaction() as fs:
  477. src = os.path.join(self.original_directory, self.original_changes.filename)
  478. dst = os.path.join(self.directory, self.original_changes.filename)
  479. fs.copy(src, dst, mode=0o640)
  480. self.changes = daklib.upload.Changes(self.directory, self.original_changes.filename, self.keyrings)
  481. files = {}
  482. try:
  483. files = self.changes.files
  484. except daklib.upload.InvalidChangesException:
  485. # Do not raise an exception; upload will be rejected later
  486. # due to the missing files
  487. pass
  488. for f in files.values():
  489. src = os.path.join(self.original_directory, f.filename)
  490. dst = os.path.join(self.directory, f.filename)
  491. if not os.path.exists(src):
  492. continue
  493. fs.copy(src, dst, mode=0o640)
  494. source = None
  495. try:
  496. source = self.changes.source
  497. except Exception:
  498. # Do not raise an exception here if the .dsc is invalid.
  499. pass
  500. if source is not None:
  501. for f in source.files.values():
  502. src = os.path.join(self.original_directory, f.filename)
  503. dst = os.path.join(self.directory, f.filename)
  504. if not os.path.exists(dst):
  505. try:
  506. db_file = self.transaction.get_file(f, source.dsc['Source'], check_hashes=False)
  507. db_archive_file = session.query(ArchiveFile).filter_by(file=db_file).first()
  508. fs.copy(db_archive_file.path, dst, mode=0o640)
  509. except KeyError:
  510. # Ignore if get_file could not find it. Upload will
  511. # probably be rejected later.
  512. pass
  513. def unpacked_source(self) -> Optional[str]:
  514. """Path to unpacked source
  515. Get path to the unpacked source. This method does unpack the source
  516. into a temporary directory under :attr:`directory` if it has not
  517. been done so already.
  518. :return: string giving the path to the unpacked source directory
  519. or :const:`None` if no source was included in the upload.
  520. """
  521. assert self.directory is not None
  522. source = self.changes.source
  523. if source is None:
  524. return None
  525. dsc_path = os.path.join(self.directory, source._dsc_file.filename)
  526. sourcedir = os.path.join(self.directory, 'source')
  527. if not os.path.exists(sourcedir):
  528. subprocess.check_call(["dpkg-source", "--no-copy", "--no-check", "-x", dsc_path, sourcedir], shell=False, stdout=subprocess.DEVNULL)
  529. if not os.path.isdir(sourcedir):
  530. raise Exception("{0} is not a directory after extracting source package".format(sourcedir))
  531. return sourcedir
  532. def _map_suite(self, suite_name):
  533. suite_names = set((suite_name, ))
  534. for rule in Config().value_list("SuiteMappings"):
  535. fields = rule.split()
  536. rtype = fields[0]
  537. if rtype == "map" or rtype == "silent-map":
  538. (src, dst) = fields[1:3]
  539. if src in suite_names:
  540. suite_names.remove(src)
  541. suite_names.add(dst)
  542. if rtype != "silent-map":
  543. self.warnings.append('Mapping {0} to {1}.'.format(src, dst))
  544. elif rtype == "copy" or rtype == "silent-copy":
  545. (src, dst) = fields[1:3]
  546. if src in suite_names:
  547. suite_names.add(dst)
  548. if rtype != "silent-copy":
  549. self.warnings.append('Copy {0} to {1}.'.format(src, dst))
  550. elif rtype == "ignore":
  551. ignored = fields[1]
  552. if ignored in suite_names:
  553. suite_names.remove(ignored)
  554. self.warnings.append('Ignoring target suite {0}.'.format(ignored))
  555. elif rtype == "reject":
  556. rejected = fields[1]
  557. if rejected in suite_names:
  558. raise checks.Reject('Uploads to {0} are not accepted.'.format(rejected))
  559. ## XXX: propup-version and map-unreleased not yet implemented
  560. return suite_names
  561. def _mapped_suites(self) -> list[Suite]:
  562. """Get target suites after mappings
  563. :return: list giving the mapped target suites of this upload
  564. """
  565. session = self.session
  566. suite_names = set()
  567. for dist in self.changes.distributions:
  568. suite_names.update(self._map_suite(dist))
  569. suites = session.query(Suite).filter(Suite.suite_name.in_(suite_names))
  570. return suites.all()
  571. def _check_new_binary_overrides(self, suite, overridesuite):
  572. new = False
  573. source = self.changes.source
  574. # Check binaries listed in the source package's Package-List field:
  575. if source is not None and not source.package_list.fallback:
  576. packages = source.package_list.packages_for_suite(suite)
  577. binaries = [entry for entry in packages]
  578. for b in binaries:
  579. override = self._binary_override(overridesuite, b)
  580. if override is None:
  581. self.warnings.append('binary:{0} is NEW.'.format(b.name))
  582. new = True
  583. # Check all uploaded packages.
  584. # This is necessary to account for packages without a Package-List
  585. # field, really late binary-only uploads (where an unused override
  586. # was already removed), and for debug packages uploaded to a suite
  587. # without a debug suite (which are then considered as NEW).
  588. binaries = self.changes.binaries
  589. for b in binaries:
  590. if daklib.utils.is_in_debug_section(b.control) and suite.debug_suite is not None:
  591. continue
  592. override = self._binary_override(overridesuite, b)
  593. if override is None:
  594. self.warnings.append('binary:{0} is NEW.'.format(b.name))
  595. new = True
  596. return new
  597. def _check_new(self, suite, overridesuite) -> bool:
  598. """Check if upload is NEW
  599. An upload is NEW if it has binary or source packages that do not have
  600. an override in `overridesuite` OR if it references files ONLY in a
  601. tainted archive (eg. when it references files in NEW).
  602. Debug packages (*-dbgsym in Section: debug) are not considered as NEW
  603. if `suite` has a separate debug suite.
  604. :return: :const:`True` if the upload is NEW, :const:`False` otherwise
  605. """
  606. session = self.session
  607. new = False
  608. # Check for missing overrides
  609. if self._check_new_binary_overrides(suite, overridesuite):
  610. new = True
  611. if self.changes.source is not None:
  612. override = self._source_override(overridesuite, self.changes.source)
  613. if override is None:
  614. self.warnings.append('source:{0} is NEW.'.format(self.changes.source.dsc['Source']))
  615. new = True
  616. # Check if we reference a file only in a tainted archive
  617. files = list(self.changes.files.values())
  618. if self.changes.source is not None:
  619. files.extend(self.changes.source.files.values())
  620. for f in files:
  621. query = session.query(ArchiveFile).join(PoolFile).filter(PoolFile.sha1sum == f.sha1sum)
  622. query_untainted = query.join(Archive).filter(Archive.tainted == False) # noqa:E712
  623. in_archive = (query.first() is not None)
  624. in_untainted_archive = (query_untainted.first() is not None)
  625. if in_archive and not in_untainted_archive:
  626. self.warnings.append('{0} is only available in NEW.'.format(f.filename))
  627. new = True
  628. return new
  629. def _final_suites(self):
  630. session = self.session
  631. mapped_suites = self._mapped_suites()
  632. final_suites = list()
  633. for suite in mapped_suites:
  634. overridesuite = suite
  635. if suite.overridesuite is not None:
  636. overridesuite = session.query(Suite).filter_by(suite_name=suite.overridesuite).one()
  637. if self._check_new(suite, overridesuite):
  638. self.new = True
  639. if suite not in final_suites:
  640. final_suites.append(suite)
  641. return final_suites
  642. def _binary_override(self, suite: Suite, binary: 'Union[daklib.upload.Binary, daklib.packagelist.PackageListEntry]') -> Optional[Override]:
  643. """Get override entry for a binary
  644. :param suite: suite to get override for
  645. :param binary: binary to get override for
  646. :return: override for the given binary or :const:`None`
  647. """
  648. if suite.overridesuite is not None:
  649. suite = self.session.query(Suite).filter_by(suite_name=suite.overridesuite).one()
  650. mapped_component = get_mapped_component(binary.component)
  651. if mapped_component is None:
  652. return None
  653. query = self.session.query(Override).filter_by(suite=suite, package=binary.name) \
  654. .join(Component).filter(Component.component_name == mapped_component.component_name) \
  655. .join(OverrideType).filter(OverrideType.overridetype == binary.type)
  656. return query.one_or_none()
  657. def _source_override(self, suite: Suite, source: daklib.upload.Source) -> Optional[Override]:
  658. """Get override entry for a source
  659. :param suite: suite to get override for
  660. :param source: source to get override for
  661. :return: override for the given source or :const:`None`
  662. """
  663. if suite.overridesuite is not None:
  664. suite = self.session.query(Suite).filter_by(suite_name=suite.overridesuite).one()
  665. query = self.session.query(Override).filter_by(suite=suite, package=source.dsc['Source']) \
  666. .join(OverrideType).filter(OverrideType.overridetype == 'dsc')
  667. component = source_component_from_package_list(source.package_list, suite)
  668. if component is not None:
  669. query = query.filter(Override.component == component)
  670. return query.one_or_none()
  671. def _binary_component(self, suite: Suite, binary: daklib.upload.Binary, only_overrides: bool = True) -> Optional[Component]:
  672. """get component for a binary
  673. By default this will only look at overrides to get the right component;
  674. if `only_overrides` is :const:`False` this method will also look at the
  675. Section field.
  676. :param only_overrides: only use overrides to get the right component
  677. """
  678. override = self._binary_override(suite, binary)
  679. if override is not None:
  680. return override.component
  681. if only_overrides:
  682. return None
  683. return get_mapped_component(binary.component, self.session)
  684. def _source_component(self, suite: Suite, source: daklib.upload.Binary, only_overrides: bool = True) -> Optional[Component]:
  685. """get component for a source
  686. By default this will only look at overrides to get the right component;
  687. if `only_overrides` is :const:`False` this method will also look at the
  688. Section field.
  689. :param only_overrides: only use overrides to get the right component
  690. """
  691. override = self._source_override(suite, source)
  692. if override is not None:
  693. return override.component
  694. if only_overrides:
  695. return None
  696. return get_mapped_component(source.component, self.session)
  697. def check(self, force: bool = False) -> bool:
  698. """run checks against the upload
  699. :param force: ignore failing forcable checks
  700. :return: :const:`True` if all checks passed, :const:`False` otherwise
  701. """
  702. # XXX: needs to be better structured.
  703. assert self.changes.valid_signature
  704. try:
  705. # Validate signatures and hashes before we do any real work:
  706. for chk in (
  707. checks.SignatureAndHashesCheck,
  708. checks.WeakSignatureCheck,
  709. checks.SignatureTimestampCheck,
  710. checks.ChangesCheck,
  711. checks.ExternalHashesCheck,
  712. checks.SourceCheck,
  713. checks.BinaryCheck,
  714. checks.BinaryMembersCheck,
  715. checks.BinaryTimestampCheck,
  716. checks.SingleDistributionCheck,
  717. checks.ArchAllBinNMUCheck,
  718. ):
  719. chk().check(self)
  720. final_suites = self._final_suites()
  721. if len(final_suites) == 0:
  722. self.reject_reasons.append('No target suite found. Please check your target distribution and that you uploaded to the right archive.')
  723. return False
  724. self.final_suites = final_suites
  725. for chk in (
  726. checks.TransitionCheck,
  727. checks.ACLCheck,
  728. checks.NewOverrideCheck,
  729. checks.NoSourceOnlyCheck,
  730. checks.LintianCheck,
  731. ):
  732. chk().check(self)
  733. for chk in (
  734. checks.SuiteCheck,
  735. checks.ACLCheck,
  736. checks.SourceFormatCheck,
  737. checks.SuiteArchitectureCheck,
  738. checks.VersionCheck,
  739. ):
  740. for suite in final_suites:
  741. chk().per_suite_check(self, suite)
  742. if len(self.reject_reasons) != 0:
  743. return False
  744. self._checked = True
  745. return True
  746. except checks.Reject as e:
  747. self.reject_reasons.append(str(e))
  748. except Exception as e:
  749. self.reject_reasons.append("Processing raised an exception: {0}.\n{1}".format(e, traceback.format_exc()))
  750. return False
  751. def _install_to_suite(
  752. self,
  753. target_suite: Suite,
  754. suite: Suite,
  755. source_component_func: Callable[[daklib.upload.Source], Component],
  756. binary_component_func: Callable[[daklib.upload.Binary], Component],
  757. source_suites=None,
  758. extra_source_archives: Optional[Iterable[Archive]] = None,
  759. policy_upload: bool = False
  760. ) -> tuple[Optional[DBSource], list[DBBinary]]:
  761. """Install upload to the given suite
  762. :param target_suite: target suite (before redirection to policy queue or NEW)
  763. :param suite: suite to install the package into. This is the real suite,
  764. ie. after any redirection to NEW or a policy queue
  765. :param source_component_func: function to get the :class:`daklib.dbconn.Component`
  766. for a :class:`daklib.upload.Source` object
  767. :param binary_component_func: function to get the :class:`daklib.dbconn.Component`
  768. for a :class:`daklib.upload.Binary` object
  769. :param source_suites: see :meth:`daklib.archive.ArchiveTransaction.install_binary`
  770. :param extra_source_archives: see :meth:`daklib.archive.ArchiveTransaction.install_binary`
  771. :param policy_upload: Boolean indicating upload to policy queue (including NEW)
  772. :return: tuple with two elements. The first is a :class:`daklib.dbconn.DBSource`
  773. object for the install source or :const:`None` if no source was
  774. included. The second is a list of :class:`daklib.dbconn.DBBinary`
  775. objects for the installed binary packages.
  776. """
  777. # XXX: move this function to ArchiveTransaction?
  778. control = self.changes.changes
  779. changed_by = get_or_set_maintainer(control.get('Changed-By', control['Maintainer']), self.session)
  780. if source_suites is None:
  781. source_suites = self.session.query(Suite).join((VersionCheck, VersionCheck.reference_id == Suite.suite_id)).filter(VersionCheck.check == 'Enhances').filter(VersionCheck.suite == suite).subquery()
  782. source = self.changes.source
  783. if source is not None:
  784. component = source_component_func(source)
  785. db_source = self.transaction.install_source(
  786. self.directory,
  787. source,
  788. suite,
  789. component,
  790. changed_by,
  791. fingerprint=self.fingerprint
  792. )
  793. else:
  794. db_source = None
  795. db_binaries = []
  796. for binary in sorted(self.changes.binaries, key=lambda x: x.name):
  797. copy_to_suite = suite
  798. if daklib.utils.is_in_debug_section(binary.control) and suite.debug_suite is not None:
  799. copy_to_suite = suite.debug_suite
  800. component = binary_component_func(binary)
  801. db_binary = self.transaction.install_binary(
  802. self.directory,
  803. binary,
  804. copy_to_suite,
  805. component,
  806. fingerprint=self.fingerprint,
  807. source_suites=source_suites,
  808. extra_source_archives=extra_source_archives
  809. )
  810. db_binaries.append(db_binary)
  811. if not policy_upload:
  812. check_upload_for_external_signature_request(self.session, target_suite, copy_to_suite, db_binary)
  813. if suite.copychanges:
  814. src = os.path.join(self.directory, self.changes.filename)
  815. dst = os.path.join(suite.archive.path, 'dists', suite.suite_name, self.changes.filename)
  816. self.transaction.fs.copy(src, dst, mode=suite.archive.mode)
  817. suite.update_last_changed()
  818. return (db_source, db_binaries)
  819. def _install_changes(self) -> DBChange:
  820. assert self.changes.valid_signature
  821. control = self.changes.changes
  822. session = self.transaction.session
  823. config = Config()
  824. changelog_id = None
  825. # Only add changelog for sourceful uploads and binNMUs
  826. if self.changes.sourceful or re_bin_only_nmu.search(control['Version']):
  827. query = 'INSERT INTO changelogs_text (changelog) VALUES (:changelog) RETURNING id'
  828. changelog_id = session.execute(query, {'changelog': control['Changes']}).scalar()
  829. assert changelog_id is not None
  830. db_changes = DBChange()
  831. db_changes.changesname = self.changes.filename
  832. db_changes.source = control['Source']
  833. db_changes.binaries = control.get('Binary', None)
  834. db_changes.architecture = control['Architecture']
  835. db_changes.version = control['Version']
  836. db_changes.distribution = control['Distribution']
  837. db_changes.urgency = control['Urgency']
  838. db_changes.maintainer = control['Maintainer']
  839. db_changes.changedby = control.get('Changed-By', control['Maintainer'])
  840. db_changes.date = control['Date']
  841. db_changes.fingerprint = self.fingerprint.fingerprint
  842. db_changes.changelog_id = changelog_id
  843. db_changes.closes = self.changes.closed_bugs
  844. try:
  845. self.transaction.session.add(db_changes)
  846. self.transaction.session.flush()
  847. except sqlalchemy.exc.IntegrityError:
  848. raise ArchiveException('{0} is already known.'.format(self.changes.filename))
  849. return db_changes
  850. def _install_policy(self, policy_queue, target_suite, db_changes, db_source, db_binaries) -> PolicyQueueUpload:
  851. """install upload to policy queue"""
  852. u = PolicyQueueUpload()
  853. u.policy_queue = policy_queue
  854. u.target_suite = target_suite
  855. u.changes = db_changes
  856. u.source = db_source
  857. u.binaries = db_binaries
  858. self.transaction.session.add(u)
  859. self.transaction.session.flush()
  860. queue_files = [self.changes.filename]
  861. queue_files.extend(f.filename for f in self.changes.buildinfo_files)
  862. for fn in queue_files:
  863. src = os.path.join(self.changes.directory, fn)
  864. dst = os.path.join(policy_queue.path, fn)
  865. self.transaction.fs.copy(src, dst, mode=policy_queue.change_perms)
  866. return u
  867. def try_autobyhand(self) -> bool:
  868. """Try AUTOBYHAND
  869. Try to handle byhand packages automatically.
  870. """
  871. assert len(self.reject_reasons) == 0
  872. assert self.changes.valid_signature
  873. assert self.final_suites is not None
  874. assert self._checked
  875. byhand = self.changes.byhand_files
  876. if len(byhand) == 0:
  877. return True
  878. suites = list(self.final_suites)
  879. assert len(suites) == 1, "BYHAND uploads must be to a single suite"
  880. suite = suites[0]
  881. cnf = Config()
  882. control = self.changes.changes
  883. automatic_byhand_packages = cnf.subtree("AutomaticByHandPackages")
  884. remaining = []
  885. for f in byhand:
  886. if '_' in f.filename:
  887. parts = f.filename.split('_', 2)
  888. if len(parts) != 3:
  889. print("W: unexpected byhand filename {0}. No automatic processing.".format(f.filename))
  890. remaining.append(f)
  891. continue
  892. package, version, archext = parts
  893. arch, ext = archext.split('.', 1)
  894. else:
  895. parts = f.filename.split('.')
  896. if len(parts) < 2:
  897. print("W: unexpected byhand filename {0}. No automatic processing.".format(f.filename))
  898. remaining.append(f)
  899. continue
  900. package = parts[0]
  901. version = '0'
  902. arch = 'all'
  903. ext = parts[-1]
  904. try:
  905. rule = automatic_byhand_packages.subtree(package)
  906. except KeyError:
  907. remaining.append(f)
  908. continue
  909. if rule['Source'] != self.changes.source_name \
  910. or rule['Section'] != f.section \
  911. or ('Extension' in rule and rule['Extension'] != ext):
  912. remaining.append(f)
  913. continue
  914. script = rule['Script']
  915. retcode = subprocess.call([script, os.path.join(self.directory, f.filename), control['Version'], arch, os.path.join(self.directory, self.changes.filename), suite.suite_name], shell=False)
  916. if retcode != 0:
  917. print("W: error processing {0}.".format(f.filename))
  918. remaining.append(f)
  919. return len(remaining) == 0
  920. def _install_byhand(self, policy_queue_upload: PolicyQueueUpload, hashed_file: daklib.upload.HashedFile) -> PolicyQueueByhandFile:
  921. """install byhand file"""
  922. fs = self.transaction.fs
  923. session = self.transaction.session
  924. policy_queue = policy_queue_upload.policy_queue
  925. byhand_file = PolicyQueueByhandFile()
  926. byhand_file.upload = policy_queue_upload
  927. byhand_file.filename = hashed_file.filename
  928. session.add(byhand_file)
  929. session.flush()
  930. src = os.path.join(self.directory, hashed_file.filename)
  931. dst = os.path.join(policy_queue.path, hashed_file.filename)
  932. fs.copy(src, dst, mode=policy_queue.change_perms)
  933. return byhand_file
  934. def _do_bts_versiontracking(self) -> None:
  935. cnf = Config()
  936. fs = self.transaction.fs
  937. btsdir = cnf.get('Dir::BTSVersionTrack')
  938. if btsdir is None or btsdir == '':
  939. return
  940. base = os.path.join(btsdir, self.changes.filename[:-8])
  941. # version history
  942. sourcedir = self.unpacked_source()
  943. if sourcedir is not None:
  944. dch_path = os.path.join(sourcedir, 'debian', 'changelog')
  945. with open(dch_path, 'r') as fh:
  946. versions = fs.create("{0}.versions".format(base), mode=0o644)
  947. for line in fh.readlines():
  948. if re_changelog_versions.match(line):
  949. versions.write(line)
  950. versions.close()
  951. # binary -> source mapping
  952. if self.changes.binaries:
  953. debinfo = fs.create("{0}.debinfo".format(base), mode=0o644)
  954. for binary in self.changes.binaries:
  955. control = binary.control
  956. source_package, source_version = binary.source
  957. line = " ".join([control['Package'], control['Version'], control['Architecture'], source_package, source_version])
  958. print(line, file=debinfo)
  959. debinfo.close()
  960. def _policy_queue(self, suite) -> Optional[PolicyQueue]:
  961. if suite.policy_queue is not None:
  962. return suite.policy_queue
  963. return None
  964. def install(self) -> None:
  965. """install upload
  966. Install upload to a suite or policy queue. This method does **not**
  967. handle uploads to NEW.
  968. You need to have called the :meth:`check` method before calling this method.
  969. """
  970. assert len(self.reject_reasons) == 0
  971. assert self.changes.valid_signature
  972. assert self.final_suites is not None
  973. assert self._checked
  974. assert not self.new
  975. db_changes = self._install_changes()
  976. for suite in self.final_suites:
  977. overridesuite = suite
  978. if suite.overridesuite is not None:
  979. overridesuite = self.session.query(Suite).filter_by(suite_name=suite.overridesuite).one()
  980. policy_queue = self._policy_queue(suite)
  981. policy_upload = False
  982. redirected_suite = suite
  983. if policy_queue is not None:
  984. redirected_suite = policy_queue.suite
  985. policy_upload = True
  986. # source can be in the suite we install to or any suite we enhance
  987. source_suite_ids = set([suite.suite_id, redirected_suite.suite_id])
  988. for enhanced_suite_id, in self.session.query(VersionCheck.reference_id) \
  989. .filter(VersionCheck.suite_id.in_(source_suite_ids)) \
  990. .filter(VersionCheck.check == 'Enhances'):
  991. source_suite_ids.add(enhanced_suite_id)
  992. source_suites = self.session.query(Suite).filter(Suite.suite_id.in_(source_suite_ids)).subquery()
  993. def source_component_func(source):
  994. return self._source_component(overridesuite, source, only_overrides=False)
  995. def binary_component_func(binary):
  996. return self._binary_component(overridesuite, binary, only_overrides=False)
  997. (db_source, db_binaries) = self._install_to_suite(suite, redirected_suite, source_component_func, binary_component_func, source_suites=source_suites, extra_source_archives=[suite.archive], policy_upload=policy_upload)
  998. if policy_queue is not None:
  999. self._install_policy(policy_queue, suite, db_changes, db_source, db_binaries)
  1000. # copy to build queues
  1001. if policy_queue is None or policy_queue.send_to_build_queues:
  1002. for build_queue in suite.copy_queues:
  1003. self._install_to_suite(suite, build_queue.suite, source_component_func, binary_component_func, source_suites=source_suites, extra_source_archives=[suite.archive])
  1004. self._do_bts_versiontracking()
  1005. def install_to_new(self) -> None:
  1006. """install upload to NEW
  1007. Install upload to NEW. This method does **not** handle regular uploads
  1008. to suites or policy queues.
  1009. You need to have called the :meth:`check` method before calling this method.
  1010. """
  1011. # Uploads to NEW are special as we don't have overrides.
  1012. assert len(self.reject_reasons) == 0
  1013. assert self.changes.valid_signature
  1014. assert self.final_suites is not None
  1015. source = self.changes.source
  1016. binaries = self.changes.binaries
  1017. byhand = self.changes.byhand_files
  1018. # we need a suite to guess components
  1019. suites = list(self.final_suites)
  1020. assert len(suites) == 1, "NEW uploads must be to a single suite"
  1021. suite = suites[0]
  1022. # decide which NEW queue to use
  1023. if suite.new_queue is None:
  1024. new_queue = self.transaction.session.query(PolicyQueue).filter_by(queue_name='new').one()
  1025. else:
  1026. new_queue = suite.new_queue
  1027. if len(byhand) > 0:
  1028. # There is only one global BYHAND queue
  1029. new_queue = self.transaction.session.query(PolicyQueue).filter_by(queue_name='byhand').one()
  1030. new_suite = new_queue.suite
  1031. def binary_component_func(binary):
  1032. return self._binary_component(suite, binary, only_overrides=False)
  1033. # guess source component
  1034. # XXX: should be moved into an extra method
  1035. binary_component_names = set()
  1036. for binary in binaries:
  1037. component = binary_component_func(binary)
  1038. binary_component_names.add(component.component_name)
  1039. source_component_name = None
  1040. for c in self.session.query(Component).order_by(Component.component_id):
  1041. guess = c.component_name
  1042. if guess in binary_component_names:
  1043. source_component_name = guess
  1044. break
  1045. if source_component_name is None:
  1046. source_component = self.session.query(Component).order_by(Component.component_id).first()
  1047. else:
  1048. source_component = self.session.query(Component).filter_by(component_name=source_component_name).one()
  1049. def source_component_func(source):
  1050. return source_component
  1051. db_changes = self._install_changes()
  1052. (db_source, db_binaries) = self._install_to_suite(suite, new_suite, source_component_func, binary_component_func, source_suites=True, extra_source_archives=[suite.archive], policy_upload=True)
  1053. policy_upload = self._install_policy(new_queue, suite, db_changes, db_source, db_binaries)
  1054. for f in byhand:
  1055. self._install_byhand(policy_upload, f)
  1056. self._do_bts_versiontracking()
  1057. def commit(self) -> None:
  1058. """commit changes"""
  1059. self.transaction.commit()
  1060. def rollback(self) -> None:
  1061. """rollback changes"""
  1062. self.transaction.rollback()
  1063. def __enter__(self):
  1064. self.prepare()
  1065. return self
  1066. def __exit__(self, type, value, traceback):
  1067. if self.directory is not None:
  1068. shutil.rmtree(self.directory)
  1069. self.directory = None
  1070. self.changes = None
  1071. self.transaction.rollback()
  1072. return None