File: databasesanity.py

package info (click to toggle)
miro 3.0.3-1
  • links: PTS
  • area: main
  • in suites: squeeze
  • size: 36,056 kB
  • ctags: 9,438
  • sloc: python: 52,860; cpp: 832; ansic: 692; xml: 432; sh: 403; makefile: 62
file content (224 lines) | stat: -rw-r--r-- 8,583 bytes parent folder | download
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
# Miro - an RSS based video player application
# Copyright (C) 2005-2010 Participatory Culture Foundation
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
#
# In addition, as a special exception, the copyright holders give
# permission to link the code of portions of this program with the OpenSSL
# library.
#
# You must obey the GNU General Public License in all respects for all of
# the code used other than OpenSSL. If you modify file(s) with this
# exception, you may extend this exception to your version of the file(s),
# but you are not obligated to do so. If you do not wish to do so, delete
# this exception statement from your version. If you delete this exception
# statement from all source files in the program, then also delete it here.

"""Sanity checks for the databases.

.. note::

    This module is deprecated: database sanity checking is done by the
    ``check_constraints`` method on DDBObjects.  This is a better way
    to do things because it will catch errors right when we save
    objects, instead of some unknown point in the future.  We still
    have this code around, because it's used to do sanity checks on
    old databases in ``convert20database``.
"""

from miro import item
from miro import feed
from miro import signals
from miro import guide

class DatabaseInsaneError(Exception):
    pass

class SanityTest(object):
    """Base class for the sanity test objects."""

    def check_object(self, obj):
        """``check_object`` will be called for each object in the
        object list.  If there is an error return a string describing
        it.  If not return None (or just let the function hit the
        bottom).
        """
        raise NotImplementedError()

    def finished(self):
        """Called when we reach the end of the object list,
        ``SanityTest`` subclasses may implement additional checking
        here.
        """
        return

    def fix_if_possible(self, object_list):
        """Subclasses may implement this method if it's possible to
        fix broken databases.  The default implementation just raises
        a ``DatabaseInsaneError``.
        """
        raise DatabaseInsaneError()

class PhantomFeedTest(SanityTest):
    """Check that no items reference a Feed that isn't around anymore.
    """
    def __init__(self):
        self.feeds_in_items = set()
        self.top_level_feeds = set()
        self.parents_in_items = set()
        self.top_level_parents = set()

    def check_object(self, obj):
        if isinstance(obj, item.Item):
            if obj.feed_id is not None:
                self.feeds_in_items.add(obj.feed_id)
            if obj.parent_id is not None:
                self.parents_in_items.add(obj.parent_id)
            if obj.isContainerItem in (None, True):
                self.top_level_parents.add(obj.id)
        elif isinstance(obj, feed.Feed):
            self.top_level_feeds.add(obj.id)

    def finished(self):
        if not self.feeds_in_items.issubset(self.top_level_feeds):
            phantoms = self.feeds_in_items.difference(self.top_level_feeds)
            phantoms_string = ', '.join([str(p) for p in phantoms])
            return "Phantom feed(s) referenced in items: %s" % phantoms_string
        if not self.parents_in_items.issubset(self.top_level_parents):
            phantoms = self.parents_in_items.difference(self.top_level_parents)
            phantoms_string = ', '.join([str(p) for p in phantoms])
            return "Phantom items(s) referenced in items: %s" % phantoms_string

    def fix_if_possible(self, object_list):
        for i in reversed(xrange(len(object_list))):
            if ((isinstance(object_list[i], item.Item) and
                 object_list[i].feed_id is not None and
                 object_list[i].feed_id not in self.top_level_feeds)):
                del object_list[i]
            elif (isinstance(object_list[i], item.Item) and
                  object_list[i].parent_id is not None and
                  object_list[i].parent_id not in self.top_level_parents):
                del object_list[i]

class SingletonTest(SanityTest):
    """Check that singleton DB objects are really singletons.

    This is a baseclass for the channle guide test, manual feed test, etc.
    """
    singletonName = ""

    def __init__(self):
        self.count = 0

    def object_is_singleton(self, obj):
        raise NotImplementedError()

    def check_object(self, obj):
        if self.object_is_singleton(obj):
            self.count += 1
            if self.count > 1:
                return "Extra %s in database" % self.singletonName

    def finished(self):
        if self.count == 0:
            # For all our singletons (currently at least), we don't need to
            # create them here.  It'll happen when Miro is restarted.
            # return "No %s in database" % self.singletonName
            pass

    def fix_if_possible(self, object_list):
        if self.count == 0:
            # For all our singletons (currently at least), we don't need to
            # create them here.  It'll happen when Miro is restarted.
            return
        else:
            seen_object = False
            for i in reversed(xrange(len(object_list))):
                if self.object_is_singleton(object_list[i]):
                    if seen_object:
                        del object_list[i]
                    else:
                        seen_object = True

class ChannelGuideSingletonTest(SingletonTest):
    singletonName = "Channel Guide"
    def object_is_singleton(self, obj):
        return isinstance(obj, guide.ChannelGuide) and obj.url is None

class ManualFeedSingletonTest(SingletonTest):
    singletonName = "Manual Feed"
    def object_is_singleton(self, obj):
        return (isinstance(obj, feed.Feed) and
                isinstance(obj.actualFeed, feed.ManualFeedImpl))

def check_sanity(object_list, fix_if_possible=True, quiet=False,
                 really_quiet=False):
    """Do all sanity checks on a list of objects.

    If fix_if_possible is True, the sanity checks will try to fix
    errors.  If this happens object_list will be modified.

    If fix_if_possible is False, or if it's not possible to fix the
    errors check_sanity will raise a DatabaseInsaneError.

    If quiet is True, we print to the log instead of poping up an
    error dialog on fixable problems.  We set this when we are
    converting old databases, since sanity errors are somewhat
    expected.

    If really_quiet is True, won't even print out a warning on fixable
    problems.

    Returns True if the database passed all sanity tests, false
    otherwise.
    """
    tests = set([
        PhantomFeedTest(),
        ChannelGuideSingletonTest(),
        ManualFeedSingletonTest(),
    ])

    errors = []
    failed_tests = set()
    for obj in object_list:
        for test in tests:
            rv = test.check_object(obj)
            if rv is not None:
                errors.append(rv)
                failed_tests.add(test)
        tests = tests.difference(failed_tests)
    for test in tests:
        rv = test.finished()
        if rv is not None:
            errors.append(rv)
            failed_tests.add(test)

    if errors:
        error = "The database failed the following sanity tests:\n"
        error += "\n".join(errors)
        if fix_if_possible:
            if not quiet:
                signals.system.failed(when="While checking database",
                                      details=error)
            elif not really_quiet:
                print "WARNING: Database sanity error"
                print error
            for test in failed_tests:
                test.fix_if_possible(object_list)
                # fix_if_possible will throw a DatabaseInsaneError if
                # it fails, which we let get raised to our caller
        else:
            raise DatabaseInsaneError(error)
    return (errors == [])