misc:completion: merge zsh completion from Markus Vock.
[be.git] / libbe / command / serve_commands.py
1 # Copyright (C) 2010-2012 Chris Ball <cjb@laptop.org>
2 #                         W. Trevor King <wking@drexel.edu>
3 #
4 # This file is part of Bugs Everywhere.
5 #
6 # Bugs Everywhere is free software: you can redistribute it and/or modify it
7 # under the terms of the GNU General Public License as published by the Free
8 # Software Foundation, either version 2 of the License, or (at your option) any
9 # later version.
10 #
11 # Bugs Everywhere is distributed in the hope that it will be useful, but
12 # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 # FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
14 # more details.
15 #
16 # You should have received a copy of the GNU General Public License along with
17 # Bugs Everywhere.  If not, see <http://www.gnu.org/licenses/>.
18
19 """Define the :class:`ServeCommands` serving BE Commands over HTTP.
20
21 See Also
22 --------
23 :py:meth:`be-libbe.command.base.Command._run_remote` : the associated client
24 """
25
26 import logging
27 import os.path
28 import posixpath
29 import re
30 import urllib
31 import wsgiref.simple_server
32
33 import yaml
34
35 import libbe
36 import libbe.command
37 import libbe.command.base
38 import libbe.util.wsgi
39 import libbe.version
40
41 if libbe.TESTING:
42     import copy
43     import doctest
44     import StringIO
45     import sys
46     import unittest
47     import wsgiref.validate
48     try:
49         import cherrypy.test.webtest
50         cherrypy_test_webtest = True
51     except ImportError:
52         cherrypy_test_webtest = None
53
54     import libbe.bugdir
55     import libbe.command.list
56
57     
58 class ServerApp (libbe.util.wsgi.WSGI_AppObject,
59                  libbe.util.wsgi.WSGI_DataObject):
60     """WSGI server for a BE Command invocation over HTTP.
61
62     RESTful_ WSGI request handler for serving the
63     libbe.command.base.Command._run_remote backend with GET, POST, and
64     HEAD commands.
65
66     This serves all commands from a single, persistant storage
67     instance, usually a VCS-based repository located on the local
68     machine.
69     """
70     server_version = "BE-command-server/" + libbe.version.version()
71
72     def __init__(self, storage=None, notify=False, **kwargs):
73         super(ServerApp, self).__init__(
74             urls=[
75                 (r'^run/?$', self.run),
76                 ],
77             **kwargs)
78         self.storage = storage
79         self.ui = libbe.command.base.UserInterface()
80         self.notify = notify
81         self.http_user_error = 418
82
83     # handlers
84     def run(self, environ, start_response):
85         self.check_login(environ)
86         data = self.post_data(environ)
87         source = 'post'
88         name = data['command']
89         parameters = data['parameters']
90         try:
91             Class = libbe.command.get_command_class(command_name=name)
92         except libbe.command.UnknownCommand, e:
93             raise libbe.util.wsgi.HandlerError(
94                 self.http_user_error, 'UnknownCommand {}'.format(e))
95         command = Class(ui=self.ui)
96         self.ui.setup_command(command)
97         command.status = command._run(**parameters)  # already parsed params
98         assert command.status == 0, command.status
99         stdout = self.ui.io.get_stdout()
100         if self.notify:  # TODO, check what notify does
101             self._notify(environ, 'run', command)
102         return self.ok_response(environ, start_response, stdout)
103
104     # handler utility functions
105     def _parse_post(self, post):
106         return yaml.safe_load(post)
107
108     def check_login(self, environ):
109         user = environ.get('be-auth.user', None)
110         if user is not None:  # we're running under AuthenticationApp
111             if environ['REQUEST_METHOD'] == 'POST':
112                 # TODO: better detection of commands requiring writes
113                 if user == 'guest' or self.storage.is_writeable() == False:
114                     raise _Unauthorized() # only non-guests allowed to write
115             # allow read-only commands for all users
116
117     def _notify(self, environ, command, id, params):
118         message = self._format_notification(environ, command, id, params)
119         self._submit_notification(message)
120
121     def _format_notification(self, environ, command, id, params):
122         key_length = len('command')
123         for key,value in params:
124             if len(key) > key_length and '\n' not in str(value):
125                 key_length = len(key)
126         key_length += 1
127         lines = []
128         multi_line_params = []
129         for key,value in [('address', environ.get('REMOTE_ADDR', '-')),
130                           ('command', command), ('id', id)]+params:
131             v = str(value)
132             if '\n' in v:
133                 multi_line_params.append((key,v))
134                 continue
135             lines.append('%*.*s %s' % (key_length, key_length, key+':', v))
136         lines.append('')
137         for key,value in multi_line_params:
138             lines.extend(['=== START %s ===' % key, v,
139                           '=== STOP %s ===' % key, ''])
140         lines.append('')
141         return '\n'.join(lines)
142
143     def _submit_notification(self, message):
144         libbe.util.subproc.invoke(self.notify, stdin=message, shell=True)
145
146
147 class ServeCommands (libbe.util.wsgi.ServerCommand):
148     """Serve commands over HTTP.
149
150     This allows you to run local `be` commands interfacing with remote
151     data, transmitting command requests over the network.
152
153     :class:`~libbe.command.base.Command` wrapper around
154     :class:`ServerApp`.
155     """
156
157     name = 'serve-commands'
158
159     def _get_app(self, logger, storage, **kwargs):
160         return ServerApp(
161             logger=logger, storage=storage, notify=kwargs.get('notify', False))
162
163     def _long_help(self):
164         return """
165 Example usage::
166
167     $ be serve-commands
168
169 And in another terminal (or after backgrounding the server)::
170
171     $ be --server http://localhost:8000/ list
172
173 If you bind your server to a public interface, take a look at the
174 ``--read-only`` option or the combined ``--ssl --auth FILE``
175 options so other people can't mess with your repository.  If you do use
176 authentication, you'll need to send in your username and password with,
177 for example::
178
179     $ be --repo http://username:password@localhost:8000/ list
180 """
181
182
183 # alias for libbe.command.base.get_command_class()
184 Serve_commands = ServeCommands
185
186
187 if libbe.TESTING:
188     class ServerAppTestCase (libbe.util.wsgi.WSGITestCase):
189         def setUp(self):
190             libbe.util.wsgi.WSGITestCase.setUp(self)
191             self.bd = libbe.bugdir.SimpleBugDir(memory=False)
192             self.app = ServerApp(self.bd.storage, logger=self.logger)
193
194         def tearDown(self):
195             self.bd.cleanup()
196             libbe.util.wsgi.WSGITestCase.tearDown(self)
197
198         def test_run_list(self):
199             list = libbe.command.list.List()
200             params = list._parse_options_args()
201             data = yaml.safe_dump({
202                     'command': 'list',
203                     'parameters': params,
204                     })
205             self.getURL(self.app, '/run', method='POST', data=data)
206             self.failUnless(self.status.startswith('200 '), self.status)
207             self.failUnless(
208                 ('Content-Type', 'application/octet-stream'
209                  ) in self.response_headers,
210                 self.response_headers)
211             self.failUnless(self.exc_info == None, self.exc_info)
212         # TODO: integration tests on ServeCommands?
213
214     unitsuite =unittest.TestLoader().loadTestsFromModule(sys.modules[__name__])
215     suite = unittest.TestSuite([unitsuite, doctest.DocTestSuite()])