dbconn.py 77 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514
  1. """ DB access class
  2. @contact: Debian FTPMaster <ftpmaster@debian.org>
  3. @copyright: 2000, 2001, 2002, 2003, 2004, 2006 James Troup <james@nocrew.org>
  4. @copyright: 2008-2009 Mark Hymers <mhy@debian.org>
  5. @copyright: 2009, 2010 Joerg Jaspert <joerg@debian.org>
  6. @copyright: 2009 Mike O'Connor <stew@debian.org>
  7. @license: GNU General Public License version 2 or later
  8. """
  9. # This program is free software; you can redistribute it and/or modify
  10. # it under the terms of the GNU General Public License as published by
  11. # the Free Software Foundation; either version 2 of the License, or
  12. # (at your option) any later version.
  13. # This program is distributed in the hope that it will be useful,
  14. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. # GNU General Public License for more details.
  17. # You should have received a copy of the GNU General Public License
  18. # along with this program; if not, write to the Free Software
  19. # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  20. ################################################################################
  21. # < mhy> I need a funny comment
  22. # < sgran> two peanuts were walking down a dark street
  23. # < sgran> one was a-salted
  24. # * mhy looks up the definition of "funny"
  25. ################################################################################
  26. import apt_pkg
  27. from daklib.gpg import GpgException
  28. import functools
  29. import inspect
  30. import os
  31. from os.path import normpath
  32. import re
  33. import six
  34. import subprocess
  35. import warnings
  36. from debian.debfile import Deb822
  37. from tarfile import TarFile
  38. import sqlalchemy
  39. from sqlalchemy import create_engine, Table, desc
  40. from sqlalchemy.orm import sessionmaker, mapper, relation, object_session, \
  41. backref, object_mapper
  42. import sqlalchemy.types
  43. from sqlalchemy.orm.collections import attribute_mapped_collection
  44. from sqlalchemy.ext.associationproxy import association_proxy
  45. # Don't remove this, we re-export the exceptions to scripts which import us
  46. from sqlalchemy.exc import *
  47. from sqlalchemy.orm.exc import NoResultFound
  48. from .aptversion import AptVersion
  49. # Only import Config until Queue stuff is changed to store its config
  50. # in the database
  51. from .config import Config
  52. from .textutils import fix_maintainer, force_to_utf8
  53. # suppress some deprecation warnings in squeeze related to sqlalchemy
  54. warnings.filterwarnings('ignore',
  55. "Predicate of partial index .* ignored during reflection",
  56. SAWarning)
  57. from .database.base import Base
  58. ################################################################################
  59. # Patch in support for the debversion field type so that it works during
  60. # reflection
  61. class DebVersion(sqlalchemy.types.UserDefinedType):
  62. def get_col_spec(self):
  63. return "DEBVERSION"
  64. def bind_processor(self, dialect):
  65. return None
  66. def result_processor(self, dialect, coltype):
  67. return None
  68. from sqlalchemy.databases import postgresql
  69. postgresql.ischema_names['debversion'] = DebVersion
  70. ################################################################################
  71. __all__ = ['IntegrityError', 'SQLAlchemyError', 'DebVersion']
  72. ################################################################################
  73. def session_wrapper(fn):
  74. """
  75. Wrapper around common ".., session=None):" handling. If the wrapped
  76. function is called without passing 'session', we create a local one
  77. and destroy it when the function ends.
  78. Also attaches a commit_or_flush method to the session; if we created a
  79. local session, this is a synonym for session.commit(), otherwise it is a
  80. synonym for session.flush().
  81. """
  82. def wrapped(*args, **kwargs):
  83. private_transaction = False
  84. # Find the session object
  85. session = kwargs.get('session')
  86. if session is None:
  87. if len(args) < len(inspect.getfullargspec(fn).args):
  88. # No session specified as last argument or in kwargs
  89. private_transaction = True
  90. session = kwargs['session'] = DBConn().session()
  91. else:
  92. # Session is last argument in args
  93. session = args[-1]
  94. if session is None:
  95. args = list(args)
  96. session = args[-1] = DBConn().session()
  97. private_transaction = True
  98. if private_transaction:
  99. session.commit_or_flush = session.commit
  100. else:
  101. session.commit_or_flush = session.flush
  102. try:
  103. return fn(*args, **kwargs)
  104. finally:
  105. if private_transaction:
  106. # We created a session; close it.
  107. session.close()
  108. wrapped.__doc__ = fn.__doc__
  109. wrapped.__name__ = fn.__name__
  110. return wrapped
  111. __all__.append('session_wrapper')
  112. ################################################################################
  113. class ORMObject(object):
  114. """
  115. ORMObject is a base class for all ORM classes mapped by SQLalchemy. All
  116. derived classes must implement the properties() method.
  117. """
  118. def properties(self):
  119. '''
  120. This method should be implemented by all derived classes and returns a
  121. list of the important properties. The properties 'created' and
  122. 'modified' will be added automatically. A suffix '_count' should be
  123. added to properties that are lists or query objects. The most important
  124. property name should be returned as the first element in the list
  125. because it is used by repr().
  126. '''
  127. return []
  128. def classname(self):
  129. '''
  130. Returns the name of the class.
  131. '''
  132. return type(self).__name__
  133. def __repr__(self):
  134. '''
  135. Returns a short string representation of the object using the first
  136. element from the properties() method.
  137. '''
  138. primary_property = self.properties()[0]
  139. value = getattr(self, primary_property)
  140. return '<%s %s>' % (self.classname(), str(value))
  141. def __str__(self):
  142. '''
  143. Returns a human readable form of the object using the properties()
  144. method.
  145. '''
  146. return '<%s(...)>' % (self.classname())
  147. @classmethod
  148. @session_wrapper
  149. def get(cls, primary_key, session=None):
  150. '''
  151. This is a support function that allows getting an object by its primary
  152. key.
  153. Architecture.get(3[, session])
  154. instead of the more verbose
  155. session.query(Architecture).get(3)
  156. '''
  157. return session.query(cls).get(primary_key)
  158. def session(self):
  159. '''
  160. Returns the current session that is associated with the object. May
  161. return None is object is in detached state.
  162. '''
  163. return object_session(self)
  164. def clone(self, session=None):
  165. """
  166. Clones the current object in a new session and returns the new clone. A
  167. fresh session is created if the optional session parameter is not
  168. provided. The function will fail if a session is provided and has
  169. unflushed changes.
  170. RATIONALE: SQLAlchemy's session is not thread safe. This method clones
  171. an existing object to allow several threads to work with their own
  172. instances of an ORMObject.
  173. WARNING: Only persistent (committed) objects can be cloned. Changes
  174. made to the original object that are not committed yet will get lost.
  175. The session of the new object will always be rolled back to avoid
  176. resource leaks.
  177. """
  178. if self.session() is None:
  179. raise RuntimeError(
  180. 'Method clone() failed for detached object:\n%s' % self)
  181. self.session().flush()
  182. mapper = object_mapper(self)
  183. primary_key = mapper.primary_key_from_instance(self)
  184. object_class = self.__class__
  185. if session is None:
  186. session = DBConn().session()
  187. elif len(session.new) + len(session.dirty) + len(session.deleted) > 0:
  188. raise RuntimeError(
  189. 'Method clone() failed due to unflushed changes in session.')
  190. new_object = session.query(object_class).get(primary_key)
  191. session.rollback()
  192. if new_object is None:
  193. raise RuntimeError(
  194. 'Method clone() failed for non-persistent object:\n%s' % self)
  195. return new_object
  196. __all__.append('ORMObject')
  197. ################################################################################
  198. class ACL(ORMObject):
  199. def __repr__(self):
  200. return "<ACL {0}>".format(self.name)
  201. __all__.append('ACL')
  202. class ACLPerSource(ORMObject):
  203. def __repr__(self):
  204. return "<ACLPerSource acl={0} fingerprint={1} source={2} reason={3}>".format(self.acl.name, self.fingerprint.fingerprint, self.source, self.reason)
  205. __all__.append('ACLPerSource')
  206. ################################################################################
  207. from .database.architecture import Architecture
  208. __all__.append('Architecture')
  209. @session_wrapper
  210. def get_architecture(architecture, session=None):
  211. """
  212. Returns database id for given C{architecture}.
  213. @type architecture: string
  214. @param architecture: The name of the architecture
  215. @type session: Session
  216. @param session: Optional SQLA session object (a temporary one will be
  217. generated if not supplied)
  218. @rtype: Architecture
  219. @return: Architecture object for the given arch (None if not present)
  220. """
  221. q = session.query(Architecture).filter_by(arch_string=architecture)
  222. return q.one_or_none()
  223. __all__.append('get_architecture')
  224. ################################################################################
  225. class Archive(object):
  226. def __init__(self, *args, **kwargs):
  227. pass
  228. def __repr__(self):
  229. return '<Archive %s>' % self.archive_name
  230. __all__.append('Archive')
  231. @session_wrapper
  232. def get_archive(archive, session=None):
  233. """
  234. returns database id for given C{archive}.
  235. @type archive: string
  236. @param archive: the name of the arhive
  237. @type session: Session
  238. @param session: Optional SQLA session object (a temporary one will be
  239. generated if not supplied)
  240. @rtype: Archive
  241. @return: Archive object for the given name (None if not present)
  242. """
  243. archive = archive.lower()
  244. q = session.query(Archive).filter_by(archive_name=archive)
  245. return q.one_or_none()
  246. __all__.append('get_archive')
  247. ################################################################################
  248. class ArchiveFile(object):
  249. def __init__(self, archive=None, component=None, file=None):
  250. self.archive = archive
  251. self.component = component
  252. self.file = file
  253. @property
  254. def path(self):
  255. return os.path.join(self.archive.path, 'pool', self.component.component_name, self.file.filename)
  256. __all__.append('ArchiveFile')
  257. ################################################################################
  258. class BinContents(ORMObject):
  259. def __init__(self, file=None, binary=None):
  260. self.file = file
  261. self.binary = binary
  262. def properties(self):
  263. return ['file', 'binary']
  264. __all__.append('BinContents')
  265. ################################################################################
  266. class DBBinary(ORMObject):
  267. def __init__(self, package=None, source=None, version=None,
  268. maintainer=None, architecture=None, poolfile=None,
  269. binarytype='deb', fingerprint=None):
  270. self.package = package
  271. self.source = source
  272. self.version = version
  273. self.maintainer = maintainer
  274. self.architecture = architecture
  275. self.poolfile = poolfile
  276. self.binarytype = binarytype
  277. self.fingerprint = fingerprint
  278. @property
  279. def pkid(self):
  280. return self.binary_id
  281. @property
  282. def name(self):
  283. return self.package
  284. @property
  285. def arch_string(self):
  286. return "%s" % self.architecture
  287. def properties(self):
  288. return ['package', 'version', 'maintainer', 'source', 'architecture',
  289. 'poolfile', 'binarytype', 'fingerprint', 'install_date',
  290. 'suites_count', 'binary_id', 'contents_count', 'extra_sources']
  291. metadata = association_proxy('key', 'value')
  292. def scan_contents(self):
  293. '''
  294. Yields the contents of the package. Only regular files are yielded and
  295. the path names are normalized after converting them from either utf-8
  296. or iso8859-1 encoding. It yields the string ' <EMPTY PACKAGE>' if the
  297. package does not contain any regular file.
  298. '''
  299. fullpath = self.poolfile.fullpath
  300. dpkg_cmd = ('dpkg-deb', '--fsys-tarfile', fullpath)
  301. dpkg = subprocess.Popen(dpkg_cmd, stdout=subprocess.PIPE)
  302. tar = TarFile.open(fileobj=dpkg.stdout, mode='r|')
  303. for member in tar.getmembers():
  304. if not member.isdir():
  305. name = normpath(member.name)
  306. name = force_to_utf8(name)
  307. yield name
  308. tar.close()
  309. dpkg.stdout.close()
  310. dpkg.wait()
  311. def read_control(self):
  312. '''
  313. Reads the control information from a binary.
  314. @rtype: text
  315. @return: stanza text of the control section.
  316. '''
  317. from . import utils
  318. fullpath = self.poolfile.fullpath
  319. return utils.deb_extract_control(fullpath)
  320. def read_control_fields(self):
  321. '''
  322. Reads the control information from a binary and return
  323. as a dictionary.
  324. @rtype: dict
  325. @return: fields of the control section as a dictionary.
  326. '''
  327. stanza = self.read_control()
  328. return apt_pkg.TagSection(stanza)
  329. @property
  330. def proxy(self):
  331. session = object_session(self)
  332. query = session.query(BinaryMetadata).filter_by(binary=self)
  333. return MetadataProxy(session, query)
  334. __all__.append('DBBinary')
  335. @session_wrapper
  336. def get_suites_binary_in(package, session=None):
  337. """
  338. Returns list of Suite objects which given C{package} name is in
  339. @type package: str
  340. @param package: DBBinary package name to search for
  341. @rtype: list
  342. @return: list of Suite objects for the given package
  343. """
  344. return session.query(Suite).filter(Suite.binaries.any(DBBinary.package == package)).all()
  345. __all__.append('get_suites_binary_in')
  346. @session_wrapper
  347. def get_component_by_package_suite(package, suite_list, arch_list=None, session=None):
  348. '''
  349. Returns the component name of the newest binary package in suite_list or
  350. None if no package is found. The result can be optionally filtered by a list
  351. of architecture names.
  352. @type package: str
  353. @param package: DBBinary package name to search for
  354. @type suite_list: list of str
  355. @param suite_list: list of suite_name items
  356. @type arch_list: list of str
  357. @param arch_list: optional list of arch_string items that defaults to []
  358. @rtype: str or NoneType
  359. @return: name of component or None
  360. '''
  361. q = session.query(DBBinary).filter_by(package=package). \
  362. join(DBBinary.suites).filter(Suite.suite_name.in_(suite_list))
  363. if arch_list:
  364. q = q.join(DBBinary.architecture). \
  365. filter(Architecture.arch_string.in_(arch_list))
  366. binary = q.order_by(desc(DBBinary.version)).first()
  367. if binary is None:
  368. return None
  369. else:
  370. return binary.poolfile.component.component_name
  371. __all__.append('get_component_by_package_suite')
  372. ################################################################################
  373. class BuildQueue(object):
  374. def __init__(self, *args, **kwargs):
  375. pass
  376. def __repr__(self):
  377. return '<BuildQueue %s>' % self.queue_name
  378. __all__.append('BuildQueue')
  379. ################################################################################
  380. class Component(ORMObject):
  381. def __init__(self, component_name=None):
  382. self.component_name = component_name
  383. def __eq__(self, val):
  384. if isinstance(val, str):
  385. warnings.warn("comparison with a `str` is deprecated", DeprecationWarning, stacklevel=2)
  386. return (self.component_name == val)
  387. # This signals to use the normal comparison operator
  388. return NotImplemented
  389. def __ne__(self, val):
  390. if isinstance(val, str):
  391. warnings.warn("comparison with a `str` is deprecated", DeprecationWarning, stacklevel=2)
  392. return (self.component_name != val)
  393. # This signals to use the normal comparison operator
  394. return NotImplemented
  395. __hash__ = ORMObject.__hash__
  396. def properties(self):
  397. return ['component_name', 'component_id', 'description',
  398. 'meets_dfsg', 'overrides_count']
  399. __all__.append('Component')
  400. @session_wrapper
  401. def get_component(component, session=None):
  402. """
  403. Returns database id for given C{component}.
  404. @type component: string
  405. @param component: The name of the override type
  406. @rtype: int
  407. @return: the database id for the given component
  408. """
  409. component = component.lower()
  410. q = session.query(Component).filter_by(component_name=component)
  411. return q.one_or_none()
  412. __all__.append('get_component')
  413. def get_mapped_component_name(component_name):
  414. cnf = Config()
  415. for m in cnf.value_list("ComponentMappings"):
  416. (src, dst) = m.split()
  417. if component_name == src:
  418. component_name = dst
  419. return component_name
  420. __all__.append('get_mapped_component_name')
  421. @session_wrapper
  422. def get_mapped_component(component_name, session=None):
  423. """get component after mappings
  424. Evaluate component mappings from ComponentMappings in dak.conf for the
  425. given component name.
  426. @todo: ansgar wants to get rid of this. It's currently only used for
  427. the security archive
  428. @type component_name: str
  429. @param component_name: component name
  430. @param session: database session
  431. @rtype: L{daklib.dbconn.Component} or C{None}
  432. @return: component after applying maps or C{None}
  433. """
  434. component_name = get_mapped_component_name(component_name)
  435. component = session.query(Component).filter_by(component_name=component_name).first()
  436. return component
  437. __all__.append('get_mapped_component')
  438. @session_wrapper
  439. def get_component_names(session=None):
  440. """
  441. Returns list of strings of component names.
  442. @rtype: list
  443. @return: list of strings of component names
  444. """
  445. return [x.component_name for x in session.query(Component).all()]
  446. __all__.append('get_component_names')
  447. ################################################################################
  448. class DBConfig(object):
  449. def __init__(self, *args, **kwargs):
  450. pass
  451. def __repr__(self):
  452. return '<DBConfig %s>' % self.name
  453. __all__.append('DBConfig')
  454. ################################################################################
  455. class DSCFile(object):
  456. def __init__(self, *args, **kwargs):
  457. pass
  458. def __repr__(self):
  459. return '<DSCFile %s>' % self.dscfile_id
  460. __all__.append('DSCFile')
  461. @session_wrapper
  462. def get_dscfiles(dscfile_id=None, source_id=None, poolfile_id=None, session=None):
  463. """
  464. Returns a list of DSCFiles which may be empty
  465. @type dscfile_id: int (optional)
  466. @param dscfile_id: the dscfile_id of the DSCFiles to find
  467. @type source_id: int (optional)
  468. @param source_id: the source id related to the DSCFiles to find
  469. @type poolfile_id: int (optional)
  470. @param poolfile_id: the poolfile id related to the DSCFiles to find
  471. @rtype: list
  472. @return: Possibly empty list of DSCFiles
  473. """
  474. q = session.query(DSCFile)
  475. if dscfile_id is not None:
  476. q = q.filter_by(dscfile_id=dscfile_id)
  477. if source_id is not None:
  478. q = q.filter_by(source_id=source_id)
  479. if poolfile_id is not None:
  480. q = q.filter_by(poolfile_id=poolfile_id)
  481. return q.all()
  482. __all__.append('get_dscfiles')
  483. ################################################################################
  484. class ExternalOverride(ORMObject):
  485. def __init__(self, *args, **kwargs):
  486. pass
  487. def __repr__(self):
  488. return '<ExternalOverride %s = %s: %s>' % (self.package, self.key, self.value)
  489. __all__.append('ExternalOverride')
  490. ################################################################################
  491. class PoolFile(ORMObject):
  492. def __init__(self, filename=None, filesize=-1,
  493. md5sum=None):
  494. self.filename = filename
  495. self.filesize = filesize
  496. self.md5sum = md5sum
  497. @property
  498. def fullpath(self):
  499. session = DBConn().session().object_session(self)
  500. af = session.query(ArchiveFile).join(Archive) \
  501. .filter(ArchiveFile.file == self) \
  502. .order_by(Archive.tainted.desc()).first()
  503. return af.path
  504. @property
  505. def component(self):
  506. session = DBConn().session().object_session(self)
  507. component_id = session.query(ArchiveFile.component_id).filter(ArchiveFile.file == self) \
  508. .group_by(ArchiveFile.component_id).one()
  509. return session.query(Component).get(component_id)
  510. @property
  511. def basename(self):
  512. return os.path.basename(self.filename)
  513. def properties(self):
  514. return ['filename', 'file_id', 'filesize', 'md5sum', 'sha1sum',
  515. 'sha256sum', 'source', 'binary', 'last_used']
  516. __all__.append('PoolFile')
  517. ################################################################################
  518. class Fingerprint(ORMObject):
  519. def __init__(self, fingerprint=None):
  520. self.fingerprint = fingerprint
  521. def properties(self):
  522. return ['fingerprint', 'fingerprint_id', 'keyring', 'uid',
  523. 'binary_reject']
  524. __all__.append('Fingerprint')
  525. @session_wrapper
  526. def get_fingerprint(fpr, session=None):
  527. """
  528. Returns Fingerprint object for given fpr.
  529. @type fpr: string
  530. @param fpr: The fpr to find / add
  531. @type session: SQLAlchemy
  532. @param session: Optional SQL session object (a temporary one will be
  533. generated if not supplied).
  534. @rtype: Fingerprint
  535. @return: the Fingerprint object for the given fpr or None
  536. """
  537. q = session.query(Fingerprint).filter_by(fingerprint=fpr)
  538. return q.one_or_none()
  539. __all__.append('get_fingerprint')
  540. @session_wrapper
  541. def get_or_set_fingerprint(fpr, session=None):
  542. """
  543. Returns Fingerprint object for given fpr.
  544. If no matching fpr is found, a row is inserted.
  545. @type fpr: string
  546. @param fpr: The fpr to find / add
  547. @type session: SQLAlchemy
  548. @param session: Optional SQL session object (a temporary one will be
  549. generated if not supplied). If not passed, a commit will be performed at
  550. the end of the function, otherwise the caller is responsible for commiting.
  551. A flush will be performed either way.
  552. @rtype: Fingerprint
  553. @return: the Fingerprint object for the given fpr
  554. """
  555. q = session.query(Fingerprint).filter_by(fingerprint=fpr)
  556. try:
  557. ret = q.one()
  558. except NoResultFound:
  559. fingerprint = Fingerprint()
  560. fingerprint.fingerprint = fpr
  561. session.add(fingerprint)
  562. session.commit_or_flush()
  563. ret = fingerprint
  564. return ret
  565. __all__.append('get_or_set_fingerprint')
  566. ################################################################################
  567. # Helper routine for Keyring class
  568. def get_ldap_name(entry):
  569. name = []
  570. for k in ["cn", "mn", "sn"]:
  571. ret = entry.get(k)
  572. if not ret:
  573. continue
  574. value = six.ensure_str(ret[0])
  575. if value and value[0] != "-":
  576. name.append(value)
  577. return " ".join(name)
  578. ################################################################################
  579. class Keyring(object):
  580. keys = {}
  581. fpr_lookup = {}
  582. def __init__(self, *args, **kwargs):
  583. pass
  584. def __repr__(self):
  585. return '<Keyring %s>' % self.keyring_name
  586. def de_escape_gpg_str(self, txt):
  587. esclist = re.split(r'(\\x..)', txt)
  588. for x in range(1, len(esclist), 2):
  589. esclist[x] = "%c" % (int(esclist[x][2:], 16))
  590. return "".join(esclist)
  591. def parse_address(self, uid):
  592. """parses uid and returns a tuple of real name and email address"""
  593. import email.utils
  594. (name, address) = email.utils.parseaddr(uid)
  595. name = re.sub(r"\s*[(].*[)]", "", name)
  596. name = self.de_escape_gpg_str(name)
  597. if name == "":
  598. name = uid
  599. return (name, address)
  600. def load_keys(self, keyring):
  601. if not self.keyring_id:
  602. raise Exception('Must be initialized with database information')
  603. cmd = ["gpg", "--no-default-keyring", "--keyring", keyring,
  604. "--with-colons", "--fingerprint", "--fingerprint"]
  605. p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  606. key = None
  607. need_fingerprint = False
  608. for line_raw in p.stdout:
  609. try:
  610. line = six.ensure_str(line_raw)
  611. except UnicodeDecodeError:
  612. # Some old UIDs might not use UTF-8 encoding. We assume they
  613. # use latin1.
  614. line = six.ensure_str(line_raw, encoding='latin1')
  615. field = line.split(":")
  616. if field[0] == "pub":
  617. key = field[4]
  618. self.keys[key] = {}
  619. (name, addr) = self.parse_address(field[9])
  620. if "@" in addr:
  621. self.keys[key]["email"] = addr
  622. self.keys[key]["name"] = name
  623. need_fingerprint = True
  624. elif key and field[0] == "uid":
  625. (name, addr) = self.parse_address(field[9])
  626. if "email" not in self.keys[key] and "@" in addr:
  627. self.keys[key]["email"] = addr
  628. self.keys[key]["name"] = name
  629. elif need_fingerprint and field[0] == "fpr":
  630. self.keys[key]["fingerprints"] = [field[9]]
  631. self.fpr_lookup[field[9]] = key
  632. need_fingerprint = False
  633. (out, err) = p.communicate()
  634. r = p.returncode
  635. if r != 0:
  636. raise GpgException("command failed: %s\nstdout: %s\nstderr: %s\n" % (cmd, out, err))
  637. def import_users_from_ldap(self, session):
  638. from .utils import open_ldap_connection
  639. import ldap
  640. l = open_ldap_connection()
  641. cnf = Config()
  642. LDAPDn = cnf["Import-LDAP-Fingerprints::LDAPDn"]
  643. Attrs = l.search_s(LDAPDn, ldap.SCOPE_ONELEVEL,
  644. "(&(keyfingerprint=*)(supplementaryGid=%s))" % (cnf["Import-Users-From-Passwd::ValidGID"]),
  645. ["uid", "keyfingerprint", "cn", "mn", "sn"])
  646. byuid = {}
  647. byname = {}
  648. for i in Attrs:
  649. entry = i[1]
  650. uid = six.ensure_str(entry["uid"][0])
  651. name = get_ldap_name(entry)
  652. fingerprints = entry["keyFingerPrint"]
  653. keyid = None
  654. for f in fingerprints:
  655. f = six.ensure_str(f)
  656. key = self.fpr_lookup.get(f, None)
  657. if key not in self.keys:
  658. continue
  659. self.keys[key]["uid"] = uid
  660. if keyid is not None:
  661. continue
  662. keyid = get_or_set_uid(uid, session).uid_id
  663. byuid[keyid] = (uid, name)
  664. byname[uid] = (keyid, name)
  665. return (byname, byuid)
  666. def generate_users_from_keyring(self, format, session):
  667. byuid = {}
  668. byname = {}
  669. any_invalid = False
  670. for x in list(self.keys.keys()):
  671. if "email" not in self.keys[x]:
  672. any_invalid = True
  673. self.keys[x]["uid"] = format % "invalid-uid"
  674. else:
  675. uid = format % self.keys[x]["email"]
  676. keyid = get_or_set_uid(uid, session).uid_id
  677. byuid[keyid] = (uid, self.keys[x]["name"])
  678. byname[uid] = (keyid, self.keys[x]["name"])
  679. self.keys[x]["uid"] = uid
  680. if any_invalid:
  681. uid = format % "invalid-uid"
  682. keyid = get_or_set_uid(uid, session).uid_id
  683. byuid[keyid] = (uid, "ungeneratable user id")
  684. byname[uid] = (keyid, "ungeneratable user id")
  685. return (byname, byuid)
  686. __all__.append('Keyring')
  687. @session_wrapper
  688. def get_keyring(keyring, session=None):
  689. """
  690. If C{keyring} does not have an entry in the C{keyrings} table yet, return None
  691. If C{keyring} already has an entry, simply return the existing Keyring
  692. @type keyring: string
  693. @param keyring: the keyring name
  694. @rtype: Keyring
  695. @return: the Keyring object for this keyring
  696. """
  697. q = session.query(Keyring).filter_by(keyring_name=keyring)
  698. return q.one_or_none()
  699. __all__.append('get_keyring')
  700. @session_wrapper
  701. def get_active_keyring_paths(session=None):
  702. """
  703. @rtype: list
  704. @return: list of active keyring paths
  705. """
  706. return [x.keyring_name for x in session.query(Keyring).filter(Keyring.active == True).order_by(desc(Keyring.priority)).all()] # noqa:E712
  707. __all__.append('get_active_keyring_paths')
  708. ################################################################################
  709. class DBChange(object):
  710. def __init__(self, *args, **kwargs):
  711. pass
  712. def __repr__(self):
  713. return '<DBChange %s>' % self.changesname
  714. __all__.append('DBChange')
  715. @session_wrapper
  716. def get_dbchange(filename, session=None):
  717. """
  718. returns DBChange object for given C{filename}.
  719. @type filename: string
  720. @param filename: the name of the file
  721. @type session: Session
  722. @param session: Optional SQLA session object (a temporary one will be
  723. generated if not supplied)
  724. @rtype: DBChange
  725. @return: DBChange object for the given filename (C{None} if not present)
  726. """
  727. q = session.query(DBChange).filter_by(changesname=filename)
  728. return q.one_or_none()
  729. __all__.append('get_dbchange')
  730. ################################################################################
  731. class Maintainer(ORMObject):
  732. def __init__(self, name=None):
  733. self.name = name
  734. def properties(self):
  735. return ['name', 'maintainer_id']
  736. def get_split_maintainer(self):
  737. if not hasattr(self, 'name') or self.name is None:
  738. return ('', '', '', '')
  739. return fix_maintainer(self.name.strip())
  740. __all__.append('Maintainer')
  741. @session_wrapper
  742. def get_or_set_maintainer(name, session=None):
  743. """
  744. Returns Maintainer object for given maintainer name.
  745. If no matching maintainer name is found, a row is inserted.
  746. @type name: string
  747. @param name: The maintainer name to add
  748. @type session: SQLAlchemy
  749. @param session: Optional SQL session object (a temporary one will be
  750. generated if not supplied). If not passed, a commit will be performed at
  751. the end of the function, otherwise the caller is responsible for commiting.
  752. A flush will be performed either way.
  753. @rtype: Maintainer
  754. @return: the Maintainer object for the given maintainer
  755. """
  756. q = session.query(Maintainer).filter_by(name=name)
  757. try:
  758. ret = q.one()
  759. except NoResultFound:
  760. maintainer = Maintainer()
  761. maintainer.name = name
  762. session.add(maintainer)
  763. session.commit_or_flush()
  764. ret = maintainer
  765. return ret
  766. __all__.append('get_or_set_maintainer')
  767. @session_wrapper
  768. def get_maintainer(maintainer_id, session=None):
  769. """
  770. Return the name of the maintainer behind C{maintainer_id} or None if that
  771. maintainer_id is invalid.
  772. @type maintainer_id: int
  773. @param maintainer_id: the id of the maintainer
  774. @rtype: Maintainer
  775. @return: the Maintainer with this C{maintainer_id}
  776. """
  777. return session.query(Maintainer).get(maintainer_id)
  778. __all__.append('get_maintainer')
  779. ################################################################################
  780. class NewComment(object):
  781. def __init__(self, *args, **kwargs):
  782. pass
  783. def __repr__(self):
  784. return '''<NewComment for '%s %s' (%s)>''' % (self.package, self.version, self.comment_id)
  785. __all__.append('NewComment')
  786. @session_wrapper
  787. def has_new_comment(policy_queue, package, version, session=None):
  788. """
  789. Returns true if the given combination of C{package}, C{version} has a comment.
  790. @type package: string
  791. @param package: name of the package
  792. @type version: string
  793. @param version: package version
  794. @type session: Session
  795. @param session: Optional SQLA session object (a temporary one will be
  796. generated if not supplied)
  797. @rtype: boolean
  798. @return: true/false
  799. """
  800. q = session.query(NewComment).filter_by(policy_queue=policy_queue)
  801. q = q.filter_by(package=package)
  802. q = q.filter_by(version=version)
  803. return bool(q.count() > 0)
  804. __all__.append('has_new_comment')
  805. @session_wrapper
  806. def get_new_comments(policy_queue, package=None, version=None, comment_id=None, session=None):
  807. """
  808. Returns (possibly empty) list of NewComment objects for the given
  809. parameters
  810. @type package: string (optional)
  811. @param package: name of the package
  812. @type version: string (optional)
  813. @param version: package version
  814. @type comment_id: int (optional)
  815. @param comment_id: An id of a comment
  816. @type session: Session
  817. @param session: Optional SQLA session object (a temporary one will be
  818. generated if not supplied)
  819. @rtype: list
  820. @return: A (possibly empty) list of NewComment objects will be returned
  821. """
  822. q = session.query(NewComment).filter_by(policy_queue=policy_queue)
  823. if package is not None:
  824. q = q.filter_by(package=package)
  825. if version is not None:
  826. q = q.filter_by(version=version)
  827. if comment_id is not None:
  828. q = q.filter_by(comment_id=comment_id)
  829. return q.all()
  830. __all__.append('get_new_comments')
  831. ################################################################################
  832. class Override(ORMObject):
  833. def __init__(self, package=None, suite=None, component=None, overridetype=None,
  834. section=None, priority=None):
  835. self.package = package
  836. self.suite = suite
  837. self.component = component
  838. self.overridetype = overridetype
  839. self.section = section
  840. self.priority = priority
  841. def properties(self):
  842. return ['package', 'suite', 'component', 'overridetype', 'section',
  843. 'priority']
  844. __all__.append('Override')
  845. @session_wrapper
  846. def get_override(package, suite=None, component=None, overridetype=None, session=None):
  847. """
  848. Returns Override object for the given parameters
  849. @type package: string
  850. @param package: The name of the package
  851. @type suite: string, list or None
  852. @param suite: The name of the suite (or suites if a list) to limit to. If
  853. None, don't limit. Defaults to None.
  854. @type component: string, list or None
  855. @param component: The name of the component (or components if a list) to
  856. limit to. If None, don't limit. Defaults to None.
  857. @type overridetype: string, list or None
  858. @param overridetype: The name of the overridetype (or overridetypes if a list) to
  859. limit to. If None, don't limit. Defaults to None.
  860. @type session: Session
  861. @param session: Optional SQLA session object (a temporary one will be
  862. generated if not supplied)
  863. @rtype: list
  864. @return: A (possibly empty) list of Override objects will be returned
  865. """
  866. q = session.query(Override)
  867. q = q.filter_by(package=package)
  868. if suite is not None:
  869. if not isinstance(suite, list):
  870. suite = [suite]
  871. q = q.join(Suite).filter(Suite.suite_name.in_(suite))
  872. if component is not None:
  873. if not isinstance(component, list):
  874. component = [component]
  875. q = q.join(Component).filter(Component.component_name.in_(component))
  876. if overridetype is not None:
  877. if not isinstance(overridetype, list):
  878. overridetype = [overridetype]
  879. q = q.join(OverrideType).filter(OverrideType.overridetype.in_(overridetype))
  880. return q.all()
  881. __all__.append('get_override')
  882. ################################################################################
  883. class OverrideType(ORMObject):
  884. def __init__(self, overridetype=None):
  885. self.overridetype = overridetype
  886. def properties(self):
  887. return ['overridetype', 'overridetype_id', 'overrides_count']
  888. __all__.append('OverrideType')
  889. @session_wrapper
  890. def get_override_type(override_type, session=None):
  891. """
  892. Returns OverrideType object for given C{override type}.
  893. @type override_type: string
  894. @param override_type: The name of the override type
  895. @type session: Session
  896. @param session: Optional SQLA session object (a temporary one will be
  897. generated if not supplied)
  898. @rtype: int
  899. @return: the database id for the given override type
  900. """
  901. q = session.query(OverrideType).filter_by(overridetype=override_type)
  902. return q.one_or_none()
  903. __all__.append('get_override_type')
  904. ################################################################################
  905. class PolicyQueue(object):
  906. def __init__(self, *args, **kwargs):
  907. pass
  908. def __repr__(self):
  909. return '<PolicyQueue %s>' % self.queue_name
  910. __all__.append('PolicyQueue')
  911. @session_wrapper
  912. def get_policy_queue(queuename, session=None):
  913. """
  914. Returns PolicyQueue object for given C{queue name}
  915. @type queuename: string
  916. @param queuename: The name of the queue
  917. @type session: Session
  918. @param session: Optional SQLA session object (a temporary one will be
  919. generated if not supplied)
  920. @rtype: PolicyQueue
  921. @return: PolicyQueue object for the given queue
  922. """
  923. q = session.query(PolicyQueue).filter_by(queue_name=queuename)
  924. return q.one_or_none()
  925. __all__.append('get_policy_queue')
  926. ################################################################################
  927. @functools.total_ordering
  928. class PolicyQueueUpload(object):
  929. def _key(self):
  930. return (
  931. self.changes.source,
  932. AptVersion(self.changes.version),
  933. self.source is None,
  934. self.changes.changesname
  935. )
  936. def __eq__(self, other):
  937. return self._key() == other._key()
  938. def __lt__(self, other):
  939. return self._key() < other._key()
  940. __all__.append('PolicyQueueUpload')
  941. ################################################################################
  942. class PolicyQueueByhandFile(object):
  943. pass
  944. __all__.append('PolicyQueueByhandFile')
  945. ################################################################################
  946. class Priority(ORMObject):
  947. def __init__(self, priority=None, level=None):
  948. self.priority = priority
  949. self.level = level
  950. def properties(self):
  951. return ['priority', 'priority_id', 'level', 'overrides_count']
  952. def __eq__(self, val):
  953. if isinstance(val, str):
  954. warnings.warn("comparison with a `str` is deprecated", DeprecationWarning, stacklevel=2)
  955. return (self.priority == val)
  956. # This signals to use the normal comparison operator
  957. return NotImplemented
  958. def __ne__(self, val):
  959. if isinstance(val, str):
  960. warnings.warn("comparison with a `str` is deprecated", DeprecationWarning, stacklevel=2)
  961. return (self.priority != val)
  962. # This signals to use the normal comparison operator
  963. return NotImplemented
  964. __hash__ = ORMObject.__hash__
  965. __all__.append('Priority')
  966. @session_wrapper
  967. def get_priority(priority, session=None):
  968. """
  969. Returns Priority object for given C{priority name}.
  970. @type priority: string
  971. @param priority: The name of the priority
  972. @type session: Session
  973. @param session: Optional SQLA session object (a temporary one will be
  974. generated if not supplied)
  975. @rtype: Priority
  976. @return: Priority object for the given priority
  977. """
  978. q = session.query(Priority).filter_by(priority=priority)
  979. return q.one_or_none()
  980. __all__.append('get_priority')
  981. @session_wrapper
  982. def get_priorities(session=None):
  983. """
  984. Returns dictionary of priority names -> id mappings
  985. @type session: Session
  986. @param session: Optional SQL session object (a temporary one will be
  987. generated if not supplied)
  988. @rtype: dictionary
  989. @return: dictionary of priority names -> id mappings
  990. """
  991. ret = {}
  992. q = session.query(Priority)
  993. for x in q.all():
  994. ret[x.priority] = x.priority_id
  995. return ret
  996. __all__.append('get_priorities')
  997. ################################################################################
  998. from .database.section import Section
  999. __all__.append('Section')
  1000. @session_wrapper
  1001. def get_section(section, session=None):
  1002. """
  1003. Returns Section object for given C{section name}.
  1004. @type section: string
  1005. @param section: The name of the section
  1006. @type session: Session
  1007. @param session: Optional SQLA session object (a temporary one will be
  1008. generated if not supplied)
  1009. @rtype: Section
  1010. @return: Section object for the given section name
  1011. """
  1012. q = session.query(Section).filter_by(section=section)
  1013. return q.one_or_none()
  1014. __all__.append('get_section')
  1015. @session_wrapper
  1016. def get_sections(session=None):
  1017. """
  1018. Returns dictionary of section names -> id mappings
  1019. @type session: Session
  1020. @param session: Optional SQL session object (a temporary one will be
  1021. generated if not supplied)
  1022. @rtype: dictionary
  1023. @return: dictionary of section names -> id mappings
  1024. """
  1025. ret = {}
  1026. q = session.query(Section)
  1027. for x in q.all():
  1028. ret[x.section] = x.section_id
  1029. return ret
  1030. __all__.append('get_sections')
  1031. ################################################################################
  1032. class SignatureHistory(ORMObject):
  1033. @classmethod
  1034. def from_signed_file(cls, signed_file):
  1035. """signature history entry from signed file
  1036. @type signed_file: L{daklib.gpg.SignedFile}
  1037. @param signed_file: signed file
  1038. @rtype: L{SignatureHistory}
  1039. """
  1040. self = cls()
  1041. self.fingerprint = signed_file.primary_fingerprint
  1042. self.signature_timestamp = signed_file.signature_timestamp
  1043. self.contents_sha1 = signed_file.contents_sha1()
  1044. return self
  1045. def query(self, session):
  1046. return session.query(SignatureHistory).filter_by(fingerprint=self.fingerprint, signature_timestamp=self.signature_timestamp, contents_sha1=self.contents_sha1).first()
  1047. __all__.append('SignatureHistory')
  1048. ################################################################################
  1049. class SrcContents(ORMObject):
  1050. def __init__(self, file=None, source=None):
  1051. self.file = file
  1052. self.source = source
  1053. def properties(self):
  1054. return ['file', 'source']
  1055. __all__.append('SrcContents')
  1056. ################################################################################
  1057. class DBSource(ORMObject):
  1058. def __init__(self, source=None, version=None, maintainer=None,
  1059. changedby=None, poolfile=None, install_date=None, fingerprint=None):
  1060. self.source = source
  1061. self.version = version
  1062. self.maintainer = maintainer
  1063. self.changedby = changedby
  1064. self.poolfile = poolfile
  1065. self.install_date = install_date
  1066. self.fingerprint = fingerprint
  1067. @property
  1068. def pkid(self):
  1069. return self.source_id
  1070. @property
  1071. def name(self):
  1072. return self.source
  1073. @property
  1074. def arch_string(self):
  1075. return 'source'
  1076. def properties(self):
  1077. return ['source', 'source_id', 'maintainer', 'changedby',
  1078. 'fingerprint', 'poolfile', 'version', 'suites_count',
  1079. 'install_date', 'binaries_count', 'uploaders_count']
  1080. def read_control_fields(self):
  1081. '''
  1082. Reads the control information from a dsc
  1083. @rtype: tuple
  1084. @return: fields is the dsc information in a dictionary form
  1085. '''
  1086. with open(self.poolfile.fullpath, 'r') as fd:
  1087. fields = Deb822(fd)
  1088. return fields
  1089. metadata = association_proxy('key', 'value')
  1090. def scan_contents(self):
  1091. '''
  1092. Returns a set of names for non directories. The path names are
  1093. normalized after converting them from either utf-8 or iso8859-1
  1094. encoding.
  1095. '''
  1096. fullpath = self.poolfile.fullpath
  1097. from daklib.contents import UnpackedSource
  1098. unpacked = UnpackedSource(fullpath)
  1099. fileset = set()
  1100. for name in unpacked.get_all_filenames():
  1101. name = force_to_utf8(name)
  1102. fileset.add(name)
  1103. return fileset
  1104. @property
  1105. def proxy(self):
  1106. session = object_session(self)
  1107. query = session.query(SourceMetadata).filter_by(source=self)
  1108. return MetadataProxy(session, query)
  1109. __all__.append('DBSource')
  1110. @session_wrapper
  1111. def get_suites_source_in(source, session=None):
  1112. """
  1113. Returns list of Suite objects which given C{source} name is in
  1114. @type source: str
  1115. @param source: DBSource package name to search for
  1116. @rtype: list
  1117. @return: list of Suite objects for the given source
  1118. """
  1119. return session.query(Suite).filter(Suite.sources.any(source=source)).all()
  1120. __all__.append('get_suites_source_in')
  1121. # FIXME: This function fails badly if it finds more than 1 source package and
  1122. # its implementation is trivial enough to be inlined.
  1123. @session_wrapper
  1124. def get_source_in_suite(source, suite_name, session=None):
  1125. """
  1126. Returns a DBSource object for a combination of C{source} and C{suite_name}.
  1127. - B{source} - source package name, eg. I{mailfilter}, I{bbdb}, I{glibc}
  1128. - B{suite_name} - a suite name, eg. I{unstable}
  1129. @type source: string
  1130. @param source: source package name
  1131. @type suite_name: string
  1132. @param suite_name: the suite name
  1133. @rtype: string
  1134. @return: the version for I{source} in I{suite}
  1135. """
  1136. suite = get_suite(suite_name, session)
  1137. if suite is None:
  1138. return None
  1139. return suite.get_sources(source).one_or_none()
  1140. __all__.append('get_source_in_suite')
  1141. @session_wrapper
  1142. def import_metadata_into_db(obj, session=None):
  1143. """
  1144. This routine works on either DBBinary or DBSource objects and imports
  1145. their metadata into the database
  1146. """
  1147. fields = obj.read_control_fields()
  1148. for k in fields.keys():
  1149. try:
  1150. # Try raw ASCII
  1151. val = str(fields[k])
  1152. except UnicodeEncodeError:
  1153. # Fall back to UTF-8
  1154. try:
  1155. val = fields[k].encode('utf-8')
  1156. except UnicodeEncodeError:
  1157. # Finally try iso8859-1
  1158. val = fields[k].encode('iso8859-1')
  1159. # Otherwise we allow the exception to percolate up and we cause
  1160. # a reject as someone is playing silly buggers
  1161. obj.metadata[get_or_set_metadatakey(k, session)] = val
  1162. session.commit_or_flush()
  1163. __all__.append('import_metadata_into_db')
  1164. ################################################################################
  1165. class SrcFormat(object):
  1166. def __init__(self, *args, **kwargs):
  1167. pass
  1168. def __repr__(self):
  1169. return '<SrcFormat %s>' % (self.format_name)
  1170. __all__.append('SrcFormat')
  1171. ################################################################################
  1172. SUITE_FIELDS = [('SuiteName', 'suite_name'),
  1173. ('SuiteID', 'suite_id'),
  1174. ('Version', 'version'),
  1175. ('Origin', 'origin'),
  1176. ('Label', 'label'),
  1177. ('Description', 'description'),
  1178. ('Untouchable', 'untouchable'),
  1179. ('Announce', 'announce'),
  1180. ('Codename', 'codename'),
  1181. ('OverrideCodename', 'overridecodename'),
  1182. ('ValidTime', 'validtime'),
  1183. ('Priority', 'priority'),
  1184. ('NotAutomatic', 'notautomatic'),
  1185. ('CopyChanges', 'copychanges'),
  1186. ('OverrideSuite', 'overridesuite')]
  1187. # Why the heck don't we have any UNIQUE constraints in table suite?
  1188. # TODO: Add UNIQUE constraints for appropriate columns.
  1189. class Suite(ORMObject):
  1190. def __init__(self, suite_name=None, version=None):
  1191. self.suite_name = suite_name
  1192. self.version = version
  1193. def properties(self):
  1194. return ['suite_name', 'version', 'sources_count', 'binaries_count',
  1195. 'overrides_count']
  1196. def __eq__(self, val):
  1197. if isinstance(val, str):
  1198. warnings.warn("comparison with a `str` is deprecated", DeprecationWarning, stacklevel=2)
  1199. return (self.suite_name == val)
  1200. # This signals to use the normal comparison operator
  1201. return NotImplemented
  1202. def __ne__(self, val):
  1203. if isinstance(val, str):
  1204. warnings.warn("comparison with a `str` is deprecated", DeprecationWarning, stacklevel=2)
  1205. return (self.suite_name != val)
  1206. # This signals to use the normal comparison operator
  1207. return NotImplemented
  1208. __hash__ = ORMObject.__hash__
  1209. def details(self):
  1210. ret = []
  1211. for disp, field in SUITE_FIELDS:
  1212. val = getattr(self, field, None)
  1213. if val is not None:
  1214. ret.append("%s: %s" % (disp, val))
  1215. return "\n".join(ret)
  1216. def get_architectures(self, skipsrc=False, skipall=False):
  1217. """
  1218. Returns list of Architecture objects
  1219. @type skipsrc: boolean
  1220. @param skipsrc: Whether to skip returning the 'source' architecture entry
  1221. (Default False)
  1222. @type skipall: boolean
  1223. @param skipall: Whether to skip returning the 'all' architecture entry
  1224. (Default False)
  1225. @rtype: list
  1226. @return: list of Architecture objects for the given name (may be empty)
  1227. """
  1228. q = object_session(self).query(Architecture).with_parent(self)
  1229. if skipsrc:
  1230. q = q.filter(Architecture.arch_string != 'source')
  1231. if skipall:
  1232. q = q.filter(Architecture.arch_string != 'all')
  1233. return q.order_by(Architecture.arch_string).all()
  1234. def get_sources(self, source):
  1235. """
  1236. Returns a query object representing DBSource that is part of C{suite}.
  1237. - B{source} - source package name, eg. I{mailfilter}, I{bbdb}, I{glibc}
  1238. @type source: string
  1239. @param source: source package name
  1240. @rtype: sqlalchemy.orm.query.Query
  1241. @return: a query of DBSource
  1242. """
  1243. session = object_session(self)
  1244. return session.query(DBSource).filter_by(source=source). \
  1245. with_parent(self)
  1246. def get_overridesuite(self):
  1247. if self.overridesuite is None:
  1248. return self
  1249. else:
  1250. return object_session(self).query(Suite).filter_by(suite_name=self.overridesuite).one()
  1251. def update_last_changed(self):
  1252. self.last_changed = sqlalchemy.func.now()
  1253. @property
  1254. def path(self):
  1255. return os.path.join(self.archive.path, 'dists', self.suite_name)
  1256. @property
  1257. def release_suite_output(self):
  1258. if self.release_suite is not None:
  1259. return self.release_suite
  1260. return self.suite_name
  1261. __all__.append('Suite')
  1262. @session_wrapper
  1263. def get_suite(suite, session=None):
  1264. """
  1265. Returns Suite object for given C{suite name}.
  1266. @type suite: string
  1267. @param suite: The name of the suite
  1268. @type session: Session
  1269. @param session: Optional SQLA session object (a temporary one will be
  1270. generated if not supplied)
  1271. @rtype: Suite
  1272. @return: Suite object for the requested suite name (None if not present)
  1273. """
  1274. # Start by looking for the dak internal name
  1275. q = session.query(Suite).filter_by(suite_name=suite)
  1276. try:
  1277. return q.one()
  1278. except NoResultFound:
  1279. pass
  1280. # Now try codename
  1281. q = session.query(Suite).filter_by(codename=suite)
  1282. try:
  1283. return q.one()
  1284. except NoResultFound:
  1285. pass
  1286. # Finally give release_suite a try
  1287. q = session.query(Suite).filter_by(release_suite=suite)
  1288. return q.one_or_none()
  1289. __all__.append('get_suite')
  1290. ################################################################################
  1291. @session_wrapper
  1292. def get_suite_architectures(suite, skipsrc=False, skipall=False, session=None):
  1293. """
  1294. Returns list of Architecture objects for given C{suite} name. The list is
  1295. empty if suite does not exist.
  1296. @type suite: str
  1297. @param suite: Suite name to search for
  1298. @type skipsrc: boolean
  1299. @param skipsrc: Whether to skip returning the 'source' architecture entry
  1300. (Default False)
  1301. @type skipall: boolean
  1302. @param skipall: Whether to skip returning the 'all' architecture entry
  1303. (Default False)
  1304. @type session: Session
  1305. @param session: Optional SQL session object (a temporary one will be
  1306. generated if not supplied)
  1307. @rtype: list
  1308. @return: list of Architecture objects for the given name (may be empty)
  1309. """
  1310. try:
  1311. return get_suite(suite, session).get_architectures(skipsrc, skipall)
  1312. except AttributeError:
  1313. return []
  1314. __all__.append('get_suite_architectures')
  1315. ################################################################################
  1316. class Uid(ORMObject):
  1317. def __init__(self, uid=None, name=None):
  1318. self.uid = uid
  1319. self.name = name
  1320. def __eq__(self, val):
  1321. if isinstance(val, str):
  1322. warnings.warn("comparison with a `str` is deprecated", DeprecationWarning, stacklevel=2)
  1323. return (self.uid == val)
  1324. # This signals to use the normal comparison operator
  1325. return NotImplemented
  1326. def __ne__(self, val):
  1327. if isinstance(val, str):
  1328. warnings.warn("comparison with a `str` is deprecated", DeprecationWarning, stacklevel=2)
  1329. return (self.uid != val)
  1330. # This signals to use the normal comparison operator
  1331. return NotImplemented
  1332. __hash__ = ORMObject.__hash__
  1333. def properties(self):
  1334. return ['uid', 'name', 'fingerprint']
  1335. __all__.append('Uid')
  1336. @session_wrapper
  1337. def get_or_set_uid(uidname, session=None):
  1338. """
  1339. Returns uid object for given uidname.
  1340. If no matching uidname is found, a row is inserted.
  1341. @type uidname: string
  1342. @param uidname: The uid to add
  1343. @type session: SQLAlchemy
  1344. @param session: Optional SQL session object (a temporary one will be
  1345. generated if not supplied). If not passed, a commit will be performed at
  1346. the end of the function, otherwise the caller is responsible for commiting.
  1347. @rtype: Uid
  1348. @return: the uid object for the given uidname
  1349. """
  1350. q = session.query(Uid).filter_by(uid=uidname)
  1351. try:
  1352. ret = q.one()
  1353. except NoResultFound:
  1354. uid = Uid()
  1355. uid.uid = uidname
  1356. session.add(uid)
  1357. session.commit_or_flush()
  1358. ret = uid
  1359. return ret
  1360. __all__.append('get_or_set_uid')
  1361. @session_wrapper
  1362. def get_uid_from_fingerprint(fpr, session=None):
  1363. q = session.query(Uid)
  1364. q = q.join(Fingerprint).filter_by(fingerprint=fpr)
  1365. return q.one_or_none()
  1366. __all__.append('get_uid_from_fingerprint')
  1367. ################################################################################
  1368. class MetadataKey(ORMObject):
  1369. def __init__(self, key=None):
  1370. self.key = key
  1371. def properties(self):
  1372. return ['key']
  1373. __all__.append('MetadataKey')
  1374. @session_wrapper
  1375. def get_or_set_metadatakey(keyname, session=None):
  1376. """
  1377. Returns MetadataKey object for given uidname.
  1378. If no matching keyname is found, a row is inserted.
  1379. @type keyname: string
  1380. @param keyname: The keyname to add
  1381. @type session: SQLAlchemy
  1382. @param session: Optional SQL session object (a temporary one will be
  1383. generated if not supplied). If not passed, a commit will be performed at
  1384. the end of the function, otherwise the caller is responsible for commiting.
  1385. @rtype: MetadataKey
  1386. @return: the metadatakey object for the given keyname
  1387. """
  1388. q = session.query(MetadataKey).filter_by(key=keyname)
  1389. try:
  1390. ret = q.one()
  1391. except NoResultFound:
  1392. ret = MetadataKey(keyname)
  1393. session.add(ret)
  1394. session.commit_or_flush()
  1395. return ret
  1396. __all__.append('get_or_set_metadatakey')
  1397. ################################################################################
  1398. class BinaryMetadata(ORMObject):
  1399. def __init__(self, key=None, value=None, binary=None):
  1400. self.key = key
  1401. self.value = value
  1402. if binary is not None:
  1403. self.binary = binary
  1404. def properties(self):
  1405. return ['binary', 'key', 'value']
  1406. __all__.append('BinaryMetadata')
  1407. ################################################################################
  1408. class SourceMetadata(ORMObject):
  1409. def __init__(self, key=None, value=None, source=None):
  1410. self.key = key
  1411. self.value = value
  1412. if source is not None:
  1413. self.source = source
  1414. def properties(self):
  1415. return ['source', 'key', 'value']
  1416. __all__.append('SourceMetadata')
  1417. ################################################################################
  1418. class MetadataProxy(object):
  1419. def __init__(self, session, query):
  1420. self.session = session
  1421. self.query = query
  1422. def _get(self, key):
  1423. metadata_key = self.session.query(MetadataKey).filter_by(key=key).first()
  1424. if metadata_key is None:
  1425. return None
  1426. metadata = self.query.filter_by(key=metadata_key).first()
  1427. return metadata
  1428. def __contains__(self, key):
  1429. if self._get(key) is not None:
  1430. return True
  1431. return False
  1432. def __getitem__(self, key):
  1433. metadata = self._get(key)
  1434. if metadata is None:
  1435. raise KeyError
  1436. return metadata.value
  1437. def get(self, key, default=None):
  1438. try:
  1439. return self[key]
  1440. except KeyError:
  1441. return default
  1442. ################################################################################
  1443. class VersionCheck(ORMObject):
  1444. def __init__(self, *args, **kwargs):
  1445. pass
  1446. def properties(self):
  1447. return ['check']
  1448. __all__.append('VersionCheck')
  1449. @session_wrapper
  1450. def get_version_checks(suite_name, check=None, session=None):
  1451. suite = get_suite(suite_name, session)
  1452. if not suite:
  1453. # Make sure that what we return is iterable so that list comprehensions
  1454. # involving this don't cause a traceback
  1455. return []
  1456. q = session.query(VersionCheck).filter_by(suite=suite)
  1457. if check:
  1458. q = q.filter_by(check=check)
  1459. return q.all()
  1460. __all__.append('get_version_checks')
  1461. ################################################################################
  1462. class DBConn(object):
  1463. """
  1464. database module init.
  1465. """
  1466. __shared_state = {}
  1467. db_meta = None
  1468. tbl_architecture = Architecture.__table__
  1469. tables = (
  1470. 'acl',
  1471. 'acl_architecture_map',
  1472. 'acl_fingerprint_map',
  1473. 'acl_per_source',
  1474. 'archive',
  1475. 'bin_associations',
  1476. 'bin_contents',
  1477. 'binaries',
  1478. 'binaries_metadata',
  1479. 'build_queue',
  1480. 'changelogs_text',
  1481. 'changes',
  1482. 'component',
  1483. 'component_suite',
  1484. 'config',
  1485. 'dsc_files',
  1486. 'external_files',
  1487. 'external_overrides',
  1488. 'external_signature_requests',
  1489. 'extra_src_references',
  1490. 'files',
  1491. 'files_archive_map',
  1492. 'fingerprint',
  1493. 'hashfile',
  1494. 'keyrings',
  1495. 'maintainer',
  1496. 'metadata_keys',
  1497. 'new_comments',
  1498. # TODO: the maintainer column in table override should be removed.
  1499. 'override',
  1500. 'override_type',
  1501. 'policy_queue',
  1502. 'policy_queue_upload',
  1503. 'policy_queue_upload_binaries_map',
  1504. 'policy_queue_byhand_file',
  1505. 'priority',
  1506. 'signature_history',
  1507. 'source',
  1508. 'source_metadata',
  1509. 'src_associations',
  1510. 'src_contents',
  1511. 'src_format',
  1512. 'src_uploaders',
  1513. 'suite',
  1514. 'suite_acl_map',
  1515. 'suite_architectures',
  1516. 'suite_build_queue_copy',
  1517. 'suite_permission',
  1518. 'suite_src_formats',
  1519. 'uid',
  1520. 'version_check',
  1521. )
  1522. views = (
  1523. 'bin_associations_binaries',
  1524. 'changelogs',
  1525. 'newest_source',
  1526. 'newest_src_association',
  1527. 'package_list',
  1528. 'source_suite',
  1529. 'src_associations_src',
  1530. )
  1531. def __init__(self, *args, **kwargs):
  1532. self.__dict__ = self.__shared_state
  1533. if not getattr(self, 'initialised', False):
  1534. self.initialised = True
  1535. self.debug = 'debug' in kwargs
  1536. self.__createconn()
  1537. def __setuptables(self):
  1538. for table_name in self.tables:
  1539. table = Table(table_name, self.db_meta,
  1540. autoload=True, extend_existing=True)
  1541. setattr(self, 'tbl_%s' % table_name, table)
  1542. for view_name in self.views:
  1543. view = Table(view_name, self.db_meta, autoload=True)
  1544. setattr(self, 'view_%s' % view_name, view)
  1545. def __setupmappers(self):
  1546. mapper(ACL, self.tbl_acl,
  1547. properties=dict(
  1548. architectures=relation(Architecture, secondary=self.tbl_acl_architecture_map, collection_class=set),
  1549. fingerprints=relation(Fingerprint, secondary=self.tbl_acl_fingerprint_map, collection_class=set),
  1550. match_keyring=relation(Keyring, primaryjoin=(self.tbl_acl.c.match_keyring_id == self.tbl_keyrings.c.id)),
  1551. per_source=relation(ACLPerSource, collection_class=set),
  1552. ))
  1553. mapper(ACLPerSource, self.tbl_acl_per_source,
  1554. properties=dict(
  1555. acl=relation(ACL),
  1556. fingerprint=relation(Fingerprint, primaryjoin=(self.tbl_acl_per_source.c.fingerprint_id == self.tbl_fingerprint.c.id)),
  1557. created_by=relation(Fingerprint, primaryjoin=(self.tbl_acl_per_source.c.created_by_id == self.tbl_fingerprint.c.id)),
  1558. ))
  1559. mapper(Archive, self.tbl_archive,
  1560. properties=dict(archive_id=self.tbl_archive.c.id,
  1561. archive_name=self.tbl_archive.c.name))
  1562. mapper(ArchiveFile, self.tbl_files_archive_map,
  1563. properties=dict(archive=relation(Archive, backref='files'),
  1564. component=relation(Component),
  1565. file=relation(PoolFile, backref='archives')))
  1566. mapper(BuildQueue, self.tbl_build_queue,
  1567. properties=dict(queue_id=self.tbl_build_queue.c.id,
  1568. suite=relation(Suite, primaryjoin=(self.tbl_build_queue.c.suite_id == self.tbl_suite.c.id))))
  1569. mapper(DBBinary, self.tbl_binaries,
  1570. properties=dict(binary_id=self.tbl_binaries.c.id,
  1571. package=self.tbl_binaries.c.package,
  1572. version=self.tbl_binaries.c.version,
  1573. maintainer_id=self.tbl_binaries.c.maintainer,
  1574. maintainer=relation(Maintainer),
  1575. source_id=self.tbl_binaries.c.source,
  1576. source=relation(DBSource, backref='binaries'),
  1577. arch_id=self.tbl_binaries.c.architecture,
  1578. architecture=relation(Architecture),
  1579. poolfile_id=self.tbl_binaries.c.file,
  1580. poolfile=relation(PoolFile),
  1581. binarytype=self.tbl_binaries.c.type,
  1582. fingerprint_id=self.tbl_binaries.c.sig_fpr,
  1583. fingerprint=relation(Fingerprint),
  1584. install_date=self.tbl_binaries.c.install_date,
  1585. suites=relation(Suite, secondary=self.tbl_bin_associations,
  1586. backref=backref('binaries', lazy='dynamic')),
  1587. extra_sources=relation(DBSource, secondary=self.tbl_extra_src_references,
  1588. backref=backref('extra_binary_references', lazy='dynamic')),
  1589. key=relation(BinaryMetadata, cascade='all',
  1590. collection_class=attribute_mapped_collection('key'))),
  1591. )
  1592. mapper(Component, self.tbl_component,
  1593. properties=dict(component_id=self.tbl_component.c.id,
  1594. component_name=self.tbl_component.c.name),
  1595. )
  1596. mapper(DBConfig, self.tbl_config,
  1597. properties=dict(config_id=self.tbl_config.c.id))
  1598. mapper(DSCFile, self.tbl_dsc_files,
  1599. properties=dict(dscfile_id=self.tbl_dsc_files.c.id,
  1600. source_id=self.tbl_dsc_files.c.source,
  1601. source=relation(DBSource),
  1602. poolfile_id=self.tbl_dsc_files.c.file,
  1603. poolfile=relation(PoolFile)))
  1604. mapper(ExternalOverride, self.tbl_external_overrides,
  1605. properties=dict(
  1606. suite_id=self.tbl_external_overrides.c.suite,
  1607. suite=relation(Suite),
  1608. component_id=self.tbl_external_overrides.c.component,
  1609. component=relation(Component)))
  1610. mapper(PoolFile, self.tbl_files,
  1611. properties=dict(file_id=self.tbl_files.c.id,
  1612. filesize=self.tbl_files.c.size),
  1613. )
  1614. mapper(Fingerprint, self.tbl_fingerprint,
  1615. properties=dict(fingerprint_id=self.tbl_fingerprint.c.id,
  1616. uid_id=self.tbl_fingerprint.c.uid,
  1617. uid=relation(Uid),
  1618. keyring_id=self.tbl_fingerprint.c.keyring,
  1619. keyring=relation(Keyring),
  1620. acl=relation(ACL)),
  1621. )
  1622. mapper(Keyring, self.tbl_keyrings,
  1623. properties=dict(keyring_name=self.tbl_keyrings.c.name,
  1624. keyring_id=self.tbl_keyrings.c.id,
  1625. acl=relation(ACL, primaryjoin=(self.tbl_keyrings.c.acl_id == self.tbl_acl.c.id)))),
  1626. mapper(DBChange, self.tbl_changes,
  1627. properties=dict(change_id=self.tbl_changes.c.id,
  1628. seen=self.tbl_changes.c.seen,
  1629. source=self.tbl_changes.c.source,
  1630. binaries=self.tbl_changes.c.binaries,
  1631. architecture=self.tbl_changes.c.architecture,
  1632. distribution=self.tbl_changes.c.distribution,
  1633. urgency=self.tbl_changes.c.urgency,
  1634. maintainer=self.tbl_changes.c.maintainer,
  1635. changedby=self.tbl_changes.c.changedby,
  1636. date=self.tbl_changes.c.date,
  1637. version=self.tbl_changes.c.version))
  1638. mapper(Maintainer, self.tbl_maintainer,
  1639. properties=dict(maintainer_id=self.tbl_maintainer.c.id,
  1640. maintains_sources=relation(DBSource, backref='maintainer',
  1641. primaryjoin=(self.tbl_maintainer.c.id == self.tbl_source.c.maintainer)),
  1642. changed_sources=relation(DBSource, backref='changedby',
  1643. primaryjoin=(self.tbl_maintainer.c.id == self.tbl_source.c.changedby))),
  1644. )
  1645. mapper(NewComment, self.tbl_new_comments,
  1646. properties=dict(comment_id=self.tbl_new_comments.c.id,
  1647. policy_queue=relation(PolicyQueue)))
  1648. mapper(Override, self.tbl_override,
  1649. properties=dict(suite_id=self.tbl_override.c.suite,
  1650. suite=relation(Suite,
  1651. backref=backref('overrides', lazy='dynamic')),
  1652. package=self.tbl_override.c.package,
  1653. component_id=self.tbl_override.c.component,
  1654. component=relation(Component,
  1655. backref=backref('overrides', lazy='dynamic')),
  1656. priority_id=self.tbl_override.c.priority,
  1657. priority=relation(Priority,
  1658. backref=backref('overrides', lazy='dynamic')),
  1659. section_id=self.tbl_override.c.section,
  1660. section=relation(Section,
  1661. backref=backref('overrides', lazy='dynamic')),
  1662. overridetype_id=self.tbl_override.c.type,
  1663. overridetype=relation(OverrideType,
  1664. backref=backref('overrides', lazy='dynamic'))))
  1665. mapper(OverrideType, self.tbl_override_type,
  1666. properties=dict(overridetype=self.tbl_override_type.c.type,
  1667. overridetype_id=self.tbl_override_type.c.id))
  1668. mapper(PolicyQueue, self.tbl_policy_queue,
  1669. properties=dict(policy_queue_id=self.tbl_policy_queue.c.id,
  1670. suite=relation(Suite, primaryjoin=(self.tbl_policy_queue.c.suite_id == self.tbl_suite.c.id))))
  1671. mapper(PolicyQueueUpload, self.tbl_policy_queue_upload,
  1672. properties=dict(
  1673. changes=relation(DBChange),
  1674. policy_queue=relation(PolicyQueue, backref='uploads'),
  1675. target_suite=relation(Suite),
  1676. source=relation(DBSource),
  1677. binaries=relation(DBBinary, secondary=self.tbl_policy_queue_upload_binaries_map),
  1678. ))
  1679. mapper(PolicyQueueByhandFile, self.tbl_policy_queue_byhand_file,
  1680. properties=dict(
  1681. upload=relation(PolicyQueueUpload, backref='byhand'),
  1682. )
  1683. )
  1684. mapper(Priority, self.tbl_priority,
  1685. properties=dict(priority_id=self.tbl_priority.c.id))
  1686. mapper(SignatureHistory, self.tbl_signature_history)
  1687. mapper(DBSource, self.tbl_source,
  1688. properties=dict(source_id=self.tbl_source.c.id,
  1689. version=self.tbl_source.c.version,
  1690. maintainer_id=self.tbl_source.c.maintainer,
  1691. poolfile_id=self.tbl_source.c.file,
  1692. poolfile=relation(PoolFile),
  1693. fingerprint_id=self.tbl_source.c.sig_fpr,
  1694. fingerprint=relation(Fingerprint),
  1695. changedby_id=self.tbl_source.c.changedby,
  1696. srcfiles=relation(DSCFile,
  1697. primaryjoin=(self.tbl_source.c.id == self.tbl_dsc_files.c.source)),
  1698. suites=relation(Suite, secondary=self.tbl_src_associations,
  1699. backref=backref('sources', lazy='dynamic')),
  1700. uploaders=relation(Maintainer,
  1701. secondary=self.tbl_src_uploaders),
  1702. key=relation(SourceMetadata, cascade='all',
  1703. collection_class=attribute_mapped_collection('key'))),
  1704. )
  1705. mapper(SrcFormat, self.tbl_src_format,
  1706. properties=dict(src_format_id=self.tbl_src_format.c.id,
  1707. format_name=self.tbl_src_format.c.format_name))
  1708. mapper(Suite, self.tbl_suite,
  1709. properties=dict(suite_id=self.tbl_suite.c.id,
  1710. policy_queue=relation(PolicyQueue, primaryjoin=(self.tbl_suite.c.policy_queue_id == self.tbl_policy_queue.c.id)),
  1711. new_queue=relation(PolicyQueue, primaryjoin=(self.tbl_suite.c.new_queue_id == self.tbl_policy_queue.c.id)),
  1712. debug_suite=relation(Suite, remote_side=[self.tbl_suite.c.id]),
  1713. copy_queues=relation(BuildQueue,
  1714. secondary=self.tbl_suite_build_queue_copy),
  1715. srcformats=relation(SrcFormat, secondary=self.tbl_suite_src_formats,
  1716. backref=backref('suites', lazy='dynamic')),
  1717. archive=relation(Archive, backref='suites'),
  1718. acls=relation(ACL, secondary=self.tbl_suite_acl_map, collection_class=set),
  1719. components=relation(Component, secondary=self.tbl_component_suite,
  1720. order_by=self.tbl_component.c.ordering,
  1721. backref=backref('suites')),
  1722. architectures=relation(Architecture, secondary=self.tbl_suite_architectures,
  1723. backref=backref('suites'))),
  1724. )
  1725. mapper(Uid, self.tbl_uid,
  1726. properties=dict(uid_id=self.tbl_uid.c.id,
  1727. fingerprint=relation(Fingerprint)),
  1728. )
  1729. mapper(BinContents, self.tbl_bin_contents,
  1730. properties=dict(
  1731. binary=relation(DBBinary,
  1732. backref=backref('contents', lazy='dynamic', cascade='all')),
  1733. file=self.tbl_bin_contents.c.file))
  1734. mapper(SrcContents, self.tbl_src_contents,
  1735. properties=dict(
  1736. source=relation(DBSource,
  1737. backref=backref('contents', lazy='dynamic', cascade='all')),
  1738. file=self.tbl_src_contents.c.file))
  1739. mapper(MetadataKey, self.tbl_metadata_keys,
  1740. properties=dict(
  1741. key_id=self.tbl_metadata_keys.c.key_id,
  1742. key=self.tbl_metadata_keys.c.key))
  1743. mapper(BinaryMetadata, self.tbl_binaries_metadata,
  1744. properties=dict(
  1745. binary_id=self.tbl_binaries_metadata.c.bin_id,
  1746. binary=relation(DBBinary),
  1747. key_id=self.tbl_binaries_metadata.c.key_id,
  1748. key=relation(MetadataKey),
  1749. value=self.tbl_binaries_metadata.c.value))
  1750. mapper(SourceMetadata, self.tbl_source_metadata,
  1751. properties=dict(
  1752. source_id=self.tbl_source_metadata.c.src_id,
  1753. source=relation(DBSource),
  1754. key_id=self.tbl_source_metadata.c.key_id,
  1755. key=relation(MetadataKey),
  1756. value=self.tbl_source_metadata.c.value))
  1757. mapper(VersionCheck, self.tbl_version_check,
  1758. properties=dict(
  1759. suite_id=self.tbl_version_check.c.suite,
  1760. suite=relation(Suite, primaryjoin=self.tbl_version_check.c.suite == self.tbl_suite.c.id),
  1761. reference_id=self.tbl_version_check.c.reference,
  1762. reference=relation(Suite, primaryjoin=self.tbl_version_check.c.reference == self.tbl_suite.c.id, lazy='joined')))
  1763. ## Connection functions
  1764. def __createconn(self):
  1765. from .config import Config
  1766. cnf = Config()
  1767. if "DB::Service" in cnf:
  1768. connstr = "postgresql://service=%s" % cnf["DB::Service"]
  1769. elif "DB::Host" in cnf:
  1770. # TCP/IP
  1771. connstr = "postgresql://%s" % cnf["DB::Host"]
  1772. if "DB::Port" in cnf and cnf["DB::Port"] != "-1":
  1773. connstr += ":%s" % cnf["DB::Port"]
  1774. connstr += "/%s" % cnf["DB::Name"]
  1775. else:
  1776. # Unix Socket
  1777. connstr = "postgresql:///%s" % cnf["DB::Name"]
  1778. if "DB::Port" in cnf and cnf["DB::Port"] != "-1":
  1779. connstr += "?port=%s" % cnf["DB::Port"]
  1780. engine_args = {'echo': self.debug}
  1781. if 'DB::PoolSize' in cnf:
  1782. engine_args['pool_size'] = int(cnf['DB::PoolSize'])
  1783. if 'DB::MaxOverflow' in cnf:
  1784. engine_args['max_overflow'] = int(cnf['DB::MaxOverflow'])
  1785. # we don't support non-utf-8 connections
  1786. engine_args['client_encoding'] = 'utf-8'
  1787. # Monkey patch a new dialect in in order to support service= syntax
  1788. import sqlalchemy.dialects.postgresql
  1789. from sqlalchemy.dialects.postgresql.psycopg2 import PGDialect_psycopg2
  1790. class PGDialect_psycopg2_dak(PGDialect_psycopg2):
  1791. def create_connect_args(self, url):
  1792. if str(url).startswith('postgresql://service='):
  1793. # Eww
  1794. servicename = str(url)[21:]
  1795. return (['service=%s' % servicename], {})
  1796. else:
  1797. return PGDialect_psycopg2.create_connect_args(self, url)
  1798. sqlalchemy.dialects.postgresql.base.dialect = PGDialect_psycopg2_dak
  1799. try:
  1800. self.db_pg = create_engine(connstr, **engine_args)
  1801. self.db_smaker = sessionmaker(bind=self.db_pg,
  1802. autoflush=True,
  1803. autocommit=False)
  1804. if self.db_meta is None:
  1805. self.__class__.db_meta = Base.metadata
  1806. self.__class__.db_meta.bind = self.db_pg
  1807. self.__setuptables()
  1808. self.__setupmappers()
  1809. except OperationalError as e:
  1810. from . import utils
  1811. utils.fubar("Cannot connect to database (%s)" % str(e))
  1812. self.pid = os.getpid()
  1813. def session(self, work_mem=0):
  1814. '''
  1815. Returns a new session object. If a work_mem parameter is provided a new
  1816. transaction is started and the work_mem parameter is set for this
  1817. transaction. The work_mem parameter is measured in MB. A default value
  1818. will be used if the parameter is not set.
  1819. '''
  1820. # reinitialize DBConn in new processes
  1821. if self.pid != os.getpid():
  1822. self.__createconn()
  1823. session = self.db_smaker()
  1824. if work_mem > 0:
  1825. session.execute("SET LOCAL work_mem TO '%d MB'" % work_mem)
  1826. return session
  1827. __all__.append('DBConn')