~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-22 10:39:15 UTC
  • Revision ID: william.grant@canonical.com-20120122103915-lqjw4jsaw3ug1q2g
Merge grackle.server into grackle. Alter Makefile to run all the tests.

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
23
22
import uuid
24
23
 
25
24
import pycassa
28
27
    SystemManager,
29
28
    TIME_UUID_TYPE,
30
29
    )
31
 
from pycassa.util import convert_time_to_uuid
32
30
 
33
31
from grackle.cassandra import workaround_1779
34
32
 
80
78
    return date, message_dict
81
79
 
82
80
 
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
 
 
107
 
def _make_bounds(memo, range_start, range_finish, backward):
108
 
    start = finish = ''
109
 
    if memo != '':
110
 
        memo = uuid.UUID(memo)
111
 
    if backward:
112
 
        finish = memo
113
 
    else:
114
 
        start = memo
115
 
    if range_start is not None:
116
 
        start = _bound_timeuuid(
117
 
            start, _utc_timeuuid(range_start), max=True)
118
 
    if range_finish is not None:
119
 
        finish = _bound_timeuuid(
120
 
            finish, _utc_timeuuid(range_finish, lowest_val=False))
121
 
    return memo, start, finish
122
 
 
123
 
 
124
 
def _format_message(message):
125
 
    return {
126
 
        'date': message.get('date'),
127
 
        'from': message.get('from'),
128
 
        'subject': message.get('subject'),
129
 
        'message-id': message.get('message-id'),
130
 
        'content': message.get('content'),
131
 
        }
132
 
 
133
 
 
134
81
class CassandraConnection(object):
135
82
 
136
83
    def __init__(self, keyspace, host):
155
102
        self.messages.insert(message_uuid, message_dict)
156
103
        self.archive_messages.insert(
157
104
            archive_uuid,
158
 
            {_utc_timestamp(message_date): message_uuid})
 
105
            {message_date.astimezone(dateutil.tz.tzutc()): message_uuid})
159
106
        logging.debug(
160
107
            'Imported %s into %s'
161
108
            % (message_dict.get('message-id', None), archive_uuid))
162
109
        return message_uuid
163
110
 
164
 
    def _trim(self, sequence, end):
165
 
        """Return the sequence with one of the ends trimmed.
166
 
 
167
 
        :param end: if true, remove the last element. otherwise remove
168
 
            the first.
169
 
        """
170
 
        if end:
171
 
            return sequence[:-1]
172
 
        else:
173
 
            return sequence[1:]
174
 
 
175
 
    def get_messages(self, archive_uuid, order, count, memo, backward=False,
176
 
                     start_date=None, finish_date=None):
 
111
    def _format_message(self, message):
 
112
        return {
 
113
            'date': message.get('date'),
 
114
            'from': message.get('from'),
 
115
            'subject': message.get('subject'),
 
116
            }
 
117
 
 
118
    def get_messages(self, archive_uuid, order, count, start):
177
119
        if order in ("date", "-date"):
178
120
            reversed = order[0] == '-'
179
121
        else:
180
122
            raise AssertionError("Unsupported order.")
181
 
 
182
 
        memo, start, finish = _make_bounds(
183
 
            memo, start_date, finish_date, backward)
184
 
 
185
 
        # Get up to n+1 messages from the memo: the last item of the
186
 
        # previous batch (because that's where the memo starts) + this
187
 
        # batch.
188
123
        pairs = self.archive_messages.get(
189
 
            archive_uuid, column_count=count + 1, column_start=start,
190
 
            column_finish=finish, column_reversed=reversed).items()
191
 
 
192
 
        if len(pairs) and memo and pairs[0][0] <= memo:
193
 
            # The memo (from the previous batch) was included in the result.
194
 
            # Trim it.
195
 
            pairs = self._trim(pairs, False ^ backward)
196
 
        elif len(pairs) > count:
197
 
            # There was no memo in the result, so the n+1th element is
198
 
            # unnecessary. Kill it.
199
 
            pairs = self._trim(pairs, True ^ backward)
200
 
 
201
 
        if len(pairs) == 0:
202
 
            return (None, [], None)
203
 
 
204
 
        assert 0 < len(pairs) <= count
205
 
 
206
 
        # We've narrowed down the message references. Fetch the messages.
 
124
            archive_uuid, column_count=count + 1,
 
125
            column_start=start, column_reversed=reversed).items()
207
126
        ids = [v for k, v in pairs]
208
127
        messages = self.messages.multiget(
209
 
            ids, columns=['date', 'from', 'subject', 'message-id', 'content'])
210
 
 
 
128
            ids, columns=['date', 'from', 'subject'])
 
129
        actual_count = len(pairs)
 
130
        if len(pairs) > count:
 
131
            assert len(pairs) == count + 1
 
132
            actual_count -= 1
 
133
            next_memo = str(pairs[count][0])
 
134
        else:
 
135
            next_memo = None
211
136
        return (
212
 
            str(pairs[0][0]),
213
 
            [_format_message(messages[id]) for id in ids],
214
 
            str(pairs[-1][0]),
 
137
            [self._format_message(messages[id]) for id in ids[:actual_count]],
 
138
            next_memo,
215
139
            )