8
by William Grant
A little bit of server. |
1 |
# Copyright (c) 2012 Canonical Ltd
|
2 |
#
|
|
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.
|
|
7 |
#
|
|
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.
|
|
12 |
#
|
|
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/>.
|
|
16 |
||
17 |
import datetime |
|
9
by William Grant
Extract some message metadata. Log betterer. |
18 |
import dateutil.tz |
19 |
import email.parser |
|
20 |
from email.utils import parsedate_tz |
|
21 |
import logging |
|
8
by William Grant
A little bit of server. |
22 |
import uuid |
23 |
||
24 |
import pycassa |
|
25 |
from pycassa.system_manager import ( |
|
26 |
LEXICAL_UUID_TYPE, |
|
27 |
SystemManager, |
|
28 |
TIME_UUID_TYPE, |
|
29 |
)
|
|
30 |
||
21
by William Grant
Merge grackle.server into grackle. Alter Makefile to run all the tests. |
31 |
from grackle.cassandra import workaround_1779 |
8
by William Grant
A little bit of server. |
32 |
|
33 |
||
19
by William Grant
grackle-create-instance can now create the keyspace too. |
34 |
def create_schema(host, keyspace, clobber=False, create_keyspace=False): |
8
by William Grant
A little bit of server. |
35 |
mgr = SystemManager(host) |
36 |
||
19
by William Grant
grackle-create-instance can now create the keyspace too. |
37 |
if create_keyspace: |
38 |
mgr.create_keyspace(keyspace, replication_factor=1) |
|
39 |
||
8
by William Grant
A little bit of server. |
40 |
if clobber: |
41 |
for cf in mgr.get_keyspace_column_families(keyspace): |
|
42 |
mgr.drop_column_family(keyspace, cf) |
|
43 |
||
44 |
try: |
|
45 |
workaround_1779( |
|
46 |
mgr.create_column_family, keyspace, 'message', |
|
47 |
key_validation_class=LEXICAL_UUID_TYPE) |
|
48 |
workaround_1779( |
|
49 |
mgr.create_column_family, keyspace, 'archive_message', |
|
50 |
comparator_type=TIME_UUID_TYPE, |
|
51 |
default_validation_class=LEXICAL_UUID_TYPE) |
|
52 |
pass
|
|
53 |
finally: |
|
54 |
mgr.close() |
|
55 |
||
56 |
||
17
by William Grant
Turn _parse_message into a non-member function. |
57 |
def _parse_message(message): |
58 |
"""Get a date and dict of an RFC822 message."""
|
|
59 |
parsed = email.parser.Parser().parsestr(message) |
|
60 |
message_dict = {} |
|
61 |
||
62 |
for key in ('from', 'to', 'subject', 'message-id'): |
|
63 |
value = parsed.get(key, None) |
|
64 |
if value is not None: |
|
65 |
message_dict[key] = value |
|
66 |
||
67 |
date = parsed.get('date') |
|
68 |
if date is not None: |
|
69 |
try: |
|
70 |
pdate = parsedate_tz(date) |
|
71 |
date = datetime.datetime( |
|
72 |
*pdate[:6], |
|
73 |
tzinfo=dateutil.tz.tzoffset('', pdate[9])) |
|
74 |
except ValueError: |
|
75 |
pass
|
|
76 |
message_dict['date'] = date.isoformat() if date is not None else None |
|
77 |
||
78 |
return date, message_dict |
|
79 |
||
80 |
||
8
by William Grant
A little bit of server. |
81 |
class CassandraConnection(object): |
82 |
||
83 |
def __init__(self, keyspace, host): |
|
84 |
self._keyspace = keyspace |
|
85 |
self._host = host |
|
86 |
self._connection = self._connect() |
|
87 |
self.messages = self._column_family('message') |
|
88 |
self.archive_messages = self._column_family('archive_message') |
|
89 |
||
90 |
def _connect(self): |
|
91 |
return pycassa.connect(self._keyspace, self._host) |
|
92 |
||
93 |
def _column_family(self, name): |
|
94 |
return pycassa.ColumnFamily(self._connection, name) |
|
95 |
||
14
by William Grant
Refactor. |
96 |
def add_message(self, archive_uuid, message): |
97 |
message_uuid = uuid.uuid4() |
|
17
by William Grant
Turn _parse_message into a non-member function. |
98 |
message_date, message_dict = _parse_message(message) |
16
by William Grant
message content isn't always included. |
99 |
message_dict['content'] = message |
15
by William Grant
date_created is no longer part of the original message dict. |
100 |
message_dict['date_created'] = ( |
101 |
datetime.datetime.utcnow().isoformat() + 'Z') |
|
14
by William Grant
Refactor. |
102 |
self.messages.insert(message_uuid, message_dict) |
8
by William Grant
A little bit of server. |
103 |
self.archive_messages.insert( |
9
by William Grant
Extract some message metadata. Log betterer. |
104 |
archive_uuid, |
14
by William Grant
Refactor. |
105 |
{message_date.astimezone(dateutil.tz.tzutc()): message_uuid}) |
9
by William Grant
Extract some message metadata. Log betterer. |
106 |
logging.debug( |
14
by William Grant
Refactor. |
107 |
'Imported %s into %s' |
108 |
% (message_dict.get('message-id', None), archive_uuid)) |
|
8
by William Grant
A little bit of server. |
109 |
return message_uuid |
110 |
||
9
by William Grant
Extract some message metadata. Log betterer. |
111 |
def _format_message(self, message): |
112 |
return { |
|
14
by William Grant
Refactor. |
113 |
'date': message.get('date'), |
114 |
'from': message.get('from'), |
|
115 |
'subject': message.get('subject'), |
|
23
by William Grant
Include message-id in the result. |
116 |
'message-id': message.get('message-id'), |
9
by William Grant
Extract some message metadata. Log betterer. |
117 |
}
|
118 |
||
29
by William Grant
Do backward correctly. |
119 |
def _trim(self, sequence, end): |
30
by William Grant
Comment and document. |
120 |
"""Return the sequence with one of the ends trimmed.
|
121 |
||
122 |
:param end: if true, remove the last element. otherwise remove
|
|
123 |
the first.
|
|
124 |
"""
|
|
29
by William Grant
Do backward correctly. |
125 |
if end: |
126 |
return sequence[:-1] |
|
127 |
else: |
|
128 |
return sequence[1:] |
|
129 |
||
130 |
def get_messages(self, archive_uuid, order, count, memo, backward=False): |
|
10
by William Grant
Let the HTTP client decide count and order (to an extent). |
131 |
if order in ("date", "-date"): |
132 |
reversed = order[0] == '-' |
|
133 |
else: |
|
134 |
raise AssertionError("Unsupported order.") |
|
27
by William Grant
Fix batching to almost work backwards too. |
135 |
if memo != '': |
136 |
memo = uuid.UUID(memo) |
|
29
by William Grant
Do backward correctly. |
137 |
if backward: |
138 |
start = '' |
|
139 |
finish = memo |
|
140 |
else: |
|
141 |
start = memo |
|
142 |
finish = '' |
|
30
by William Grant
Comment and document. |
143 |
|
144 |
# Get up to n+1 messages from the memo: the last item of the
|
|
145 |
# previous batch (because that's where the memo starts) + this
|
|
146 |
# batch.
|
|
11
by William Grant
Support batching. |
147 |
pairs = self.archive_messages.get( |
29
by William Grant
Do backward correctly. |
148 |
archive_uuid, column_count=count + 1, column_start=start, |
149 |
column_finish=finish, column_reversed=reversed).items() |
|
30
by William Grant
Comment and document. |
150 |
|
151 |
if len(pairs) and memo and pairs[0][0] <= memo: |
|
152 |
# The memo (from the previous batch) was included in the result.
|
|
153 |
# Trim it.
|
|
29
by William Grant
Do backward correctly. |
154 |
pairs = self._trim(pairs, False ^ backward) |
27
by William Grant
Fix batching to almost work backwards too. |
155 |
elif len(pairs) > count: |
30
by William Grant
Comment and document. |
156 |
# There was no memo in the result, so the n+1th element is
|
157 |
# unnecessary. Kill it.
|
|
29
by William Grant
Do backward correctly. |
158 |
pairs = self._trim(pairs, True ^ backward) |
27
by William Grant
Fix batching to almost work backwards too. |
159 |
|
160 |
if len(pairs) == 0: |
|
161 |
return (None, [], None) |
|
162 |
||
163 |
assert 0 < len(pairs) <= count |
|
164 |
||
30
by William Grant
Comment and document. |
165 |
# We've narrowed down the message references. Fetch the messages.
|
11
by William Grant
Support batching. |
166 |
ids = [v for k, v in pairs] |
167 |
messages = self.messages.multiget( |
|
23
by William Grant
Include message-id in the result. |
168 |
ids, columns=['date', 'from', 'subject', 'message-id']) |
27
by William Grant
Fix batching to almost work backwards too. |
169 |
|
11
by William Grant
Support batching. |
170 |
return ( |
27
by William Grant
Fix batching to almost work backwards too. |
171 |
str(pairs[0][0]), |
172 |
[self._format_message(messages[id]) for id in ids], |
|
173 |
str(pairs[-1][0]), |
|
11
by William Grant
Support batching. |
174 |
)
|