o vf9@sdZddlZddlZddlZddlZzddlmZddlmZm Z e Z ee fWn!e yIddl mZddlmZddlm Z ddlm Z YnwddlZd d ZGd d d Zdd dZddZGdddeZdS)z"Abstract crash database interface.N) Exception) quote_plusurlopen) cmp_to_key)r)r)URLErrorcCst|tr |ddS|S)z.Convert str to an unicode if it isn't already.UTF-8ignore) isinstancebytesdecode)strr 0/usr/lib/python3/dist-packages/apport/crashdb.py_us  rc@sXeZdZddZddZddZddZdRd d Zd d ZddZ ddZ ddZ ddZ ddZ ddZddZdSddZdd Zd!d"Zd#d$Zed%d&ZdRd'd(Zd)d*Zd+d,Zd-d.Z  dTd/d0ZdUd2d3Zd4d5Zd6d7Zd8d9Zd:d;Zdd?Z!d@dAZ"dBdCZ#dDdEZ$dFdGZ%dHdIZ&dJdKZ'dLdMZ(dRdNdOZ)dPdQZ*d S)V CrashDatabasecCs||_||_d|_dS)azInitialize crash database connection. You need to specify an implementation specific file with the authentication credentials for retracing access for download() and update(). For upload() and get_comment_url() you can use None. options is a dictionary with additional settings from crashdb.conf; see get_crashdb() for details. N) auth_fileoptions duplicate_db)selfrrr r r__init__&s  zCrashDatabase.__init__cCs |jdS)zReturn the base URL for bug patterns. See apport.report.Report.search_bug_patterns() for details. If this function returns None, bug patterns are disabled. bug_pattern_urlrgetrr r rget_bugpattern_baseurl4s z$CrashDatabase.get_bugpattern_baseurlcCs"d|jvr|d|jdvSdS)zCheck if this report can be uploaded to this database. Crash databases might limit the types of reports they get with e. g. the "problem_types" option. problem_types ProblemTypeTr)rreportr r raccepts<s zCrashDatabase.acceptsc Cs|ddl}|jdks Jdd|_tj| p"|dkp"tj|dk}|j|dd|_|rN|j }| d | d |jg| d | d |j |j }| d | }|dgkrit dt|z | d|}Wn|jjy}zdt|vrdg}WYd}~nd}~ww|d|jkrt d|d|d|jkrtd|d|jf||ddSdS)zInitialize duplicate database. path specifies an SQLite database. It will be created if it does not exist yet. rNqmarkz/this module assumes qmark dbapi parameter stylez:memory:i )timeoutz.CREATE TABLE version (format INTEGER NOT NULL)zINSERT INTO version VALUES (?)aCREATE TABLE crashes ( signature VARCHAR(255) NOT NULL, crash_id INTEGER NOT NULL, fixed_version VARCHAR(50), last_change TIMESTAMP, CONSTRAINT crashes_pk PRIMARY KEY (crash_id))zCREATE TABLE address_signatures ( signature VARCHAR(1000) NOT NULL, crash_id INTEGER NOT NULL, CONSTRAINT address_signatures_pk PRIMARY KEY (signature))zPRAGMA integrity_check)okzCorrupt duplicate db:zSELECT format FROM versionz no such tablez"duplicate DB has unknown format %iz+duplicate db has format %i, upgrading to %i)sqlite3 paramstyleformat_versionospathexistsgetsizeconnectrcursorexecutecommitfetchall SystemErrorr fetchoneOperationalErrorprint_duplicate_db_upgrade)rr'dbapi2initcurresulter r rinit_duplicate_dbLsJ             zCrashDatabase.init_duplicate_dbNc Cs|jsJd|s||}|||d|vr|d}n|}g}|r?|||}|r?|D] \}}||q/|||}z |dd}Wn ttfyVd}Ynwd}d} |D]\}} | rn|rnt j || dkrt|}| } n q]|r| ||dd| } | r|| } | r| |kr|dur| }n#|| kr||| ||| |n|||| ||| | }d} |dur||kr| r|| ||||||| fS|r|j} | d|g| d}|dkr| d t||df|j| r|| |dS) aCheck whether a crash is already known. If the crash is new, it will be added to the duplicate database and the function returns None. If the crash is already known, the function returns a pair (crash_id, fixed_version), where fixed_version might be None if the crash is not fixed in the latest version yet. Depending on whether the version in report is smaller than/equal to the fixed version or larger, this calls close_duplicate() or mark_regression(). If the report does not have a valid crash signature, this function does nothing and just returns None. By default, the report gets download()ed, but for performance reasons it can be explicitly passed to this function if it is already available. -init_duplicate_db() needs to be called beforeDuplicateSignaturePackageNrz0SELECT count(*) FROM crashes WHERE crash_id == ?z7INSERT INTO crashes VALUES (?, ?, ?, CURRENT_TIMESTAMP))rdownload_mark_dup_checkedcrash_signature_duplicate_search_signature_duplicate_db_sync_statussplitKeyError IndexErrorapport packagingcompare_versionsmark_regressioncrash_signature_addresses#_duplicate_search_address_signatureclose_duplicate_duplicate_db_merge_id#_duplicate_db_add_address_signaturer+r,r0rr-)ridrsigexistingex_id_report_package_version master_id master_verex_veraddr_sig addr_matchr6count_idr r rcheck_duplicatesr                zCrashDatabase.check_duplicatec Cs*|jdsdSdD]}|dkrd|vr|d}n |}n|}|s%q ||}|s/dStj|jd|t|}zt |}| d}| d|vrRWq Wn t tfy^Yq w|D].}z|dd\} } t| } Wn ty|Yqcw| |kr||| } | sd } | Sqcq dS) aCheck if the crash db already knows about the crash signature. Check if the report has a DuplicateSignature, crash_signature(), or StacktraceAddressSignature, and ask the database whether the problem is already known. If so, return an URL where the user can check the status or subscribe (if available), or just return True if the report is known but there is no public URL. In that case the report will not be uploaded (i. e. upload() will not be called). Return None if the report does not have any signature or the crash database does not support checking for duplicates on the client side. The default implementation uses a text file format generated by duplicate_db_publish() at an URL specified by the "dupdb_url" option. Subclasses are free to override this with a custom implementation, such as a real database lookup. dupdb_urlN)rQaddressrQr;rz404 Not Foundr=���1)r���r���rA���rK���duplicate_sig_hashr&���r'���joinr���r���readr ���closeIOErrorr��� splitlinesrD���int ValueError get_id_url) r���r���kindrQ���hurlfcontentslinerP���sr7���r ���r ���r���known���sN���          zCrashDatabase.knownc�����������������C���sD���|�j�sJ�d|�j��}|d||f}|jdksJ�|�j���dS�)zMark given crash ID as fixed in the duplicate database. version specifies the package version the crash was fixed in (None for 'still unfixed'). r:���zXUPDATE crashes SET fixed_version = ?, last_change = CURRENT_TIMESTAMP WHERE crash_id = ?r=���N)r���r+���r,���rowcountr-���)r���rP���versionr6���nr ���r ���r���duplicate_db_fixed2��s��� z CrashDatabase.duplicate_db_fixedc�����������������C���sB���|�j�sJ�d|�j��}|d|g�|d|g�|�j���dS�)z{Remove crash from the duplicate database. This happens when a report got rejected or manually duplicated. r:���&DELETE FROM crashes WHERE crash_id = ?z1DELETE FROM address_signatures WHERE crash_id = ?Nr���r+���r,���r-���)r���rP���r6���r ���r ���r���duplicate_db_remove@��s ��� z!CrashDatabase.duplicate_db_removec�����������������C���sF���|�j�sJ�d|�j��}|d||g�|d||g�|�j���dS�)zChange a crash ID.r:���zSUPDATE crashes SET crash_id = ?, last_change = CURRENT_TIMESTAMP WHERE crash_id = ?=UPDATE address_signatures SET crash_id = ? WHERE crash_id = ?Nrv���)r���old_idnew_idr6���r ���r ���r���duplicate_db_change_master_idL��s��� z+CrashDatabase.duplicate_db_change_master_idc����������� ������C���s��|�j�sJ�d|d�}t|�tj|d}t|�d}d}|�j��}|d�|�D�]-\}}|�|} | du�r<q.| |krR| }|rH| ��t tj||d}| d||f��q.|rb| ��tj|d} t| �d}d}|d �|�D�]0\}}|�|} | du�rq{| |kr| }|r| ��t tj| |d }| d||f� d �q{|r| ��tj |rt||d ��t||�tj |d �rt|d ��dS�dS�) a��Create text files suitable for www publishing. Create a number of text files in the given directory which Apport clients can use to determine whether a problem is already reported to the database, through the known() method. This directory is suitable for publishing to the web. The database is indexed by the first two fields of the duplicate or crash signature, to avoid having to download the entire database every time. If the directory already exists, it will be updated. The new content is built in a new directory which is the given one with ".new" appended, then moved to the given name in an almost atomic way. r:���z.newr^���Nz3SELECT * from address_signatures ORDER BY signaturewz%i %s rQ���z:SELECT signature, crash_id from crashes ORDER BY signaturewbr���z.old)r���r&���mkdirr'���ra���r+���r,���r.���r`���rc���openwriteencoder(���renameshutilrmtree) r���dirout addr_basecur_hashcur_filer6���rQ���rP���rj���sig_baser ���r ���r���duplicate_db_publishX��sX���          z"CrashDatabase.duplicate_db_publishc�����������������C���sD���|dk�rt�d|�j�}|d|f�|�j��||�jks J�dS�)z"Upgrade database to current formatr ���z2Cannot upgrade database from format earlier than 3zUPDATE version SET format = ?N)r/���r���r+���r,���r-���r%���)r��� cur_formatr6���r ���r ���r���r3�����s ���  z#CrashDatabase._duplicate_db_upgradec�����������������C���s`���|�j��}|dt||g�|�}dd�}tjd�dkr(|jt|d�|S�|j|d�|S�)a��Look up signature in the duplicate db. Return [(id, fixed_version)] tuple list. There might be several matches if a crash has been reintroduced in a later version. The results are sorted so that the highest fixed version comes first, and "unfixed" being the last result. id is the bug we are looking to find a duplicate for. The result will never contain id, to avoid marking a bug as a duplicate of itself if a bug is reprocessed more than once. zQSELECT crash_id, fixed_version FROM crashes WHERE signature = ? AND crash_id <> ?c�����������������S���sr���|�d�}�|d�}|�|krdS�|�dkr|d�u�rdS�dS�|dkr&|�d�u�r$dS�dS�|�d�u�r,dS�|d�u�r2dS�t�j|�|S�)Nr=���r����r>���)rG���rH���rI���)xyr ���r ���r���cmp��s"���z6CrashDatabase._duplicate_search_signature.<locals>.cmpr���3)key)r���) r���r+���r,���r���r.���sysrr���sortr���)r���rQ���rP���r6���rR���r���r ���r ���r���rB�����s���  z)CrashDatabase._duplicate_search_signaturec�����������������C���sL���|sdS�|�j��}|d|g�|�}t|dksJ�|r$|d�d�S�dS�)z]Return ID for crash address signature. Return None if signature is unknown. Nz<SELECT crash_id FROM address_signatures WHERE signature == ?r=���r���)r���r+���r,���r.���len)r���rQ���r6��� existing_idsr ���r ���r���rL�����s���  z1CrashDatabase._duplicate_search_address_signatureFc�����������������C���s\���|�j�sJ�di�}|�j��}|d�|D�]\}}}}|r%|||f||<�q||f||<�q|S�)aY��Return the entire duplicate database as a dictionary. The returned dictionary maps "signature" to (crash_id, fixed_version) pairs. If with_timestamps is True, then the map will contain triples (crash_id, fixed_version, last_change) instead. This is mainly useful for debugging and test suites. r:���zSELECT * FROM crashes)r���r+���r,���)r���with_timestampsdumpr6���rQ���rP���ver last_changer ���r ���r���_duplicate_db_dump��s���   z CrashDatabase._duplicate_db_dumpc�����������������C���s���|�j�sJ�d|�j��}|d|g�|�}|sdS�|d�}|�|}|dkr5td|��|�|�dS�|sI|rItd||f��|�||�dS�|r]|s_td||f��|�||�dS�dS�dS�) a��Update the duplicate db to the reality of the report in the crash db. This uses get_fixed_version() to get the status of the given crash. An invalid ID gets removed from the duplicate db, and a crash which got fixed is marked as such in the database. r:���z4SELECT fixed_version FROM crashes WHERE crash_id = ?Nr���invalidz5DEBUG: bug %i was invalidated, removing from databasez8DEBUG: bug %i got fixed in version %s, updating databasezCDEBUG: bug %i got reopened, dropping fixed version %s from database)r���r+���r,���r0���get_fixed_versionr2���rw���rt���)r���rP���r6���db_fixed_versionreal_fixed_versionr ���r ���r���rC��� ��s*���      z'CrashDatabase._duplicate_db_sync_statusc�����������������C���sX���|��|}|r||krtd|||f�d�S�|�j�}|dt||f�|�j��d�S�)NzIID %i has signature %s, but database already has that signature for ID %iz,INSERT INTO address_signatures VALUES (?, ?))rL���r/���r���r+���r,���r���r-���)r���rQ���rP���rR���r6���r ���r ���r���rO���/��s���  z1CrashDatabase._duplicate_db_add_address_signaturec�����������������C���sD���|�j�sJ�d|�j��}|d|g�|d||g�|�j���dS�)zMerge two crash IDs. This is necessary when having to mark a bug as a duplicate if it already is in the duplicate DB. r:���ru���rx���Nrv���)r���dupmasterr6���r ���r ���r���rN���;��s��� z$CrashDatabase._duplicate_db_merge_idc�����������������C���s`���d|v�rdS�|�ddd�}d|�dddd�}|d d}t|d }|dd �}|S�) z5Create a www/URL proof hash for a duplicate signature N r=���r���rT���:���/r������)rD���ra���replacer���r���)klassrQ���ir ���r ���r���r`���I��s���  z CrashDatabase.duplicate_sig_hashc�����������������C������t�d)a��Upload given problem report return a handle for it. This should happen noninteractively. If the implementation supports it, and a function progress_callback is passed, that is called repeatedly with two arguments: the number of bytes already sent, and the total number of bytes to send. This can be used to provide a proper upload progress indication on frontends. Implementations ought to "assert self.accepts(report)". The UI logic already prevents uploading a report to a database which does not accept it, but for third-party users of the API this should still be checked. This method can raise a NeedsCredentials exception in case of failure. 6this method must be implemented by a concrete subclassNotImplementedError)r���r���progress_callbackr ���r ���r���uploada��s���zCrashDatabase.uploadc�����������������C���r���)a8��Return an URL that should be opened after report has been uploaded and upload() returned handle. Should return None if no URL should be opened (anonymous filing without user comments); in that case this function should do whichever interactive steps it wants to perform. r���r���)r���r���handler ���r ���r���get_comment_urls�����zCrashDatabase.get_comment_urlc�����������������C���r���)zReturn URL for a given report ID. The report is passed in case building the URL needs additional information from it, such as the SourcePackage name. Return None if URL is not available or cannot be determined. r���r���)r���r���rP���r ���r ���r���rh���}��r���zCrashDatabase.get_id_urlc�����������������C���r���)z>Download the problem report from given ID and return a Report.r���r���r���rP���r ���r ���r���r?��������zCrashDatabase.downloadc�����������������C���r���)ah��Update the given report ID with all data from report. This creates a text comment with the "short" data (see ProblemReport.write_mime()), and creates attachments for all the bulk/binary data. If change_description is True, and the crash db implementation supports it, the short data will be put into the description instead (like in a new bug). comment will be added to the "short" data. If attachment_comment is given, it will be added to the attachment uploads. If key_filter is a list or set, then only those keys will be added. r���r���)r���rP���r���commentchange_descriptionattachment_comment key_filterr ���r ���r���update��s���zCrashDatabase.updater���c�����������������C���s���|�j�|||g�dd�dS�)zUpdate the given report ID for retracing results. This updates Stacktrace, ThreadStacktrace, StacktraceTop, and StacktraceSource. You can also supply an additional comment. ) StacktraceThreadStacktraceStacktraceSource StacktraceTop)r���N)r���)r���rP���r���r���r ���r ���r��� update_traces��s���zCrashDatabase.update_tracesc�����������������C���r���)zSet username and password.r���r���)r���usernamepasswordr ���r ���r���set_credentials��r���zCrashDatabase.set_credentialsc�����������������C���r���)z2Get 'DistroRelease: <release>' from the report ID.r���r���r���r ���r ���r���get_distro_release��r���z CrashDatabase.get_distro_releasec�����������������C���r���)zReturn set of crash IDs which have not been retraced yet. This should only include crashes which match the current host architecture. r���r���r���r ���r ���r���get_unretraced��s���zCrashDatabase.get_unretracedc�����������������C���r���)a��Return set of crash IDs which need duplicate checking. This is mainly useful for crashes of scripting languages such as Python, since they do not need to be retraced. It should not return bugs that are covered by get_unretraced(). r���r���r���r ���r ���r���get_dup_unchecked��s���zCrashDatabase.get_dup_uncheckedc�����������������C���r���)aX��Return an ID set of all crashes which are not yet fixed. The list must not contain bugs which were rejected or duplicate. This function should make sure that the returned list is correct. If there are any errors with connecting to the crash database, it should raise an exception (preferably IOError). r���r���r���r ���r ���r��� get_unfixed��s��� zCrashDatabase.get_unfixedc�����������������C���r���)a��Return the package version that fixes a given crash. Return None if the crash is not yet fixed, or an empty string if the crash is fixed, but it cannot be determined by which version. Return 'invalid' if the crash report got invalidated, such as closed a duplicate or rejected. This function should make sure that the returned result is correct. If there are any errors with connecting to the crash database, it should raise an exception (preferably IOError). r���r���r���r ���r ���r���r�����s��� zCrashDatabase.get_fixed_versionc�����������������C���r���)z5Return list of affected source packages for given ID.r���r���r���r ���r ���r���get_affected_packages��r���z#CrashDatabase.get_affected_packagesc�����������������C���r���)z3Check whether the user is the reporter of given ID.r���r���r���r ���r ���r��� is_reporter��r���zCrashDatabase.is_reporterc�����������������C���r���)aB��Check whether the user is eligible to update a report. A user should add additional information to an existing ID if (s)he is the reporter or subscribed, the bug is open, not a duplicate, etc. The exact policy and checks should be done according to the particular implementation. r���r���r���r ���r ���r��� can_update��r���zCrashDatabase.can_updatec�����������������C���r���)zcReturn master ID for a duplicate bug. If the bug is not a duplicate, return None. r���r���r���r ���r ���r��� duplicate_of�����zCrashDatabase.duplicate_ofc�����������������C���r���)zlMark a crash id as duplicate of given master ID. If master is None, id gets un-duplicated. r���r���)r���r���rP���r���r ���r ���r���rM�����r���zCrashDatabase.close_duplicatec�����������������C���r���)zpMark a crash id as reintroducing an earlier crash which is already marked as fixed (having ID 'master').r���r���)r���rP���r���r ���r ���r���rJ�����s���zCrashDatabase.mark_regressionc�����������������C���r���)zMark crash id as retraced.r���r���r���r ���r ���r��� mark_retraced��r���zCrashDatabase.mark_retracedc�����������������C���r���)zMark crash id as 'failed to retrace'. If invalid_msg is given, the bug should be closed as invalid with given message, otherwise just marked as a failed retrace. This can be a no-op if you are not interested in this. r���r���)r���rP��� invalid_msgr ���r ���r���mark_retrace_failed ��r���z!CrashDatabase.mark_retrace_failedc�����������������C���r���)zMark crash id as checked for being a duplicate This is an internal method that should not be called from outside. r���r���)r���rP���r���r ���r ���r���r@�����r���zCrashDatabase._mark_dup_checked)N)F)FNN)r���)+__name__ __module__ __qualname__r���r���r���r9���r\���rp���rt���rw���r{���r���r3���rB���rL���r���rC���rO���rN��� classmethodr`���r���r���rh���r?���r���r���r���r���r���r���r���r���r���r���r���r���rM���rJ���r���r���r@���r ���r ���r ���r���r���%���sV���� 9fG  N- $            r���c����������� ��� ���C���s>��|s t�jdd}i�}t|}tt|�|d|�W�d���n1�s%w���Y��|d�}t�j|rt� |D�]V}t�j ||}t�j |r| drz#t|}tt|�|d|d��W�d���n1�sjw���Y��W�q9�t y�}�ztjd|t|f��W�Y�d}~q9d}~ww�q9|s|d �}t|�|d�|�S�) aN��Return a CrashDatabase object for the given crash db name. This reads the configuration file 'conf'. If name is None, it defaults to the 'default' value in conf. If conf is None, it defaults to the environment variable APPORT_CRASHDB_CONF; if that does not exist, the hardcoded default is /etc/apport/crashdb.conf. This Python syntax file needs to specify: - A string variable 'default', giving a default value for 'name' if that is None. - A dictionary 'databases' which maps names to crash db configuration dictionaries. These need to have at least the key 'impl' (Python module in apport.crashdb_impl which contains a concrete 'CrashDatabase' class implementation for that crash db type). Other generally known options are 'bug_pattern_url', 'dupdb_url', and 'problem_types'. APPORT_CRASHDB_CONFz/etc/apport/crashdb.confexecNz.dz.conf databaseszInvalid file %s: %s default)r&���environr���r���r���compilerb���r'���isdirlistdirra���isfileendswithr���r���stderrr���r ��� load_crashdb) r���nameconfsettingsrl���confdDircfcfpathr8���r ���r ���r��� get_crashdb��s2���    r���c�����������������C���s(���t�d|d��t�t�dg}||�|S�)zReturn a CrashDatabase object for a given DB specification. spec is a crash db configuration dictionary as described in get_crashdb(). zapport.crashdb_impl.implr���) __import__globalslocalsr���)r���specmr ���r ���r���r���M��s��� r���c�������������������@���s���e�Zd�ZdZdS�)NeedsCredentialsz8This may be raised when unable to log in to the crashdb.N)r���r���r���__doc__r ���r ���r ���r���r���V��s����r���)NN)r���r&���os.pathr���r��� exceptionsr���urllibr���r���rd���r��� ImportError functoolsr��� urllib.parseurllib.request urllib.errorrG���r���r���r���r���r���r ���r ���r ���r���<module>���s0����       ����� .