Source

cheesecake-service / store.py

Full commit
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548

import doctest
import os
import re
import tempfile
import time

import psycopg

from util import fraction
from util import get_last_modification_time
from util import obj2dict
from util import one_of_in
from util import touch_file


class DatabaseError(Exception):
    pass


class DatabaseLog(object):
    def __init__(self, db, cursor):
        self.db = db
        self.cursor = cursor

    def __call__(self, message, level='info'):
        """Save the message into a database.
        """
        execute = lambda query, *args: self.cursor.execute(query, args)

        def to_timestamp(time_float):
            return time.strftime('%Y-%m-%d %H:%M:%S.%%d +0000',
                                 time.gmtime(int(time_float))) % \
                                 int(fraction(time_float) * 1000)

        execute('''INSERT INTO messages (message, time)
                   VALUES (%s, %s)''',
                "[%s] %s" % (level.upper(), message),
                to_timestamp(time.time()))

        self.db.commit()

    def __getattr__(self, name):
        return lambda message: self(message, level=name)


class CheesecakeScore(object):
    class MainIndex(object):
        def __init__(self, absolute, relative, subindices):
            self.absolute = absolute
            self.relative = relative
            self.subindices = subindices

        def get_subindex(self, name):
            """Get subindex that have given `name`.
            Returns None when subindex wasn't found.
            """
            for subindex in self.subindices:
                if subindex.name == name:
                    return subindex

        def __eq__(x, y):
            assert isinstance(y, x.__class__)

            if x.absolute != y.absolute: return False
            if x.relative != y.relative: return False
            if len(x.subindices) != len(y.subindices): return False

            for xsub, ysub in zip(sorted(x.subindices), sorted(y.subindices)):
                if xsub.value != ysub.value: return False
                if xsub.details != ysub.details: return False

            return True

    class SubIndex(object):
        def __init__(self, name, value, details):
            self.name = name
            self.value = value
            self.details = details

        def __cmp__(self, y):
            assert isinstance(y, self.__class__)
            return cmp(self.name, y.name)

    def __init__(self, cheesecake_output):
        """Initialize score results based on Cheesecake output.
        """
        index_regex = r'^([A-Za-z0-9_(). ]+)\s+\.+\s+(-?\d+)\s+\(([^)]+)\)'
        main_index_details_regex = r'(\d+) out of a maximum of \d+'

        subindices = []
        for line in cheesecake_output.splitlines():
            m = re.search(index_regex, line)
            if m:
                name, value, details = m.groups()

                if one_of_in(['INSTALLABILITY', 'DOCUMENTATION', 'CODE KWALITEE'], name):
                    # One of main indices.
                    m = re.search(main_index_details_regex, details)
                    absolute = m.group(1)

                    if 'INSTALLABILITY' in name:
                        self.installability = self.MainIndex(int(absolute), int(value), subindices)
                    elif 'DOCUMENTATION' in name:
                        self.documentation = self.MainIndex(int(absolute), int(value), subindices)
                    elif 'CODE KWALITEE' in name:
                        self.code_kwalitee = self.MainIndex(int(absolute), int(value), subindices)

                    subindices = []
                else:
                    subindices.append(self.SubIndex(name, int(value), details))

    def serialize(self):
        """Return self represented as nested basic data structures.
        """
        def serialize_subindices(main_index):
            return [(x.name, x.value, x.details) for x in main_index.subindices]

        def serialize_main_index(main_index):
            return (main_index.absolute,
                    main_index.relative,
                    serialize_subindices(main_index))

        return {
            'INSTALLABILITY': serialize_main_index(self.installability),
            'DOCUMENTATION': serialize_main_index(self.documentation),
            'CODE_KWALITEE': serialize_main_index(self.code_kwalitee),
        }

    def can_be_installed(self):
        """Return True if score has Installability/install score > 0.
        (which means it can be installed via easy_install).
        """
        subindex = self.installability.get_subindex('install')

        if subindex and subindex.value > 0:
            return True

        return False

