~unity-2d-team/unity-2d/Shell-MultiMonitor

« back to all changes in this revision

Viewing changes to grackle/model.py

  • Committer: William Grant
  • Date: 2012-01-23 00:16:32 UTC
  • Revision ID: william.grant@canonical.com-20120123001632-z6dig91md7qu91f6
Date filtering.

Show diffs side-by-side

added added

removed removed

Lines of Context:
19
19
import email.parser
20
20
from email.utils import parsedate_tz
21
21
import logging
 
22
import time
22
23
import uuid
23
24
 
24
25
import pycassa
27
28
    SystemManager,
28
29
    TIME_UUID_TYPE,
29
30
    )
30
 
 
31
 
from grackle.server.cassandra import workaround_1779
32
 
 
33
 
 
34
 
def create_schema(host, keyspace, clobber=False):
 
31
from pycassa.util import convert_time_to_uuid
 
32
 
 
33
from grackle.cassandra import workaround_1779
 
34
 
 
35
 
 
36
def create_schema(host, keyspace, clobber=False, create_keyspace=False):
35
37
    mgr = SystemManager(host)
36
38
 
 
39
    if create_keyspace:
 
40
        mgr.create_keyspace(keyspace, replication_factor=1)
 
41
 
37
42
    if clobber:
38
43
        for cf in mgr.get_keyspace_column_families(keyspace):
39
44
            mgr.drop_column_family(keyspace, cf)
75
80
    return date, message_dict
76
81
 
77
82
 
 
83
def _utc_datetime(dt):
 
84
    return dt.astimezone(dateutil.tz.tzutc())
 
85
 
 
86
 
 
87
def _utc_timestamp(dt):
 
88
    return time.mktime(_utc_datetime(dt).timetuple()) - time.timezone
 
89
 
 
90
 
 
91
def _utc_timeuuid(dt, lowest_val=True):
 
92
    return convert_time_to_uuid(_utc_timestamp(dt), lowest_val)
 
93
 
 
94
 
 
95
def _cmp_timeuuid(a, b):
 
96
    if a.time != b.time:
 
97
        return cmp(a.time, b.time)
 
98
    return cmp(a, b)
 
99
 
 
100
 
 
101
def _bound_timeuuid(a, b, max=False):
 
102
    if a == '' or _cmp_timeuuid(b, a) == (1 if max else -1):
 
103
        return b
 
104
    return a
 
105
 
 
106
 
78
107
class CassandraConnection(object):
79
108
 
80
109
    def __init__(self, keyspace, host):
99
128
        self.messages.insert(message_uuid, message_dict)
100
129
        self.archive_messages.insert(
101
130
            archive_uuid,
102
 
            {message_date.astimezone(dateutil.tz.tzutc()): message_uuid})
 
131
            {_utc_timestamp(message_date): message_uuid})
103
132
        logging.debug(
104
133
            'Imported %s into %s'
105
134
            % (message_dict.get('message-id', None), archive_uuid))
110
139
            'date': message.get('date'),
111
140
            'from': message.get('from'),
112
141
            'subject': message.get('subject'),
 
142
            'message-id': message.get('message-id'),
113
143
            }
114
144
 
115
 
    def get_messages(self, archive_uuid, order, count, start):
 
145
    def _trim(self, sequence, end):
 
146
        """Return the sequence with one of the ends trimmed.
 
147
 
 
148
        :param end: if true, remove the last element. otherwise remove
 
149
            the first.
 
150
        """
 
151
        if end:
 
152
            return sequence[:-1]
 
153
        else:
 
154
            return sequence[1:]
 
155
 
 
156
    def get_messages(self, archive_uuid, order, count, memo, backward=False,
 
157
                     start_date=None, finish_date=None):
116
158
        if order in ("date", "-date"):
117
159
            reversed = order[0] == '-'
118
160
        else:
119
161
            raise AssertionError("Unsupported order.")
 
162
        if memo != '':
 
163
            memo = uuid.UUID(memo)
 
164
        if backward:
 
165
            start = ''
 
166
            finish = memo
 
167
        else:
 
168
            start = memo
 
169
            finish = ''
 
170
        if start_date is not None:
 
171
            start = _bound_timeuuid(
 
172
                start, _utc_timeuuid(start_date, lowest_val=False), max=True)
 
173
        if finish_date is not None:
 
174
            finish = _bound_timeuuid(
 
175
                finish, _utc_timeuuid(finish_date, lowest_val=False))
 
176
 
 
177
        # Get up to n+1 messages from the memo: the last item of the
 
178
        # previous batch (because that's where the memo starts) + this
 
179
        # batch.
120
180
        pairs = self.archive_messages.get(
121
 
            archive_uuid, column_count=count + 1,
122
 
            column_start=start, column_reversed=reversed).items()
 
181
            archive_uuid, column_count=count + 1, column_start=start,
 
182
            column_finish=finish, column_reversed=reversed).items()
 
183
 
 
184
        if len(pairs) and memo and pairs[0][0] <= memo:
 
185
            # The memo (from the previous batch) was included in the result.
 
186
            # Trim it.
 
187
            pairs = self._trim(pairs, False ^ backward)
 
188
        elif len(pairs) > count:
 
189
            # There was no memo in the result, so the n+1th element is
 
190
            # unnecessary. Kill it.
 
191
            pairs = self._trim(pairs, True ^ backward)
 
192
 
 
193
        if len(pairs) == 0:
 
194
            return (None, [], None)
 
195
 
 
196
        assert 0 < len(pairs) <= count
 
197
 
 
198
        # We've narrowed down the message references. Fetch the messages.
123
199
        ids = [v for k, v in pairs]
124
200
        messages = self.messages.multiget(
125
 
            ids, columns=['date', 'from', 'subject'])
126
 
        actual_count = len(pairs)
127
 
        if len(pairs) > count:
128
 
            assert len(pairs) == count + 1
129
 
            actual_count -= 1
130
 
            next_memo = str(pairs[count][0])
131
 
        else:
132
 
            next_memo = None
 
201
            ids, columns=['date', 'from', 'subject', 'message-id'])
 
202
 
133
203
        return (
134
 
            [self._format_message(messages[id]) for id in ids[:actual_count]],
135
 
            next_memo,
 
204
            str(pairs[0][0]),
 
205
            [self._format_message(messages[id]) for id in ids],
 
206
            str(pairs[-1][0]),
136
207
            )