archive.py 55 KB

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