class CheesecakeScoreFromValues(CheesecakeScore):
    def __init__(self, installability, documentation, code_kwalitee):
        self.installability = installability
        self.documentation = documentation
        self.code_kwalitee = code_kwalitee


class CheesecakeRun(object):
    def __init__(self, number, package, version, result='running', execution_time=0):
        if result not in ['success', 'failure', 'running']:
            raise ValueError("result should be 'success', 'failure' or 'running'")

        self.number = number
        self.package = package
        self.version = version
        self.result = result
        self.execution_time = execution_time

    def logname(self):
        return '%(number)d-%(package)s==%(version)s-%(result)s-%(execution_time)d.log' % obj2dict(self)


class Store(object):
    """Store is the main point for preserving Cheesecake service data.

    It initializes itself by reading data from given log directory
    and a database. In particular, logs preserve data about each
    cheesecake_index script run and its results, while database contain
    data about up-to-date scores for package releases (release is a
    package name and version pair). In other words, logs are used
    to initialize CheesecakeRun instances and database is used to initialize
    CheesecakeScore instances. There's also a cheesecake_service_timestamp
    file which preserves information about last time PyPI was queried for
    packages.

    Usage:
      * Upon creating of a Store object, all data are automatically fetched.
      * After each successful fetch of PyPI last packages list, remember
        to call `update_timestamp()` method. You should save a list of
        releases that are waiting in run queue to `releases_to_score` list.
        It will be automatically saved to database upon store close.
      * After running a cheesecake_index script, put data about this run
        into `CheesecakeRun` object and save to store via `save_run()` method.
      * After successful run of cheesecake_index script, create a
        `CheesecakeScore` instance and save to to store via `save_score()` method.
      * Access scores via `score` dictionary. Keys are (name, version) tuples
        representing each scored release, values are `CheesecakeScore` instances.
      * To get a unique number that last run used, read the `runs_count`
        attribute. You don't have to modify it directly, it will be
        automatically altered after you commit new `CheesecakeRun` via
        `save_score()` method.
      * Read `failures` attribute to get full list of lognames of failed
        cheesecake_index runs.
      * When you're done with the store, remember to close() it!
    """
    logname_regex = r'(\d+)-([^=]+)==([^=]+)-((?:failure)|(?:success))-(\d+)\.log'

    def __init__(self, directory=None, postgres_config='dbname=cheesecake',
                 timestamp_file=os.path.join(tempfile.gettempdir(),
                                             'cheesecake_service_timestamp')):
        self.directory = directory
        self.postgres_config = postgres_config
        self.timestamp_file = timestamp_file

        self.closed = False

        self._runs_by_release = {}
        self._runs_by_number = {}
        self._runs_failure = []
        self._runs_success = []

        self.releases_to_score = []
        self.score = {}
        self.timestamp = 0

        self._init_database()
        self._init_log()
        self._read_cheesecake_runs()
        self._read_cheesecake_scores()
        self._read_releases_to_score()
        self._read_timestamp()

    def _init_database(self):
        try:
            self.db = psycopg.connect(self.postgres_config)
            self.cursor = self.db.cursor()
        except psycopg.OperationalError, ex:
            raise DatabaseError("Couldn't connect to database: %s" % ex)

    def _init_log(self):
        self.log = DatabaseLog(self.db, self.cursor)

    def _read_timestamp(self):
        if not os.path.isfile(self.timestamp_file):
            touch_file(self.timestamp_file)
        self.timestamp = get_last_modification_time(self.timestamp_file)

    def _read_releases_to_score(self):
        execute = lambda query, *args: self.cursor.execute(query, args)
        fetchall = self.cursor.fetchall

        execute('''SELECT * FROM releases_to_score''')
        for name, version in fetchall():
            self.releases_to_score.append((name, version))

    def _save_releases_to_score(self):
        execute = lambda query, *args: self.cursor.execute(query, args)

        execute('''DELETE FROM releases_to_score''')
        for name, version in self.releases_to_score:
            execute('''INSERT INTO releases_to_score VALUES (%s, %s)''',
                    name, version)

        self.db.commit()

    def _read_cheesecake_runs(self):
        if not self.directory:
            return

        for logname in os.listdir(self.directory):
            m = re.search(self.logname_regex, logname)
            if m:
                number, package, version, result, execution_time = m.groups()
                run = CheesecakeRun(int(number), package, version, result, int(execution_time))
                self.save_run(run)

    def _read_cheesecake_scores(self):
        execute = lambda query, *args: self.cursor.execute(query, args)
        fetchone = self.cursor.fetchone
        fetchall = self.cursor.fetchall

        def get_subindices_of(main_index_id):
            execute('''SELECT name, value, details
                       FROM subindices
                       WHERE main_index_id = %d''',
                    main_index_id)

            subindices = []
            for name, value, details in fetchall():
                subindices.append(CheesecakeScore.SubIndex(name, value, details))

            return subindices

        def get_score_of(main_index_id):
            execute('''SELECT absolute, relative
                       FROM main_indices
                       WHERE id = %d''',
                    main_index_id)
            return fetchone()

        def get_main_index(main_index_id):
            subindices = get_subindices_of(main_index_id)
            absolute, relative = get_score_of(main_index_id)
            return CheesecakeScore.MainIndex(absolute, relative, subindices)

        execute('SELECT * FROM releases')
        releases = fetchall()

        for name, version, installability_id, documentation_id, code_kwalitee_id in releases:
            installability = get_main_index(installability_id)
            documentation = get_main_index(documentation_id)
            code_kwalitee = get_main_index(code_kwalitee_id)

            score = CheesecakeScoreFromValues(installability, documentation, code_kwalitee)

            self._add_score(name, version, score)

    def _add_score(self, name, version, score):
        """Add CheesecakeScore instance to store.
        """
        self.score[(name, version)] = score

    def _map_to_lognames(self, runs_list):
        """Map list of CheesecakeRun instances to list of lognames.
        """
        return [x.logname() for x in runs_list]

    def _get_runs_count(self):
        """Determine runs_count based on filesystem logs.
        Take logname with highest number into account.
        """
        if self.closed:
            raise ValueError("Operation on closed store.")

        L = self._runs_by_number.keys()

        # Return 1 as an initial logname number.
        if not L:
            return 1

        L.sort()
        return L[-1] + 1

    runs_count = property(_get_runs_count)

    def _get_failures(self):
        """Determine list of cheesecake runs that failed.

        Return list of log filenames of failed runs.
        """
        if self.closed:
            raise ValueError("Operation on closed store.")

        failures = self._runs_failure[:]
        failures.sort(lambda x,y: cmp(x.number, y.number), reverse=True)

        return self._map_to_lognames(failures)

    failures = property(_get_failures)

    def save_run(self, run):
        """Add CheesecakeRun instance to store.
        """
        assert isinstance(run, CheesecakeRun)

        self._runs_by_number[run.number] = run
        self._runs_by_release.setdefault((run.package, run.version), []).append(run)
        if run.result == 'success':
            self._runs_success.append(run)
        else:
            self._runs_failure.append(run)

    def _save_main_index(self, main_index):
        execute = lambda query, *args: self.cursor.execute(query, args)
        fetchone = self.cursor.fetchone

        # Insert main_index into main_indices table.
        execute('''INSERT INTO main_indices
                   (absolute, relative)
                   VALUES (%d, %d)''',
                main_index.absolute,
                main_index.relative)
        execute('SELECT last_value FROM main_indices_id_seq')
        main_index_id = fetchone()[0]

        # Insert each of its subindices.
        for subindex in main_index.subindices:
            execute('''INSERT INTO subindices
                       VALUES (%d, %s, %d, %s)''',
                    main_index_id,
                    subindex.name,
                    subindex.value,
                    subindex.details)

        return main_index_id

    def _release_exists(self, name, version):
        execute = lambda query, *args: self.cursor.execute(query, args)
        fetchall = self.cursor.fetchall

        execute('''SELECT *
                   FROM releases
                   WHERE name = %s AND version = %s''',
                name,
                version)

        if fetchall():
            return True
        return False

    def _remove_indices_for_release(self, name, version):
        execute = lambda query, *args: self.cursor.execute(query, args)
        fetchone = self.cursor.fetchone

        execute('''SELECT installability_id, documentation_id, code_kwalitee_id
                   FROM releases
                   WHERE name = %s AND version = %s''',
                name,
                version)

        main_index_ids = fetchone()
        for index in main_index_ids:
            execute('''DELETE FROM subindices
                       WHERE main_index_id = %d''',
                    index)
            execute('''DELETE FROM releases
                       WHERE name = %s AND version = %s''',
                    name,
                    version)
            execute('''DELETE FROM main_indices
                       WHERE id = %d''',
                    index)

    def _insert_score_for_release(self, name, version, installability_id, documentation_id, code_kwalitee_id):
        execute = lambda query, *args: self.cursor.execute(query, args)

        execute('''INSERT INTO releases
                   VALUES (%s, %s, %d, %d, %d)''',
                name,
                version,
                installability_id,
                documentation_id,
                code_kwalitee_id)

    def save_score(self, name, version, score):
        """Save Cheesecake score into database.
        """
        assert isinstance(score, CheesecakeScore)

        if self.closed:
            raise ValueError("Operation on closed store.")

        installability_id = self._save_main_index(score.installability)
        documentation_id = self._save_main_index(score.documentation)
        code_kwalitee_id = self._save_main_index(score.code_kwalitee)

        # If score for a release already exist, remove it first.
        if self._release_exists(name, version):
            self._remove_indices_for_release(name, version)

        self._insert_score_for_release(name, version, installability_id, documentation_id, code_kwalitee_id)

        # Commit changes and update self.score dictionary.
        self.db.commit()
        self._add_score(name, version, score)

    def close(self):
        """Commit all data and close all files/connections for this store.
        """
        if self.closed:
            raise ValueError("Operation on closed store.")

        self._save_releases_to_score()
        self.db.close()
        self.closed = True

    def logs_for_release(self, name, version):
        """Return lognames of all runs for a given release.
        """
        release_runs = self._runs_by_release[(name, version)]
        return self._map_to_lognames(release_runs)

    def number_of_failures(self, name, version):
        """Count number of last failures for given release.
        """
        release_runs = self._runs_by_release[(name, version)]
        release_runs_results = [run.result for run in release_runs]
        release_runs_results.reverse()

        count = 0

        for result in release_runs_results:
            if result == 'success':
                break
            count += 1

        return count

    def update_timestamp(self):
        """Update timestamp to current time.
        """
        touch_file(self.timestamp_file)
        self.timestamp = get_last_modification_time(self.timestamp_file)

    def get_messages(self, count=0):
        """Get `count` last messages.

        If `count` is 0, return all of them.
        Returns a list of (id, timestamp, message) tuples.
        """
        assert isinstance(count, int)

        execute = lambda query, *args: self.cursor.execute(query, args)
        fetchall = self.cursor.fetchall

        query = '''SELECT *
                   FROM messages
                   ORDER BY time DESC''';
        if count:
            query += ' LIMIT %d' % count

        execute(query)
        return fetchall()

    def clean_messages(self, all_but=0):
        """Clean old messages except for recent `all_but`.
        """
        assert isinstance(all_but, int)

        execute = lambda query, *args: self.cursor.execute(query, args)

        query  = 'DELETE FROM messages'

        if all_but:
            query += ' WHERE id NOT IN (SELECT id FROM messages '\
                     'ORDER BY time DESC LIMIT %d)' % all_but

        execute(query)

        self.db.commit()

    def clean_all(self):
        """Clear the database.
        """
        tables = ['releases', 'subindices', 'main_indices',
                  'releases_to_score', 'messages']

        for table in tables:
            self.cursor.execute('DELETE FROM %s' % table)

        self.releases_to_score = []

        self.db.commit()

################################################################################

if __name__ == '__main__':
    doctest.testmod()