1
# Copyright (c) 2012 Canonical Ltd
3
# This program is free software: you can redistribute it and/or modify
4
# it under the terms of the GNU Affero General Public License as published by
5
# the Free Software Foundation, either version 3 of the License, or
6
# (at your option) any later version.
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
# GNU Affero General Public License for more details.
13
# You should have received a copy of the GNU Affero General Public
14
# License along with this program. If not, see
15
# <http://www.gnu.org/licenses/>.
20
from email.utils import parsedate_tz
27
from pycassa.system_manager import (
32
from pycassa.util import convert_time_to_uuid
34
from grackle.cassandra import workaround_1779
37
def create_schema(host, keyspace, clobber=False, create_keyspace=False):
38
mgr = SystemManager(host)
41
mgr.create_keyspace(keyspace, replication_factor=1)
44
for cf in mgr.get_keyspace_column_families(keyspace):
45
mgr.drop_column_family(keyspace, cf)
49
mgr.create_column_family, keyspace, 'message',
50
key_validation_class=LEXICAL_UUID_TYPE)
52
mgr.create_column_family, keyspace, 'archive_message',
53
comparator_type=TIME_UUID_TYPE,
54
default_validation_class=LEXICAL_UUID_TYPE)
60
def _parse_message(message):
61
"""Get a date and dict of an RFC822 message."""
62
parsed = email.parser.Parser().parsestr(message)
65
for key in ('from', 'to', 'subject', 'message-id'):
66
value = parsed.get(key, None)
68
message_dict[key] = value
70
date = parsed.get('date')
73
pdate = parsedate_tz(date)
74
date = datetime.datetime(
76
tzinfo=dateutil.tz.tzoffset('', pdate[9]))
79
message_dict['date'] = date.isoformat() if date is not None else None
81
return date, message_dict
84
def _utc_datetime(dt):
85
return dt.astimezone(dateutil.tz.tzutc())
88
def _utc_timestamp(dt):
89
return time.mktime(_utc_datetime(dt).timetuple()) - time.timezone
92
def _utc_timeuuid(dt, lowest_val=True):
93
return convert_time_to_uuid(_utc_timestamp(dt), lowest_val)
96
def _cmp_timeuuid(a, b):
98
return cmp(a.time, b.time)
102
def _bound_timeuuid(a, b, max=False):
103
if a == '' or _cmp_timeuuid(b, a) == (1 if max else -1):
108
def _make_bounds(memo, range_start, range_finish, backward):
111
memo = uuid.UUID(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
125
LEGAL_HEADERS = set([
126
'date', 'from', 'subject', 'message-id',
130
def _format_message(want, message):
133
data[key] = message.get(key)
137
def _format_all(headers):
138
assert not set(headers).difference(LEGAL_HEADERS)
139
want = list(headers) + ['content']
140
return want, functools.partial(_format_message, want)
148
class CassandraConnection(object):
150
def __init__(self, keyspace, host):
151
self._keyspace = keyspace
153
self._connection = self._connect()
154
self.messages = self._column_family('message')
155
self.archive_messages = self._column_family('archive_message')
158
return pycassa.connect(self._keyspace, self._host)
160
def _column_family(self, name):
161
return pycassa.ColumnFamily(self._connection, name)
163
def add_message(self, archive_uuid, message):
164
message_uuid = uuid.uuid4()
165
message_date, message_dict = _parse_message(message)
166
message_dict['content'] = message
167
message_dict['date_created'] = (
168
datetime.datetime.utcnow().isoformat() + 'Z')
169
self.messages.insert(message_uuid, message_dict)
170
self.archive_messages.insert(
172
{_utc_timestamp(message_date): message_uuid})
174
'Imported %s into %s'
175
% (message_dict.get('message-id', None), archive_uuid))
178
def _trim(self, sequence, end):
179
"""Return the sequence with one of the ends trimmed.
181
:param end: if true, remove the last element. otherwise remove
189
def get_messages(self, archive_uuid, order, count, memo, backward=False,
190
start_date=None, finish_date=None, format='all',
191
headers=['from', 'date', 'subject', 'message-id']):
192
if order in ("date", "-date"):
193
reversed = order[0] == '-'
195
raise AssertionError("Unsupported order.")
197
memo, start, finish = _make_bounds(
198
memo, start_date, finish_date, backward)
200
# Get up to n+1 messages from the memo: the last item of the
201
# previous batch (because that's where the memo starts) + this
203
pairs = self.archive_messages.get(
204
archive_uuid, column_count=count + 1, column_start=start,
205
column_finish=finish, column_reversed=reversed).items()
207
if len(pairs) and memo and pairs[0][0] <= memo:
208
# The memo (from the previous batch) was included in the result.
210
pairs = self._trim(pairs, False ^ backward)
211
elif len(pairs) > count:
212
# There was no memo in the result, so the n+1th element is
213
# unnecessary. Kill it.
214
pairs = self._trim(pairs, True ^ backward)
217
return (None, [], None)
219
assert 0 < len(pairs) <= count
221
# We've narrowed down the message references. Fetch the messages.
222
ids = [v for k, v in pairs]
224
wanted_cols, func = FORMATS[format](headers)
226
# XXX: No need to get all columns. Restrict based on format.
227
messages = self.messages.multiget(ids)
231
[func(messages[id]) for id in ids],