~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 12:46:24 UTC
  • Revision ID: william.grant@canonical.com-20120122124624-of899x94i30q946p
Do backward correctly.

Show diffs side-by-side

added added

removed removed

Lines of Context:
14
14
# License along with this program. If not, see
15
15
# <http://www.gnu.org/licenses/>.
16
16
 
17
 
import calendar
18
17
import datetime
 
18
import dateutil.tz
19
19
import email.parser
20
20
from email.utils import parsedate_tz
21
 
import functools
22
21
import logging
23
22
import uuid
24
23
 
25
 
import dateutil.tz
26
 
import pycassa.pool
 
24
import pycassa
27
25
from pycassa.system_manager import (
28
26
    LEXICAL_UUID_TYPE,
29
27
    SystemManager,
30
28
    TIME_UUID_TYPE,
31
29
    )
32
 
from pycassa.util import convert_time_to_uuid
33
30
 
34
31
from grackle.cassandra import workaround_1779
35
32
 
81
78
    return date, message_dict
82
79
 
83
80
 
84
 
def _utc_datetime(dt):
85
 
    return dt.astimezone(dateutil.tz.tzutc())
86
 
 
87
 
 
88
 
def _utc_timestamp(dt):
89
 
    return calendar.timegm(_utc_datetime(dt).timetuple())
90
 
 
91
 
 
92
 
def _utc_timeuuid(dt, lowest_val=True):
93
 
    return convert_time_to_uuid(_utc_timestamp(dt), lowest_val)
94
 
 
95
 
 
96
 
def _cmp_timeuuid(a, b):
97
 
    if a.time != b.time:
98
 
        return cmp(a.time, b.time)
99
 
    return cmp(a, b)
100
 
 
101
 
 
102
 
def _bound_timeuuid(a, b, max=False):
103
 
    if a == '' or _cmp_timeuuid(b, a) == (1 if max else -1):
104
 
        return b
105
 
    return a
106
 
 
107
 
 
108
 
def _make_bounds(memo, range_start, range_finish, backward):
109
 
    start = finish = ''
110
 
    if memo != '':
111
 
        memo = uuid.UUID(memo)
112
 
    if backward:
113
 
        finish = memo
114
 
    else:
115
 
        start = memo
116
 
    if range_start is not None:
117
 
        start = _bound_timeuuid(
118
 
            start, _utc_timeuuid(range_start), max=True)
119
 
    if range_finish is not None:
120
 
        finish = _bound_timeuuid(
121
 
            finish, _utc_timeuuid(range_finish, lowest_val=False))
122
 
    return memo, start, finish
123
 
 
124
 
 
125
 
LEGAL_HEADERS = set([
126
 
    'date', 'from', 'subject', 'message-id',
127
 
    ])
128
 
 
129
 
 
130
 
def _format_message(message, headers=[], include_raw=False):
131
 
    data = {}
132
 
 
133
 
    if headers:
134
 
        assert not set(headers).difference(LEGAL_HEADERS)
135
 
        hdict = {}
136
 
        for header in headers:
137
 
            hdict[header] = message.get(header)
138
 
        data['headers'] = hdict
139
 
 
140
 
    if include_raw:
141
 
        data['raw'] = message['raw']
142
 
 
143
 
    return data
144
 
 
145
 
 
146
81
class CassandraConnection(object):
147
82
 
148
 
    def __init__(self, keyspace, hosts):
 
83
    def __init__(self, keyspace, host):
149
84
        self._keyspace = keyspace
150
 
        self._hosts = hosts
 
85
        self._host = host
151
86
        self._connection = self._connect()
152
 
        self._pool = self._connect()
153
87
        self.messages = self._column_family('message')
154
88
        self.archive_messages = self._column_family('archive_message')
155
89
 
156
90
    def _connect(self):
157
 
        return pycassa.pool.ConnectionPool(self._keyspace, self._hosts)
 
91
        return pycassa.connect(self._keyspace, self._host)
158
92
 
159
93
    def _column_family(self, name):
160
 
        return pycassa.ColumnFamily(self._pool, name)
 
