Merge lp:~eday/burrow/prototype-conversion into lp:burrow

Proposed by Eric Day
Status: Merged
Approved by: Eric Day
Approved revision: 2
Merged at revision: 2
Proposed branch: lp:~eday/burrow/prototype-conversion
Merge into: lp:burrow
Diff against target: 1874 lines (+1780/-0)
17 files modified
Authors (+1/-0)
ChangeLog (+4/-0)
LICENSE (+202/-0)
MANIFEST.in (+4/-0)
bin/burrow (+18/-0)
bin/burrowd (+34/-0)
burrow/__init__.py (+19/-0)
burrowd/__init__.py (+131/-0)
burrowd/backend/__init__.py (+94/-0)
burrowd/backend/memory.py (+176/-0)
burrowd/backend/sqlite.py (+250/-0)
burrowd/config.py (+55/-0)
burrowd/frontend/__init__.py (+30/-0)
burrowd/frontend/wsgi.py (+276/-0)
etc/burrowd.conf (+99/-0)
setup.py (+74/-0)
test/frontend/test_wsgi.py (+313/-0)
To merge this branch: bzr merge lp:~eday/burrow/prototype-conversion
Reviewer Review Type Date Requested Status
Burrow Core Team Pending
Review via email: mp+53928@code.launchpad.net

Description of the change

Python prototype conversion to get new trunk started.

To post a comment you must log in.

Preview Diff

