dbconn.py 78 KB

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