94
        return pycassa.ColumnFamily(self._connection, name)
161
95
 
162
96
    def add_message(self, archive_uuid, message):
163
97
        message_uuid = uuid.uuid4()
164
98
        message_date, message_dict = _parse_message(message)
165
 
        message_dict['raw'] = message
 
99
        message_dict['content'] = message
166
100
        message_dict['date_created'] = (
167
101
            datetime.datetime.utcnow().isoformat() + 'Z')
168
102
        self.messages.insert(message_uuid, message_dict)
169
103
        self.archive_messages.insert(
170
104
            archive_uuid,
171
 
            {_utc_timestamp(message_date): message_uuid})
 
105
            {message_date.astimezone(dateutil.tz.tzutc()): message_uuid})
172
106
        logging.debug(
173
107
            'Imported %s into %s'
174
108
            % (message_dict.get('message-id', None), archive_uuid))
175
109
        return message_uuid
176
110
 
 
111
    def _format_message(self, message):
 
112
        return {
 
113
            'date': message.get('date'),
 
114
            'from': message.get('from'),
 
115
            'subject': message.get('subject'),
 
116
            'message-id': message.get('message-id'),
 
117
            }
 
118
 
177
119
    def _trim(self, sequence, end):
178
 
        """Return the sequence with one of the ends trimmed.
179
 
 
180
 
        :param end: if true, remove the last element. otherwise remove
181
 
            the first.
182
 
        """
183
120
        if end:
184
121
            return sequence[:-1]
185
122
        else:
186
123
            return sequence[1:]
187
124
 
188
 
    def get_messages(self, archive_uuid, order, count, memo, backward=False,
189
 
                     start_date=None, finish_date=None, format='all',
190
 
                     headers=['from', 'date', 'subject', 'message-id']):
 
125
    def get_messages(self, archive_uuid, order, count, memo, backward=False):
191
126
        if order in ("date", "-date"):
192
127
            reversed = order[0] == '-'
193
128
        else:
194
129
            raise AssertionError("Unsupported order.")
195
 
 
196
 
        memo, start, finish = _make_bounds(
197
 
            memo, start_date, finish_date, backward)
198
 
 
 
130
        if memo != '':
 
131
            memo = uuid.UUID(memo)
199
132
        # Get up to n+1 messages from the memo: the last item of the
200
133
        # previous batch (because that's where the memo starts) + this
201
134
        # batch.
 
135
        if backward:
 
136
            start = ''
 
137
            finish = memo
 
138
        else:
 
139
            start = memo
 
140
            finish = ''
202
141
        pairs = self.archive_messages.get(
203
142
            archive_uuid, column_count=count + 1, column_start=start,
204
143
            column_finish=finish, column_reversed=reversed).items()
205
 
 
206
 
        if len(pairs) and memo and pairs[0][0] <= memo:
207
 
            # The memo (from the previous batch) was included in the result.
208
 
            # Trim it.
 
144
        if memo and len(pairs) and pairs[0][0] <= memo:
209
145
            pairs = self._trim(pairs, False ^ backward)
210
146
        elif len(pairs) > count:
211
 
            # There was no memo in the result, so the n+1th element is
212
 
            # unnecessary. Kill it.
213
147
            pairs = self._trim(pairs, True ^ backward)
214
148
 
215
149
        if len(pairs) == 0:
217
151
 
218
152
        assert 0 < len(pairs) <= count
219
153
 
220
 
        # We've narrowed down the message references. Fetch the messages.
221
154
        ids = [v for k, v in pairs]
222
 
        formatter = functools.partial(
223
 
            _format_message, headers=headers, include_raw=True)
224
 
        # XXX: No need to get all columns. Restrict based on format.
225
 
        messages = self.messages.multiget(ids)
 
155
        messages = self.messages.multiget(
 
156
            ids, columns=['date', 'from', 'subject', 'message-id'])
226
157
 
227
158
        return (
228
159
            str(pairs[0][0]),
229
 
            [formatter(messages[id]) for id in ids],
 
160
            [self._format_message(messages[id]) for id in ids],
230
161
            str(pairs[-1][0]),
231
162
            )