[H/L] Next/Prev Comment, [J/K] Next/Prev File, [N/P] Next/Prev Hunk
=== added file 'Authors'
--- Authors 1970-01-01 00:00:00 +0000
+++ Authors 2011-03-17 23:47:24 +0000
@@ -0,0 +1,1 @@
1Eric Day <eday@oddments.org>
02
=== added file 'ChangeLog'
--- ChangeLog 1970-01-01 00:00:00 +0000
+++ ChangeLog 2011-03-17 23:47:24 +0000
@@ -0,0 +1,4 @@
12011-03-17 Eric Day <eday@oddments.org>
2
3 Created new burrow trunk.
4
05
=== added file 'LICENSE'
--- LICENSE 1970-01-01 00:00:00 +0000
+++ LICENSE 2011-03-17 23:47:24 +0000
@@ -0,0 +1,202 @@
1
2 Apache License
3 Version 2.0, January 2004
4 http://www.apache.org/licenses/
5
6 TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
8 1. Definitions.
9
10 "License" shall mean the terms and conditions for use, reproduction,
11 and distribution as defined by Sections 1 through 9 of this document.
12
13 "Licensor" shall mean the copyright owner or entity authorized by
14 the copyright owner that is granting the License.
15
16 "Legal Entity" shall mean the union of the acting entity and all
17 other entities that control, are controlled by, or are under common
18 control with that entity. For the purposes of this definition,
19 "control" means (i) the power, direct or indirect, to cause the
20 direction or management of such entity, whether by contract or
21 otherwise, or (ii) ownership of fifty percent (50%) or more of the
22 outstanding shares, or (iii) beneficial ownership of such entity.
23
24 "You" (or "Your") shall mean an individual or Legal Entity
25 exercising permissions granted by this License.
26
27 "Source" form shall mean the preferred form for making modifications,
28 including but not limited to software source code, documentation
29 source, and configuration files.
30
31 "Object" form shall mean any form resulting from mechanical
32 transformation or translation of a Source form, including but
33 not limited to compiled object code, generated documentation,
34 and conversions to other media types.
35
36 "Work" shall mean the work of authorship, whether in Source or
37 Object form, made available under the License, as indicated by a
38 copyright notice that is included in or attached to the work
39 (an example is provided in the Appendix below).
40
41 "Derivative Works" shall mean any work, whether in Source or Object
42 form, that is based on (or derived from) the Work and for which the
43 editorial revisions, annotations, elaborations, or other modifications
44 represent, as a whole, an original work of authorship. For the purposes
45 of this License, Derivative Works shall not include works that remain
46 separable from, or merely link (or bind by name) to the interfaces of,
47 the Work and Derivative Works thereof.
48
49 "Contribution" shall mean any work of authorship, including
50 the original version of the Work and any modifications or additions
51 to that Work or Derivative Works thereof, that is intentionally
52 submitted to Licensor for inclusion in the Work by the copyright owner
53 or by an individual or Legal Entity authorized to submit on behalf of
54 the copyright owner. For the purposes of this definition, "submitted"
55 means any form of electronic, verbal, or written communication sent
56 to the Licensor or its representatives, including but not limited to
57 communication on electronic mailing lists, source code control systems,
58 and issue tracking systems that are managed by, or on behalf of, the
59 Licensor for the purpose of discussing and improving the Work, but
60 excluding communication that is conspicuously marked or otherwise
61 designated in writing by the copyright owner as "Not a Contribution."
62
63 "Contributor" shall mean Licensor and any individual or Legal Entity
64 on behalf of whom a Contribution has been received by Licensor and
65 subsequently incorporated within the Work.
66
67 2. Grant of Copyright License. Subject to the terms and conditions of
68 this License, each Contributor hereby grants to You a perpetual,
69 worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70 copyright license to reproduce, prepare Derivative Works of,
71 publicly display, publicly perform, sublicense, and distribute the
72 Work and such Derivative Works in Source or Object form.
73
74 3. Grant of Patent License. Subject to the terms and conditions of
75 this License, each Contributor hereby grants to You a perpetual,
76 worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77 (except as stated in this section) patent license to make, have made,
78 use, offer to sell, sell, import, and otherwise transfer the Work,
79 where such license applies only to those patent claims licensable
80 by such Contributor that are necessarily infringed by their
81 Contribution(s) alone or by combination of their Contribution(s)
82 with the Work to which such Contribution(s) was submitted. If You
83 institute patent litigation against any entity (including a
84 cross-claim or counterclaim in a lawsuit) alleging that the Work
85 or a Contribution incorporated within the Work constitutes direct
86 or contributory patent infringement, then any patent licenses
87 granted to You under this License for that Work shall terminate
88 as of the date such litigation is filed.
89
90 4. Redistribution. You may reproduce and distribute copies of the
91 Work or Derivative Works thereof in any medium, with or without
92 modifications, and in Source or Object form, provided that You
93 meet the following conditions:
94
95 (a) You must give any other recipients of the Work or
96 Derivative Works a copy of this License; and
97
98 (b) You must cause any modified files to carry prominent notices
99 stating that You changed the files; and
100
101 (c) You must retain, in the Source form of any Derivative Works
102 that You distribute, all copyright, patent, trademark, and
103 attribution notices from the Source form of the Work,
104 excluding those notices that do not pertain to any part of
105 the Derivative Works; and
106
107 (d) If the Work includes a "NOTICE" text file as part of its
108 distribution, then any Derivative Works that You distribute must
109 include a readable copy of the attribution notices contained
110 within such NOTICE file, excluding those notices that do not
111 pertain to any part of the Derivative Works, in at least one
112 of the following places: within a NOTICE text file distributed
113 as part of the Derivative Works; within the Source form or
114 documentation, if provided along with the Derivative Works; or,
115 within a display generated by the Derivative Works, if and
116 wherever such third-party notices normally appear. The contents
117 of the NOTICE file are for informational purposes only and
118 do not modify the License. You may add Your own attribution
119 notices within Derivative Works that You distribute, alongside
120 or as an addendum to the NOTICE text from the Work, provided
121 that such additional attribution notices cannot be construed
122 as modifying the License.
123
124 You may add Your own copyright statement to Your modifications and
125 may provide additional or different license terms and conditions
126 for use, reproduction, or distribution of Your modifications, or
127 for any such Derivative Works as a whole, provided Your use,
128 reproduction, and distribution of the Work otherwise complies with
129 the conditions stated in this License.
130
131 5. Submission of Contributions. Unless You explicitly state otherwise,
132 any Contribution intentionally submitted for inclusion in the Work
133 by You to the Licensor shall be under the terms and conditions of
134 this License, without any additional terms or conditions.
135 Notwithstanding the above, nothing herein shall supersede or modify
136 the terms of any separate license agreement you may have executed
137 with Licensor regarding such Contributions.
138
139 6. Trademarks. This License does not grant permission to use the trade
140 names, trademarks, service marks, or product names of the Licensor,
141 except as required for reasonable and customary use in describing the
142 origin of the Work and reproducing the content of the NOTICE file.
143
144 7. Disclaimer of Warranty. Unless required by applicable law or
145 agreed to in writing, Licensor provides the Work (and each
146 Contributor provides its Contributions) on an "AS IS" BASIS,
147 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148 implied, including, without limitation, any warranties or conditions
149 of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150 PARTICULAR PURPOSE. You are solely responsible for determining the
151 appropriateness of using or redistributing the Work and assume any
152 risks associated with Your exercise of permissions under this License.
153
154 8. Limitation of Liability. In no event and under no legal theory,
155 whether in tort (including negligence), contract, or otherwise,
156 unless required by applicable law (such as deliberate and grossly
157 negligent acts) or agreed to in writing, shall any Contributor be
158 liable to You for damages, including any direct, indirect, special,
159 incidental, or consequential damages of any character arising as a
160 result of this License or out of the use or inability to use the
161 Work (including but not limited to damages for loss of goodwill,
162 work stoppage, computer failure or malfunction, or any and all
163 other commercial damages or losses), even if such Contributor
164 has been advised of the possibility of such damages.
165
166 9. Accepting Warranty or Additional Liability. While redistributing
167 the Work or Derivative Works thereof, You may choose to offer,
168 and charge a fee for, acceptance of support, warranty, indemnity,
169 or other liability obligations and/or rights consistent with this
170 License. However, in accepting such obligations, You may act only
171 on Your own behalf and on Your sole responsibility, not on behalf
172 of any other Contributor, and only if You agree to indemnify,
173 defend, and hold each Contributor harmless for any liability
174 incurred by, or claims asserted against, such Contributor by reason
175 of your accepting any such warranty or additional liability.
176
177 END OF TERMS AND CONDITIONS
178
179 APPENDIX: How to apply the Apache License to your work.
180
181 To apply the Apache License to your work, attach the following
182 boilerplate notice, with the fields enclosed by brackets "[]"
183 replaced with your own identifying information. (Don't include
184 the brackets!) The text should be enclosed in the appropriate
185 comment syntax for the file format. We also recommend that a
186 file or class name and description of purpose be included on the
187 same "printed page" as the copyright notice for easier
188 identification within third-party archives.
189
190 Copyright [yyyy] [name of copyright owner]
191
192 Licensed under the Apache License, Version 2.0 (the "License");
193 you may not use this file except in compliance with the License.
194 You may obtain a copy of the License at
195
196 http://www.apache.org/licenses/LICENSE-2.0
197
198 Unless required by applicable law or agreed to in writing, software
199 distributed under the License is distributed on an "AS IS" BASIS,
200 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201 See the License for the specific language governing permissions and
202 limitations under the License.
0203
=== added file 'MANIFEST.in'
--- MANIFEST.in 1970-01-01 00:00:00 +0000
+++ MANIFEST.in 2011-03-17 23:47:24 +0000
@@ -0,0 +1,4 @@
1graft etc
2include Authors
3include ChangeLog
4include LICENSE
05
=== added directory 'bin'
=== added file 'bin/burrow'
--- bin/burrow 1970-01-01 00:00:00 +0000
+++ bin/burrow 2011-03-17 23:47:24 +0000
@@ -0,0 +1,18 @@
1#!/usr/bin/env python
2# Copyright (C) 2011 OpenStack LLC.
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8# http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15
16'''
17Burrow command line client.
18'''
019
=== added file 'bin/burrowd'
--- bin/burrowd 1970-01-01 00:00:00 +0000
+++ bin/burrowd 2011-03-17 23:47:24 +0000
@@ -0,0 +1,34 @@
1#!/usr/bin/env python
2# Copyright (C) 2011 OpenStack LLC.
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8# http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15
16'''
17Burrow server.
18'''
19
20import os
21import sys
22
23# If ../burrowd/__init__.py exists, add ../ to the Python search path so
24# that it will override whatever may be installed in the default Python
25# search path.
26BASE_DIRECTORY = os.path.join(os.path.abspath(__file__), os.pardir, os.pardir)
27BASE_DIRECTORY = os.path.normpath(BASE_DIRECTORY)
28if os.path.exists(os.path.join(BASE_DIRECTORY, 'burrowd', '__init__.py')):
29 sys.path.insert(0, BASE_DIRECTORY)
30
31import burrowd
32
33if __name__ == '__main__':
34 burrowd.Burrowd(sys.argv[1:]).run()
035
=== added directory 'burrow'
=== added file 'burrow/__init__.py'
--- burrow/__init__.py 1970-01-01 00:00:00 +0000
+++ burrow/__init__.py 2011-03-17 23:47:24 +0000
@@ -0,0 +1,19 @@
1# Copyright (C) 2011 OpenStack LLC.
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
15'''Main client module for burrow.'''
16
17
18class Burrow(object):
19 pass
020
=== added directory 'burrowd'
=== added file 'burrowd/__init__.py'
--- burrowd/__init__.py 1970-01-01 00:00:00 +0000
+++ burrowd/__init__.py 2011-03-17 23:47:24 +0000
@@ -0,0 +1,131 @@
1# Copyright (C) 2011 OpenStack LLC.
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
15'''Main server module for burrow.'''
16
17import ConfigParser
18import gettext
19import logging
20import logging.config
21import sys
22
23import eventlet
24
25import burrowd.config
26
27# This installs the _(...) function as a built-in so all other modules
28# don't need to.
29gettext.install('burrowd')
30
31# Default configuration values for this module.
32DEFAULT_BACKEND = 'burrowd.backend.sqlite'
33DEFAULT_FRONTENDS = 'burrowd.frontend.wsgi'
34DEFAULT_THREAD_POOL_SIZE = 1000
35
36
37class Burrowd(object):
38 '''Server class for burrow.'''
39
40 def __init__(self, config_files=[], add_default_log_handler=True):
41 '''Initialize a server using the config files from the given
42 list. This is passed directly to ConfigParser.read(), so
43 files should be in ConfigParser format. This will load all
44 frontend and backend classes from the configuration.'''
45 if len(config_files) > 0:
46 logging.config.fileConfig(config_files)
47 self._config = ConfigParser.ConfigParser()
48 self._config.read(config_files)
49 self.config = burrowd.config.Config(self._config, 'burrowd')
50 self.log = get_logger(self.config)
51 if add_default_log_handler:
52 self._add_default_log_handler()
53 self._import_backend()
54 self._import_frontends()
55
56 def _add_default_log_handler(self):
57 '''Add a default log handler it one has not been set.'''
58 root_log = logging.getLogger()
59 if len(root_log.handlers) > 0 or len(self.log.handlers) > 0:
60 return
61 handler = logging.StreamHandler()
62 handler.setLevel(logging.DEBUG)
63 log_format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
64 handler.setFormatter(logging.Formatter(log_format))
65 root_log.addHandler(handler)
66
67 def _import_backend(self):
68 '''Load backend given in the 'backend' option.'''
69 backend = self.config.get('backend', DEFAULT_BACKEND)
70 config = (self._config, backend)
71 self.backend = import_class(backend, 'Backend')(config)
72
73 def _import_frontends(self):
74 '''Load frontends given in the 'frontends' option.'''
75 self.frontends = []
76 frontends = self.config.get('frontends', DEFAULT_FRONTENDS)
77 for frontend in frontends.split(','):
78 frontend = frontend.split(':')
79 if len(frontend) == 1:
80 frontend.append(None)
81 config = (self._config, frontend[0], frontend[1])
82 frontend = import_class(frontend[0], 'Frontend')
83 frontend = frontend(config, self.backend)
84 self.frontends.append(frontend)
85
86 def run(self):
87 '''Create the thread pool and start the main server loop. Wait
88 for the pool to complete, but possibly run forever if the
89 frontends and backend never remove threads.'''
90 thread_pool_size = self.config.getint('thread_pool_size',
91 DEFAULT_THREAD_POOL_SIZE)
92 thread_pool = eventlet.GreenPool(size=int(thread_pool_size))
93 self.backend.run(thread_pool)
94 for frontend in self.frontends:
95 frontend.run(thread_pool)
96 self.log.info(_('Waiting for all threads to exit'))
97 try:
98 thread_pool.waitall()
99 except KeyboardInterrupt:
100 pass
101
102
103class Module(object):
104 '''Common module class for burrow.'''
105
106 def __init__(self, config):
107 self.config = burrowd.config.Config(*config)
108 self.log = get_logger(self.config)
109 self.log.debug(_('Module created'))
110
111
112def get_logger(config):
113 '''Create a logger from the given config.'''
114 log = logging.getLogger(config.section)
115 log_level = config.get('log_level', 'DEBUG')
116 log_level = logging.getLevelName(log_level)
117 if isinstance(log_level, int):
118 log.setLevel(log_level)
119 return log
120
121
122def import_class(module_name, class_name=None):
123 '''Import a class given a full module.class name.'''
124 if class_name is None:
125 module_name, _separator, class_name = module_name.rpartition('.')
126 try:
127 __import__(module_name)
128 return getattr(sys.modules[module_name], class_name)
129 except (ImportError, ValueError, AttributeError), exception:
130 raise ImportError(_('Class %s.%s cannot be found (%s)') %
131 (module_name, class_name, exception))
0132
=== added directory 'burrowd/backend'
=== added file 'burrowd/backend/__init__.py'
--- burrowd/backend/__init__.py 1970-01-01 00:00:00 +0000
+++ burrowd/backend/__init__.py 2011-03-17 23:47:24 +0000
@@ -0,0 +1,94 @@
1# Copyright (C) 2011 OpenStack LLC.
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
15'''Backends for the burrow server.'''
16
17import eventlet
18
19import burrowd
20
21
22class Backend(burrowd.Module):
23 '''Interface that backend implementations must provide.'''
24
25 def __init__(self, config):
26 super(Backend, self).__init__(config)
27 self.queues = {}
28
29 def run(self, thread_pool):
30 thread_pool.spawn_n(self._clean)
31
32 def _clean(self):
33 while True:
34 self.clean()
35 eventlet.sleep(1)
36
37 def delete_accounts(self):
38 pass
39
40 def get_accounts(self):
41 return []
42
43 def delete_account(self, account):
44 pass
45
46 def get_queues(self, account):
47 return []
48
49 def queue_exists(self, account, queue):
50 return False
51
52 def delete_messages(self, account, queue, limit, marker, match_hidden):
53 return []
54
55 def get_messages(self, account, queue, limit, marker, match_hidden):
56 return []
57
58 def update_messages(self, account, queue, limit, marker, match_hidden, ttl,
59 hide):
60 return []
61
62 def delete_message(self, account, queue, message_id):
63 return None
64
65 def get_message(self, account, queue, message_id):
66 return None
67
68 def put_message(self, account, queue, message_id, ttl, hide, body):
69 return True
70
71 def update_message(self, account, queue, message_id, ttl, hide):
72 return None
73
74 def clean(self):
75 '''This method should remove all messages with an expired
76 TTL and make hidden messages that have an expired hide time
77 visible again.'''
78 pass
79
80 def notify(self, account, queue):
81 queue = '%s/%s' % (account, queue)
82 if queue in self.queues:
83 self.queues[queue].put(0)
84
85 def wait(self, account, queue, seconds):
86 queue = '%s/%s' % (account, queue)
87 if queue not in self.queues:
88 self.queues[queue] = eventlet.Queue()
89 try:
90 self.queues[queue].get(timeout=seconds)
91 except Exception:
92 pass
93 if self.queues[queue].getting() == 0:
94 del self.queues[queue]
095
=== added file 'burrowd/backend/memory.py'
--- burrowd/backend/memory.py 1970-01-01 00:00:00 +0000
+++ burrowd/backend/memory.py 2011-03-17 23:47:24 +0000
@@ -0,0 +1,176 @@
1# Copyright (C) 2011 OpenStack LLC.
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
15'''Memory backend for the burrow server.'''
16
17import time
18
19import burrowd.backend
20
21
22class Backend(burrowd.backend.Backend):
23
24 def __init__(self, config):
25 super(Backend, self).__init__(config)
26 self.accounts = {}
27
28 def delete_accounts(self):
29 self.accounts.clear()
30
31 def get_accounts(self):
32 return self.accounts.keys()
33
34 def delete_account(self, account):
35 del self.accounts[account]
36
37 def get_queues(self, account):
38 if account not in self.accounts:
39 return []
40 return self.accounts[account].keys()
41
42 def queue_exists(self, account, queue):
43 return account in self.accounts and queue in self.accounts[account]
44
45 def delete_messages(self, account, queue, limit, marker, match_hidden):
46 messages = self._scan_queue(account, queue, limit, marker,
47 match_hidden, delete=True)
48 if len(self.accounts[account][queue]) == 0:
49 del self.accounts[account][queue]
50 if len(self.accounts[account]) == 0:
51 del self.accounts[account]
52 return messages
53
54 def get_messages(self, account, queue, limit, marker, match_hidden):
55 return self._scan_queue(account, queue, limit, marker, match_hidden)
56
57 def update_messages(self, account, queue, limit, marker, match_hidden, ttl,
58 hide):
59 return self._scan_queue(account, queue, limit, marker, match_hidden,
60 ttl=ttl, hide=hide)
61
62 def delete_message(self, account, queue, message_id):
63 for index in range(0, len(self.accounts[account][queue])):
64 message = self.accounts[account][queue][index]
65 if message['id'] == message_id:
66 del self.accounts[account][queue][index]
67 if len(self.accounts[account][queue]) == 0:
68 del self.accounts[account][queue]
69 if len(self.accounts[account]) == 0:
70 del self.accounts[account]
71 return message
72 return None
73
74 def get_message(self, account, queue, message_id):
75 for index in range(0, len(self.accounts[account][queue])):
76 message = self.accounts[account][queue][index]
77 if message['id'] == message_id:
78 return message
79 return None
80
81 def put_message(self, account, queue, message_id, ttl, hide, body):
82 if account not in self.accounts:
83 self.accounts[account] = {}
84 if queue not in self.accounts[account]:
85 self.accounts[account][queue] = []
86 for index in range(0, len(self.accounts[account][queue])):
87 message = self.accounts[account][queue][index]
88 if message['id'] == message_id:
89 message['ttl'] = ttl
90 message['hide'] = hide
91 message['body'] = body
92 if hide == 0:
93 self.notify(account, queue)
94 return False
95 message = dict(id=message_id, ttl=ttl, hide=hide, body=body)
96 self.accounts[account][queue].append(message)
97 self.notify(account, queue)
98 return True
99
100 def update_message(self, account, queue, message_id, ttl, hide):
101 for index in range(0, len(self.accounts[account][queue])):
102 message = self.accounts[account][queue][index]
103 if message['id'] == message_id:
104 if ttl is not None:
105 message['ttl'] = ttl
106 if hide is not None:
107 message['hide'] = hide
108 if hide == 0:
109 self.notify(account, queue)
110 return message
111 return None
112
113 def clean(self):
114 now = int(time.time())
115 for account in self.accounts.keys():
116 for queue in self.accounts[account].keys():
117 index = 0
118 notify = False
119 total = len(self.accounts[account][queue])
120 while index < total:
121 message = self.accounts[account][queue][index]
122 if 0 < message['ttl'] <= now:
123 del self.accounts[account][queue][index]
124 total -= 1
125 else:
126 if 0 < message['hide'] <= now:
127 message['hide'] = 0
128 notify = True
129 index += 1
130 if notify:
131 self.notify(account, queue)
132 if len(self.accounts[account][queue]) == 0:
133 del self.accounts[account][queue]
134 if len(self.accounts[account]) == 0:
135 del self.accounts[account]
136
137 def _scan_queue(self, account, queue, limit, marker, match_hidden,
138 ttl=None, hide=None, delete=False):
139 index = 0
140 notify = False
141 if marker is not None:
142 found = False
143 for index in range(0, len(self.accounts[account][queue])):
144 message = self.accounts[account][queue][index]
145 if message['id'] == marker:
146 index += 1
147 found = True
148 break
149 if not found:
150 index = 0
151 messages = []
152 total = len(self.accounts[account][queue])
153 while index < total:
154 message = self.accounts[account][queue][index]
155 if not match_hidden and message['hide'] != 0:
156 index += 1
157 continue
158 if ttl is not None:
159 message['ttl'] = ttl
160 if hide is not None:
161 message['hide'] = hide
162 if hide == 0:
163 notify = True
164 if delete:
165 del self.accounts[account][queue][index]
166 total -= 1
167 else:
168 index += 1
169 messages.append(message)
170 if limit:
171 limit -= 1
172 if limit == 0:
173 break
174 if notify:
175 self.notify(account, queue)
176 return messages
0177
=== added file 'burrowd/backend/sqlite.py'
--- burrowd/backend/sqlite.py 1970-01-01 00:00:00 +0000
+++ burrowd/backend/sqlite.py 2011-03-17 23:47:24 +0000
@@ -0,0 +1,250 @@
1# Copyright (C) 2011 OpenStack LLC.
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
15'''Memory backend for the burrow server.'''
16
17import sqlite3
18import time
19
20import burrowd.backend
21
22# Default configuration values for this module.
23DEFAULT_DATABASE = ':memory:'
24
25
26class Backend(burrowd.backend.Backend):
27
28 def __init__(self, config):
29 super(Backend, self).__init__(config)
30 database = self.config.get('database', DEFAULT_DATABASE)
31 self.db = sqlite3.connect(database)
32 queries = [
33 'CREATE TABLE queues ('
34 'account VARCHAR(255) NOT NULL,'
35 'queue VARCHAR(255) NOT NULL,'
36 'PRIMARY KEY (account, queue))',
37 'CREATE TABLE messages ('
38 'queue INT UNSIGNED NOT NULL,'
39 'name VARCHAR(255) NOT NULL,'
40 'ttl INT UNSIGNED NOT NULL,'
41 'hide INT UNSIGNED NOT NULL,'
42 'body BLOB NOT NULL,'
43 'PRIMARY KEY (queue, name))']
44 for query in queries:
45 self.db.execute(query)
46
47 def delete_accounts(self):
48 self.db.execute("DELETE FROM queues")
49 self.db.execute("DELETE FROM messages")
50
51 def get_accounts(self):
52 result = self.db.execute("SELECT account FROM queues").fetchall()
53 return [row[0] for row in result]
54
55 def delete_account(self, account):
56 query = "SELECT rowid FROM queues WHERE account='%s'" % account
57 result = self.db.execute(query).fetchall()
58 if len(result) == 0:
59 return
60 queues = [str(queue[0]) for queue in result]
61 query = "DELETE FROM messages WHERE queue IN (%s)" % (','.join(queues))
62 self.db.execute(query)
63 self.db.execute("DELETE FROM queues WHERE account='%s'" % account)
64
65 def get_queues(self, account):
66 query = "SELECT queue FROM queues WHERE account='%s'" % account
67 result = self.db.execute(query).fetchall()
68 return [row[0] for row in result]
69
70 def queue_exists(self, account, queue):
71 query = "SELECT COUNT(*) FROM queues " \
72 "WHERE account='%s' AND queue='%s'" % \
73 (account, queue)
74 result = self.db.execute(query).fetchall()
75 if len(result) == 0:
76 return False
77 self.rowid = result[0][0]
78 return True
79
80 def delete_messages(self, account, queue, limit, marker, match_hidden):
81 messages = self.get_messages(account, queue, limit, marker,
82 match_hidden)
83 ids = [message['id'] for message in messages]
84 query = "DELETE FROM messages WHERE queue=%d AND name IN (%s)" % \
85 (self.rowid, ','.join(ids))
86 self.db.execute(query)
87 query = "SELECT rowid FROM messages WHERE queue=%d LIMIT 1" % \
88 self.rowid
89 if len(self.db.execute(query).fetchall()) == 0:
90 query = "DELETE FROM queues WHERE rowid=%d" % self.rowid
91 self.db.execute(query)
92 return messages
93
94 def get_messages(self, account, queue, limit, marker, match_hidden):
95 if marker is not None:
96 query = "SELECT rowid FROM messages " \
97 "WHERE queue=%d AND name='%s'" % \
98 (self.rowid, marker)
99 result = self.db.execute(query).fetchall()
100 if len(result) == 0:
101 marker = None
102 else:
103 marker = result[0][0]
104 query = "SELECT name,ttl,hide,body FROM messages WHERE queue=%d" % \
105 self.rowid
106 if match_hidden is False:
107 query += " AND hide == 0"
108 if marker is not None:
109 query += " AND rowid > %d" % marker
110 if limit is not None:
111 query += " LIMIT %d" % limit
112 result = self.db.execute(query).fetchall()
113 messages = []
114 for row in result:
115 messages.append(dict(id=row[0], ttl=row[1], hide=row[2],
116 body=row[3]))
117 return messages
118
119 def update_messages(self, account, queue, limit, marker, match_hidden, ttl,
120 hide):
121 messages = self.get_messages(account, queue, limit, marker,
122 match_hidden)
123 query = "UPDATE messages SET"
124 comma = ''
125 if ttl is not None:
126 query += "%s ttl=%d" % (comma, ttl)
127 comma = ','
128 if hide is not None:
129 query += "%s hide=%d" % (comma, hide)
130 comma = ','
131 if comma == '':
132 return (False, message)
133 ids = []
134 for message in messages:
135 ids.append(message['id'])
136 if ttl is not None:
137 message['ttl'] = ttl
138 if hide is not None:
139 message['hide'] = hide
140 query += " WHERE queue=%d AND name IN (%s)" % \
141 (self.rowid, ','.join(ids))
142 self.db.execute(query)
143 self.notify(account, queue)
144 return messages
145
146 def delete_message(self, account, queue, message_id):
147 message = self.get_message(account, queue, message_id)
148 if message is None:
149 return None
150 query = "DELETE FROM messages WHERE queue=%d AND name='%s'" % \
151 (self.rowid, message_id)
152 self.db.execute(query)
153 query = "SELECT rowid FROM messages WHERE queue=%d LIMIT 1" % \
154 self.rowid
155 if len(self.db.execute(query).fetchall()) == 0:
156 query = "DELETE FROM queues WHERE rowid=%d" % self.rowid
157 self.db.execute(query)
158 return message
159
160 def get_message(self, account, queue, message_id):
161 query = "SELECT name,ttl,hide,body FROM messages " \
162 "WHERE queue=%d AND name='%s'" % (self.rowid, message_id)
163 result = self.db.execute(query).fetchall()
164 if len(result) == 0:
165 return None
166 row = result[0]
167 return dict(id=row[0], ttl=row[1], hide=row[2], body=row[3])
168
169 def put_message(self, account, queue, message_id, ttl, hide, body):
170 query = "SELECT rowid FROM queues " \
171 "WHERE account='%s' AND queue='%s'" % (account, queue)
172 result = self.db.execute(query).fetchall()
173 if len(result) == 0:
174 query = "INSERT INTO queues VALUES ('%s', '%s')" % (account, queue)
175 rowid = self.db.execute(query).lastrowid
176 else:
177 rowid = result[0][0]
178 query = "SELECT rowid FROM messages WHERE queue=%d AND name='%s'" % \
179 (rowid, message_id)
180 result = self.db.execute(query).fetchall()
181 if len(result) == 0:
182 query = "INSERT INTO messages VALUES (%d, '%s', %d, %d, '%s')" % \
183 (rowid, message_id, ttl, hide, body)
184 self.db.execute(query)
185 self.notify(account, queue)
186 return True
187 query = "UPDATE messages SET ttl=%d, hide=%d, body='%s'" \
188 "WHERE rowid=%d" % (ttl, hide, body, result[0][0])
189 self.db.execute(query)
190 if hide == 0:
191 self.notify(account, queue)
192 return False
193
194 def update_message(self, account, queue, message_id, ttl, hide):
195 message = self.get_message(account, queue, message_id)
196 if message is None:
197 return None
198 query = "UPDATE messages SET"
199 comma = ''
200 if ttl is not None:
201 query += "%s ttl=%d" % (comma, ttl)
202 comma = ','
203 if hide is not None:
204 query += "%s hide=%d" % (comma, hide)
205 comma = ','
206 if comma == '':
207 return message
208 query += " WHERE queue=%d AND name='%s'" % (self.rowid, message_id)
209 self.db.execute(query)
210 if hide == 0:
211 self.notify(account, queue)
212 return message
213
214 def clean(self):
215 now = int(time.time())
216 query = "SELECT rowid,queue FROM messages " \
217 "WHERE ttl > 0 AND ttl <= %d" % now
218 result = self.db.execute(query).fetchall()
219 if len(result) > 0:
220 messages = []
221 queues = []
222 for row in result:
223 messages.append(str(row[0]))
224 queues.append(row[1])
225 query = 'DELETE FROM messages WHERE rowid in (%s)' % \
226 ','.join(messages)
227 self.db.execute(query)
228 for queue in queues:
229 query = "SELECT rowid FROM messages WHERE queue=%d LIMIT 1" % \
230 queue
231 if len(self.db.execute(query).fetchall()) == 0:
232 query = "DELETE FROM queues WHERE rowid=%d" % queue
233 self.db.execute(query)
234 query = "SELECT rowid,queue FROM messages WHERE " \
235 "hide > 0 AND hide <= %d" % now
236 result = self.db.execute(query).fetchall()
237 if len(result) > 0:
238 messages = []
239 queues = []
240 for row in result:
241 messages.append(str(row[0]))
242 queues.append(row[1])
243 query = 'UPDATE messages SET hide=0 WHERE rowid in (%s)' % \
244 ','.join(messages)
245 self.db.execute(query)
246 for queue in queues:
247 query = "SELECT account,queue FROM queues WHERE rowid=%d" % \
248 queue
249 result = self.db.execute(query).fetchall()[0]
250 self.notify(result[0], result[1])
0251
=== added file 'burrowd/config.py'
--- burrowd/config.py 1970-01-01 00:00:00 +0000
+++ burrowd/config.py 2011-03-17 23:47:24 +0000
@@ -0,0 +1,55 @@
1# Copyright (C) 2011 OpenStack LLC.
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
15'''Configuration module for the burrow server.'''
16
17import ConfigParser
18
19
20class Config(object):
21 '''Configuration class that wraps the ConfigParser get*
22 methods. These wrappers automatically check for options in
23 a specific instance section first before the regular section
24 (section:instance and then section). They will also return a
25 default value if given instead of throwing an exception.'''
26
27 def __init__(self, config, section, instance=None):
28 self.config = config
29 self.section = section
30 if instance is None:
31 self.instance = None
32 else:
33 self.instance = '%s:%s' % (section, instance)
34
35 def get(self, option, default=None):
36 return self._get(self.config.get, option, default)
37
38 def getboolean(self, option, default=None):
39 return self._get(self.config.getboolean, option, default)
40
41 def getfloat(self, option, default=None):
42 return self._get(self.config.getfloat, option, default)
43
44 def getint(self, option, default=None):
45 return self._get(self.config.getint, option, default)
46
47 def _get(self, method, option, default):
48 if self.instance is not None:
49 if self.config.has_option(self.instance, option):
50 return method(self.instance, option)
51 if self.config.has_option(self.section, option):
52 return method(self.section, option)
53 if self.config.has_option(ConfigParser.DEFAULTSECT, option):
54 return method(ConfigParser.DEFAULTSECT, option)
55 return default
056
=== added directory 'burrowd/frontend'
=== added file 'burrowd/frontend/__init__.py'
--- burrowd/frontend/__init__.py 1970-01-01 00:00:00 +0000
+++ burrowd/frontend/__init__.py 2011-03-17 23:47:24 +0000
@@ -0,0 +1,30 @@
1# Copyright (C) 2011 OpenStack LLC.
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
15'''Frontends for the burrow server.'''
16
17import burrowd
18
19
20class Frontend(burrowd.Module):
21 '''Interface that frontend implementations must provide.'''
22
23 def __init__(self, config, backend):
24 super(Frontend, self).__init__(config)
25 self.backend = backend
26
27 def run(self, thread_pool):
28 '''Run the frontend instance, adding any threads to the
29 thread_pool if needed.'''
30 pass
031
=== added file 'burrowd/frontend/wsgi.py'
--- burrowd/frontend/wsgi.py 1970-01-01 00:00:00 +0000
+++ burrowd/frontend/wsgi.py 2011-03-17 23:47:24 +0000
@@ -0,0 +1,276 @@
1# Copyright (C) 2011 OpenStack LLC.
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
15'''WSGI frontend for the burrow server.'''
16
17import json
18import time
19
20import eventlet
21import eventlet.wsgi
22import routes
23import routes.middleware
24import webob.dec
25import webob.exc
26
27import burrowd.frontend
28
29# Default configuration values for this module.
30DEFAULT_HOST = '0.0.0.0'
31DEFAULT_PORT = 8080
32DEFAULT_BACKLOG = 64
33DEFAULT_SSL = False
34DEFAULT_SSL_CERTFILE = 'example.pem'
35DEFAULT_SSL_KEYFILE = 'example.key'
36DEFAULT_THREAD_POOL_SIZE = 0
37DEFAULT_TTL = 600
38DEFAULT_HIDE = 0
39
40
41def queue_exists(method):
42 '''Decorator to ensure an account and queue exists. If the wait
43 option is given, this will block until a message in the queue is
44 ready or the timeout expires.'''
45 def wrapper(self, req, account, queue, *args, **kwargs):
46 wait = 0
47 if 'wait' in req.params:
48 wait = int(req.params['wait'])
49 if wait > 0:
50 wait += time.time()
51 res = webob.exc.HTTPNotFound()
52 while True:
53 if self.backend.queue_exists(account, queue):
54 res = method(self, req, account, queue, *args, **kwargs)
55 if wait == 0 or res.status_int != 404:
56 break
57 now = time.time()
58 if wait - now > 0:
59 self.backend.wait(account, queue, wait - now)
60 if wait < time.time():
61 break
62 return res
63 return wrapper
64
65
66class Frontend(burrowd.frontend.Frontend):
67
68 def __init__(self, config, backend):
69 super(Frontend, self).__init__(config, backend)
70 self.default_ttl = self.config.get('default_ttl', DEFAULT_TTL)
71 self.default_hide = self.config.get('default_hide', DEFAULT_HIDE)
72 mapper = routes.Mapper()
73 mapper.connect('/', action='root')
74 mapper.connect('/{account}', action='account')
75 mapper.connect('/{account}/{queue}', action='queue')
76 mapper.connect('/{account}/{queue}/{message_id}', action='message')
77 self._routes = routes.middleware.RoutesMiddleware(self._route, mapper)
78
79 def run(self, thread_pool):
80 '''Create the listening socket and start the thread that runs
81 the WSGI server. This extra thread is needed since the WSGI
82 server function blocks.'''
83 host = self.config.get('host', DEFAULT_HOST)
84 port = self.config.getint('port', DEFAULT_PORT)
85 backlog = self.config.getint('backlog', DEFAULT_BACKLOG)
86 socket = eventlet.listen((host, port), backlog=backlog)
87 self.log.info(_('Listening on %s:%d') % (host, port))
88 if self.config.getboolean('ssl', DEFAULT_SSL):
89 certfile = self.config.get('ssl_certfile', DEFAULT_SSL_CERTFILE)
90 keyfile = self.config.get('ssl_keyfile', DEFAULT_SSL_KEYFILE)
91 socket = eventlet.green.ssl.wrap_socket(socket, certfile=certfile,
92 keyfile=keyfile)
93 thread_pool.spawn_n(self._run, socket, thread_pool)
94
95 def _run(self, socket, thread_pool):
96 '''Thread to run the WSGI server.'''
97 thread_pool_size = self.config.getint('thread_pool_size',
98 DEFAULT_THREAD_POOL_SIZE)
99 log_format = '%(client_ip)s "%(request_line)s" %(status_code)s ' \
100 '%(body_length)s %(wall_seconds).6f'
101 if thread_pool_size == 0:
102 eventlet.wsgi.server(socket, self, log=WSGILog(self.log),
103 log_format=log_format, custom_pool=thread_pool)
104 else:
105 eventlet.wsgi.server(socket, self, log=WSGILog(self.log),
106 log_format=log_format, max_size=thread_pool_size)
107
108 def __call__(self, *args, **kwargs):
109 return self._routes(*args, **kwargs)
110
111 @webob.dec.wsgify
112 def _route(self, req):
113 args = req.environ['wsgiorg.routing_args'][1]
114 if not args:
115 return webob.exc.HTTPNotFound()
116 action = args.pop('action')
117 method = getattr(self, '_%s_%s' % (req.method.lower(), action), False)
118 if not method:
119 return webob.exc.HTTPBadRequest()
120 return method(req, **args)
121
122 @webob.dec.wsgify
123 def _delete_root(self, req):
124 self.backend.delete_accounts()
125 return webob.exc.HTTPNoContent()
126
127 @webob.dec.wsgify
128 def _get_root(self, req):
129 accounts = self.backend.get_accounts()
130 if len(accounts) == 0:
131 return webob.exc.HTTPNotFound()
132 return webob.exc.HTTPOk(body=json.dumps(accounts, indent=2))
133
134 @webob.dec.wsgify
135 def _delete_account(self, req, account):
136 self.backend.delete_account(account)
137 return webob.exc.HTTPNoContent()
138
139 @webob.dec.wsgify
140 def _get_account(self, req, account):
141 queues = self.backend.get_queues(account)
142 if len(queues) == 0:
143 return webob.exc.HTTPNotFound()
144 return webob.exc.HTTPOk(body=json.dumps(queues, indent=2))
145
146 @webob.dec.wsgify
147 @queue_exists
148 def _delete_queue(self, req, account, queue):
149 limit, marker, match_hidden = self._parse_filters(req)
150 messages = self.backend.delete_messages(account, queue, limit, marker,
151 match_hidden)
152 return self._return_messages(req, account, queue, messages, 'none')
153
154 @webob.dec.wsgify
155 @queue_exists
156 def _get_queue(self, req, account, queue):
157 limit, marker, match_hidden = self._parse_filters(req)
158 messages = self.backend.get_messages(account, queue, limit, marker,
159 match_hidden)
160 return self._return_messages(req, account, queue, messages, 'all')
161
162 @webob.dec.wsgify
163 @queue_exists
164 def _post_queue(self, req, account, queue):
165 limit, marker, match_hidden = self._parse_filters(req)
166 ttl, hide = self._parse_metadata(req)
167 messages = self.backend.update_messages(account, queue, limit, marker,
168 match_hidden, ttl, hide)
169 return self._return_messages(req, account, queue, messages, 'all')
170
171 @webob.dec.wsgify
172 @queue_exists
173 def _delete_message(self, req, account, queue, message_id):
174 message = self.backend.delete_message(account, queue, message_id)
175 if message is None:
176 return webob.exc.HTTPNotFound()
177 return self._return_message(req, account, queue, message, 'none')
178
179 @webob.dec.wsgify
180 @queue_exists
181 def _get_message(self, req, account, queue, message_id):
182 message = self.backend.get_message(account, queue, message_id)
183 if message is None:
184 return webob.exc.HTTPNotFound()
185 return self._return_message(req, account, queue, message, 'all')
186
187 @webob.dec.wsgify
188 @queue_exists
189 def _post_message(self, req, account, queue, message_id):
190 ttl, hide = self._parse_metadata(req)
191 message = self.backend.update_message(account, queue, message_id, ttl,
192 hide)
193 if message is None:
194 return webob.exc.HTTPNotFound()
195 return self._return_message(req, account, queue, message, 'id')
196
197 @webob.dec.wsgify
198 def _put_message(self, req, account, queue, message_id):
199 (ttl, hide) = self._parse_metadata(req, self.default_ttl,
200 self.default_hide)
201 if self.backend.put_message(account, queue, message_id, ttl, hide, \
202 req.body):
203 return webob.exc.HTTPCreated()
204 return webob.exc.HTTPNoContent()
205
206 def _filter_message(self, detail, message):
207 if detail == 'id':
208 return dict(id=message['id'])
209 elif detail == 'metadata':
210 message = message.copy()
211 del message['body']
212 return message
213 elif detail == 'all':
214 return message
215 return None
216
217 def _return_message(self, req, account, queue, message, detail):
218 if 'detail' in req.params:
219 detail = req.params['detail']
220 message = self._filter_message(detail, message)
221 if message is not None:
222 body = {account: {queue: [message]}}
223 return webob.exc.HTTPOk(body=json.dumps(body, indent=2))
224 return webob.exc.HTTPNoContent()
225
226 def _return_messages(self, req, account, queue, messages, detail):
227 if len(messages) == 0:
228 return webob.exc.HTTPNotFound()
229 if 'detail' in req.params:
230 detail = req.params['detail']
231 filtered_messages = []
232 for message in messages:
233 message = self._filter_message(detail, message)
234 if message is not None:
235 filtered_messages.append(message)
236 if len(filtered_messages) == 0:
237 return webob.exc.HTTPNoContent()
238 body = {account: {queue: filtered_messages}}
239 return webob.exc.HTTPOk(body=json.dumps(body, indent=2))
240
241 def _parse_filters(self, req):
242 limit = None
243 if 'limit' in req.params:
244 limit = int(req.params['limit'])
245 marker = None
246 if 'marker' in req.params:
247 marker = req.params['marker']
248 match_hidden = False
249 if 'hidden' in req.params and req.params['hidden'].lower() == 'true':
250 match_hidden = True
251 return limit, marker, match_hidden
252
253 def _parse_metadata(self, req, default_ttl=None, default_hide=None):
254 if 'ttl' in req.params:
255 ttl = int(req.params['ttl'])
256 else:
257 ttl = default_ttl
258 if ttl is not None and ttl > 0:
259 ttl += int(time.time())
260 if 'hide' in req.params:
261 hide = int(req.params['hide'])
262 else:
263 hide = default_hide
264 if hide is not None and hide > 0:
265 hide += int(time.time())
266 return ttl, hide
267
268
269class WSGILog(object):
270 '''Class for eventlet.wsgi.server to forward logging messages.'''
271
272 def __init__(self, log):
273 self.log = log
274
275 def write(self, message):
276 self.log.debug(message.rstrip())
0277
=== added directory 'etc'
=== added file 'etc/burrowd.conf'
--- etc/burrowd.conf 1970-01-01 00:00:00 +0000
+++ etc/burrowd.conf 2011-03-17 23:47:24 +0000
@@ -0,0 +1,99 @@
1[DEFAULT]
2
3# Log level to use. All sections below prefixed with 'burrowd' can define
4# this to override this default.
5log_level = DEBUG
6
7# Default expiration time in seconds to set for messages.
8default_ttl = 600
9
10# Default hide time in seconds to set for messages.
11default_hide = 0
12
13
14[burrowd]
15
16# Backend to use for storing messages.
17backend = burrowd.backend.sqlite
18
19# Comma separated list of frontends to run.
20# frontends = burrowd.frontend.wsgi,burrowd.frontend.wsgi:ssl
21frontends = burrowd.frontend.wsgi
22
23# Size of the thread pool to use for the server.
24thread_pool_size = 1000
25
26
27[burrowd.backend.sqlite]
28
29# Database file to use, passed to sqlite3.connect.
30database = :memory:
31
32
33[burrowd.frontend.wsgi]
34
35# Host to listen on.
36host = 0.0.0.0
37
38# Port to listen on.
39port = 8080
40
41# Size of backlog for listener socket.
42backlog = 64
43
44# Whether to enable SSL.
45ssl = False
46
47# If SSL is enabled, which certfile to use.
48ssl_certfile = example.pem
49
50# If SSL is enabled, which keyfile to use.
51ssl_keyfile = example.key
52
53# Size of thread pool for the WSGI server. If the size is 0, use the main
54# burrowd thread pool.
55thread_pool_size = 0
56
57# Default expiration time in seconds to set for messages. This overrides
58# the value in the DEFAULT section.
59# default_ttl = 600
60
61# Default hide time in seconds to set for messages. This overrides the
62# value in the DEFAULT section.
63# default_hide = 0
64
65
66[burrowd.frontend.wsgi:ssl]
67
68# Port to listen on.
69port = 8443
70
71# Whether to enable SSL.
72ssl = True
73
74
75# Logging configuration following the logging.config format.
76
77[loggers]
78keys=root
79
80[logger_root]
81qualname=root
82level=WARNING
83handlers=console
84
85[handlers]
86keys=console
87
88[handler_console]
89class=StreamHandler
90level=DEBUG
91formatter=simple
92args=(sys.stdout,)
93
94[formatters]
95keys=simple
96
97[formatter_simple]
98format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
99datefmt=
0100
=== added file 'setup.py'
--- setup.py 1970-01-01 00:00:00 +0000
+++ setup.py 2011-03-17 23:47:24 +0000
@@ -0,0 +1,74 @@
1#!/usr/bin/python
2# Copyright (C) 2011 OpenStack LLC.
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8# http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15
16from setuptools import setup, find_packages
17from setuptools.command.sdist import sdist
18import os
19import subprocess
20try:
21 from babel.messages import frontend
22except ImportError:
23 frontend = None
24
25
26class local_sdist(sdist):
27 """Customized sdist hook - builds the ChangeLog file from VC first"""
28
29 def run(self):
30 if os.path.isdir('.bzr'):
31 # We're in a bzr branch
32
33 log_cmd = subprocess.Popen(["bzr", "log", "--gnu"],
34 stdout=subprocess.PIPE)
35 changelog = log_cmd.communicate()[0]
36 with open("ChangeLog", "w") as changelog_file:
37 changelog_file.write(changelog)
38 sdist.run(self)
39
40
41name = 'burrow'
42
43
44cmdclass = {'sdist': local_sdist}
45
46
47if frontend:
48 cmdclass.update({
49 'compile_catalog': frontend.compile_catalog,
50 'extract_messages': frontend.extract_messages,
51 'init_catalog': frontend.init_catalog,
52 'update_catalog': frontend.update_catalog})
53
54
55setup(
56 name=name,
57 version='0.1',
58 description='Burrow',
59 license='Apache License (2.0)',
60 author='OpenStack, LLC.',
61 author_email='openstack-admins@lists.launchpad.net',
62 url='https://launchpad.net/burrow',
63 packages=find_packages(exclude=['test', 'bin']),
64 test_suite='nose.collector',
65 cmdclass=cmdclass,
66 classifiers=[
67 'Development Status :: 3 - Alpha',
68 'License :: OSI Approved :: Apache Software License',
69 'Operating System :: POSIX :: Linux',
70 'Programming Language :: Python :: 2.6',
71 'Environment :: No Input/Output (Daemon)'],
72 scripts=[
73 'bin/burrow',
74 'bin/burrowd'])
075
=== added directory 'test'
=== added file 'test/__init__.py'
=== added directory 'test/frontend'
=== added file 'test/frontend/__init__.py'
=== added file 'test/frontend/test_wsgi.py'
--- test/frontend/test_wsgi.py 1970-01-01 00:00:00 +0000
+++ test/frontend/test_wsgi.py 2011-03-17 23:47:24 +0000
@@ -0,0 +1,313 @@
1# Copyright (C) 2011 OpenStack LLC.
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
15import ConfigParser
16import json
17import time
18import unittest
19
20import eventlet
21import webob
22
23import burrowd.backend.memory
24import burrowd.backend.sqlite
25import burrowd.frontend.wsgi
26
27
28class TestWSGIMemory(unittest.TestCase):
29 '''Unittests for the WSGI frontend to SQLite backend.'''
30 backend_class = burrowd.backend.memory.Backend
31
32 def setUp(self):
33 config = (ConfigParser.ConfigParser(), 'test')
34 self.backend = self.backend_class(config)
35 self.frontend = burrowd.frontend.wsgi.Frontend(config, self.backend)
36 self.frontend.default_ttl = 0
37 self._get_url('/', status=404)
38 self._get_url('/a', status=404)
39 self._get_url('/a/q', status=404)
40
41 def tearDown(self):
42 self._get_url('/a/q', status=404)
43 self._get_url('/a', status=404)
44 self._get_url('/', status=404)
45
46 def test_account(self):
47 self._put_url('/a/q/1')
48 accounts = self._get_url('/')
49 self.assertEquals(accounts, ['a'])
50 self._delete_url('/a')
51
52 def test_queue(self):
53 self._put_url('/a/q/1')
54 accounts = self._get_url('/a')
55 self.assertEquals(accounts, ['q'])
56 self._delete_url('/a/q')
57
58 def test_message(self):
59 self._put_url('/a/q/1', body='b')
60 accounts = self._get_url('/a/q')
61 self.assertMessages(accounts, 'a', 'q', [self.message('1', body='b')])
62 self._delete_url('/a/q/1')
63
64 def test_message_post(self):
65 self._put_url('/a/q/1', body='b')
66 for x in range(0, 3):
67 accounts = self._post_url('/a/q/1?ttl=%d&hide=%d' % (x, x))
68 self.assertEquals(accounts, {'a': {'q': [{'id': '1'}]}})
69 accounts = self._get_url('/a/q?hidden=true')
70 message = self.message('1', x, x, body='b')
71 self.assertMessages(accounts, 'a', 'q', [message])
72 self._delete_url('/a/q/1')
73
74 def test_message_put(self):
75 for x in range(0, 3):
76 url = '/a/q/1?ttl=%d&hide=%d' % (x, x)
77 status = 201 if x == 0 else 204
78 self._put_url(url, body=str(x), status=status)
79 accounts = self._get_url('/a/q?hidden=true')
80 message = self.message('1', x, x, body=str(x))
81 self.assertMessages(accounts, 'a', 'q', [message])
82 self._delete_url('/a/q/1')
83
84 def test_message_delete_limit(self):
85 [self._put_url('/a/q/%d' % x) for x in range(1, 5)]
86 accounts = self._delete_url('/a/q?limit=3&detail=all', status=200)
87 messages = []
88 messages.append(self.message('1'))
89 messages.append(self.message('2'))
90 messages.append(self.message('3'))
91 self.assertMessages(accounts, 'a', 'q', messages)
92 accounts = self._delete_url('/a/q?limit=3&detail=all', status=200)
93 message = self.message('4')
94 self.assertMessages(accounts, 'a', 'q', [message])
95
96 def test_message_get_limit(self):
97 [self._put_url('/a/q/%d' % x) for x in range(1, 5)]
98 for x in range(0, 4):
99 accounts = self._get_url('/a/q?limit=3')
100 messages = []
101 for y in range(x, 4)[:3]:
102 messages.append(self.message(str(y + 1)))
103 self.assertMessages(accounts, 'a', 'q', messages)
104 self._delete_url('/a/q/%d' % (x + 1))
105
106 def test_message_post_limit(self):
107 [self._put_url('/a/q/%d' % x) for x in range(1, 5)]
108 for x in range(0, 4):
109 accounts = self._post_url('/a/q?limit=3&ttl=%d&detail=all' % x)
110 messages = []
111 for y in range(x, 4)[:3]:
112 messages.append(self.message(str(y + 1), x))
113 self.assertMessages(accounts, 'a', 'q', messages)
114 self._delete_url('/a/q/%d' % (x + 1))
115
116 def test_message_delete_marker(self):
117 [self._put_url('/a/q/%d' % x) for x in range(1, 5)]
118 accounts = self._delete_url('/a/q?marker=2&detail=all', status=200)
119 messages = []
120 messages.append(self.message('3'))
121 messages.append(self.message('4'))
122 self.assertMessages(accounts, 'a', 'q', messages)
123 accounts = self._delete_url('/a/q?marker=5&detail=all', status=200)
124 messages = []
125 messages.append(self.message('1'))
126 messages.append(self.message('2'))
127 self.assertMessages(accounts, 'a', 'q', messages)
128
129 def test_message_get_marker(self):
130 [self._put_url('/a/q/%d' % x) for x in range(1, 5)]
131 for x in range(0, 4):
132 accounts = self._get_url('/a/q?marker=%d' % x)
133 messages = []
134 for y in range(x, 4):
135 messages.append(self.message(str(y + 1)))
136 self.assertMessages(accounts, 'a', 'q', messages)
137 self._delete_url('/a/q/%d' % (x + 1))
138
139 def test_message_post_marker(self):
140 [self._put_url('/a/q/%d' % x) for x in range(1, 5)]
141 for x in range(0, 4):
142 url = '/a/q?marker=%d&ttl=%d&detail=all' % (x, x)
143 accounts = self._post_url(url)
144 messages = []
145 for y in range(x, 4):
146 messages.append(self.message(str(y + 1), x))
147 self.assertMessages(accounts, 'a', 'q', messages)
148 self._delete_url('/a/q/%d' % (x + 1))
149
150 def test_message_delete_limit_marker(self):
151 [self._put_url('/a/q/%d' % x) for x in range(1, 5)]
152 url = '/a/q?limit=2&marker=1&detail=all'
153 accounts = self._delete_url(url, status=200)
154 messages = []
155 messages.append(self.message('2'))
156 messages.append(self.message('3'))
157 self.assertMessages(accounts, 'a', 'q', messages)
158 url = '/a/q?limit=2&marker=5&detail=all'
159 accounts = self._delete_url(url, status=200)
160 messages = []
161 messages.append(self.message('1'))
162 messages.append(self.message('4'))
163 self.assertMessages(accounts, 'a', 'q', messages)
164
165 def test_message_get_limit_marker(self):
166 [self._put_url('/a/q/%d' % x) for x in range(1, 5)]
167 for x in range(0, 4):
168 accounts = self._get_url('/a/q?limit=2&marker=%d' % x)
169 messages = []
170 for y in range(x, 4)[:2]:
171 messages.append(self.message(str(y + 1)))
172 self.assertMessages(accounts, 'a', 'q', messages)
173 self._delete_url('/a/q/%d' % (x + 1))
174
175 def test_message_post_limit_marker(self):
176 [self._put_url('/a/q/%d' % x) for x in range(1, 5)]
177 for x in range(0, 4):
178 url = '/a/q?limit=2&marker=%d&ttl=%d&detail=all' % (x, x)
179 accounts = self._post_url(url)
180 messages = []
181 for y in range(x, 4)[:2]:
182 messages.append(self.message(str(y + 1), x))
183 self.assertMessages(accounts, 'a', 'q', messages)
184 self._delete_url('/a/q/%d' % (x + 1))
185
186 def test_message_ttl(self):
187 self._put_url('/a/q/1?ttl=1')
188 accounts = self._get_url('/a/q/1')
189 message = self.message('1', 1)
190 self.assertMessages(accounts, 'a', 'q', [self.message('1', 1)])
191 time.sleep(1)
192 self.backend.clean()
193 self._get_url('/a/q/1', status=404)
194 self._put_url('/a/q/1')
195 accounts = self._get_url('/a/q/1')
196 self.assertMessages(accounts, 'a', 'q', [self.message('1')])
197 self._post_url('/a/q/1?ttl=1')
198 accounts = self._get_url('/a/q/1')
199 self.assertMessages(accounts, 'a', 'q', [self.message('1', 1)])
200 time.sleep(1)
201 self.backend.clean()
202 self._get_url('/a/q/1', status=404)
203
204 def test_message_hide(self):
205 self._put_url('/a/q/1?hide=1')
206 accounts = self._get_url('/a/q/1')
207 self.assertMessages(accounts, 'a', 'q', [self.message('1', hide=1)])
208 time.sleep(1)
209 self.backend.clean()
210 accounts = self._get_url('/a/q/1')
211 self.assertMessages(accounts, 'a', 'q', [self.message('1')])
212 self._post_url('/a/q/1?hide=1')
213 accounts = self._get_url('/a/q/1')
214 self.assertMessages(accounts, 'a', 'q', [self.message('1', hide=1)])
215 time.sleep(1)
216 self.backend.clean()
217 accounts = self._get_url('/a/q/1')
218 self.assertMessages(accounts, 'a', 'q', [self.message('1')])
219 self._delete_url('/a/q/1')
220
221 def _message_wait(self):
222 accounts = self._get_url('/a/q?wait=2')
223 self.assertMessages(accounts, 'a', 'q', [self.message('1')])
224 self.success = True
225
226 def test_message_put_wait(self):
227 self.success = False
228 thread = eventlet.spawn(self._message_wait)
229 eventlet.spawn_after(0.2, self._put_url, '/a/q/1')
230 thread.wait()
231 self.assertTrue(self.success)
232 self._delete_url('/a/q/1')
233
234 def test_message_put_wait_overwrite(self):
235 self.success = False
236 self._put_url('/a/q/1?hide=10')
237 thread = eventlet.spawn(self._message_wait)
238 eventlet.spawn_after(0.2, self._put_url, '/a/q/1?hide=0', status=204)
239 thread.wait()
240 self.assertTrue(self.success)
241 self._delete_url('/a/q/1')
242
243 def test_message_put_wait_cleanup(self):
244 self.success = False
245 self._put_url('/a/q/1?hide=1')
246 thread = eventlet.spawn(self._message_wait)
247 eventlet.spawn_after(1, self.backend.clean)
248 thread.wait()
249 self.assertTrue(self.success)
250 self._delete_url('/a/q/1')
251
252 def test_message_post_wait(self):
253 self.success = False
254 self._put_url('/a/q/1?hide=10')
255 thread = eventlet.spawn(self._message_wait)
256 eventlet.spawn_after(0.2, self._post_url, '/a/q/1?hide=0')
257 thread.wait()
258 self.assertTrue(self.success)
259 self._delete_url('/a/q/1')
260
261 def test_message_post_wait_queue(self):
262 self.success = False
263 self._put_url('/a/q/1?hide=10')
264 thread = eventlet.spawn(self._message_wait)
265 eventlet.spawn_after(0.2, self._post_url, '/a/q?hide=0&hidden=true')
266 thread.wait()
267 self.assertTrue(self.success)
268 self._delete_url('/a/q/1')
269
270 def message(self, id, ttl=0, hide=0, body=''):
271 return dict(id=id, ttl=ttl, hide=hide, body=body)
272
273 def assertMessages(self, accounts, account, queue, messages):
274 self.assertEquals(len(accounts), 1)
275 self.assertEquals(len(accounts['a']), 1)
276 self.assertEquals(len(accounts['a']['q']), len(messages))
277 for x in range(0, len(messages)):
278 self.assertEquals(accounts['a']['q'][x]['id'], messages[x]['id'])
279 ttl = messages[x]['ttl']
280 if ttl > 0:
281 ttl += int(time.time())
282 self.assertAlmostEquals(accounts['a']['q'][0]['ttl'], ttl)
283 hide = messages[x]['hide']
284 if hide > 0:
285 hide += int(time.time())
286 self.assertAlmostEquals(accounts['a']['q'][0]['hide'], hide)
287 body = messages[x]['body']
288 self.assertEquals(accounts['a']['q'][x]['body'], body)
289
290 def _delete_url(self, url, status=204, **kwargs):
291 return self._url('DELETE', url, status=status, **kwargs)
292
293 def _get_url(self, url, **kwargs):
294 return self._url('GET', url, **kwargs)
295
296 def _post_url(self, url, **kwargs):
297 return self._url('POST', url, **kwargs)
298
299 def _put_url(self, url, status=201, **kwargs):
300 return self._url('PUT', url, status=status, **kwargs)
301
302 def _url(self, method, url, body='', status=200):
303 req = webob.Request.blank(url, method=method, body=body)
304 res = req.get_response(self.frontend)
305 self.assertEquals(res.status_int, status)
306 if status == 200:
307 return json.loads(res.body)
308 return None
309
310
311class TestWSGISQLite(TestWSGIMemory):
312 '''Unittests for the WSGI frontend to SQLite backend.'''
313 backend_class = burrowd.backend.sqlite.Backend

Subscribers

People subscribed via source and target branches