~ziad-sawalha/keystone/trunk

« back to all changes in this revision

Viewing changes to examples/echo/echo/server.py

  • Committer: Ziad Sawalha
  • Date: 2011-05-26 01:24:05 UTC
  • mfrom: (87.5.8)
  • Revision ID: git-v1:b0d12a558f590a501a42afd1283148961563920e
Merge pull request 53

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# vim: tabstop=4 shiftwidth=4 softtabstop=4
 
2
# Copyright (c) 2010-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
 
13
# implied.
 
14
# See the License for the specific language governing permissions and
 
15
# limitations under the License.
 
16
 
 
17
import eventlet
 
18
from eventlet import wsgi
 
19
from lxml import etree
 
20
import os
 
21
from paste.deploy import loadapp
 
22
import sys
 
23
from webob.exc import HTTPUnauthorized
 
24
 
 
25
 
 
26
# If ../echo/__init__.py exists, add ../ to Python search path, so that
 
27
# it will override what happens to be installed in /usr/(local/)lib/python...
 
28
POSSIBLE_TOPDIR = os.path.normpath(os.path.join(os.path.abspath(sys.argv[0]),
 
29
                                   os.pardir,
 
30
                                   os.pardir))
 
31
if os.path.exists(os.path.join(POSSIBLE_TOPDIR, 'echo', '__init__.py')):
 
32
    # also use the local keystone
 
33
    KEYSTONE_TOPDIR = os.path.normpath(os.path.join(POSSIBLE_TOPDIR,
 
34
                                                    os.pardir))
 
35
    if os.path.exists(os.path.join(KEYSTONE_TOPDIR,
 
36
                                   'keystone',
 
37
                                   '__init__.py')):
 
38
        sys.path.insert(0, KEYSTONE_TOPDIR)
 
39
    sys.path.insert(0, POSSIBLE_TOPDIR)
 
40
 
 
41
 
 
42
"""
 
43
Echo: a dummy service for OpenStack auth testing. It returns request info.
 
44
"""
 
45
 
 
46
 
 
47
class EchoApp(object):
 
48
    def __init__(self, environ, start_response):
 
49
        self.envr = environ
 
50
        self.start = start_response
 
51
        self.dom = self.toDOM(environ)
 
52
        echo_xsl = os.path.join(os.path.abspath(\
 
53
            os.path.dirname(__file__)), "xsl/echo.xsl")
 
54
        self.transform = etree.XSLT(etree.parse(echo_xsl))
 
55
 
 
56
    def __iter__(self):
 
57
        # We expect an X_AUTHORIZATION header to be passed in
 
58
        # We assume the request is coming from a trusted source. Middleware
 
59
        # is used to perform that validation.
 
60
        if 'HTTP_X_AUTHORIZATION' not in self.envr:
 
61
            self.start('401 Unauthorized', [('Content-Type',
 
62
                                             'application/json')])
 
63
            return iter(["401 Unauthorized"])
 
64
 
 
65
        if 'HTTP_X_IDENTITY_STATUS' not in self.envr:
 
66
            identity_status = "Unknown"
 
67
        else:
 
68
            identity_status = self.envr["HTTP_X_IDENTITY_STATUS"]
 
69
 
 
70
        print '  Received:'
 
71
        print '  Auth Status:', identity_status
 
72
        if 'HTTP_X_AUTHORIZATION' in self.envr:
 
73
            print '  Identity   :', self.envr['HTTP_X_AUTHORIZATION']
 
74
        if 'HTTP_X_TENANT' in self.envr:
 
75
            print '  Tenant     :', self.envr['HTTP_X_TENANT']
 
76
        if 'HTTP_X_GROUP' in self.envr:
 
77
            print '  Group      :', self.envr['HTTP_X_GROUP']
 
78
 
 
79
        accept = self.envr.get("HTTP_ACCEPT", "application/json")
 
80
        if accept == "application/xml":
 
81
            return self.toXML()
 
82
        else:
 
83
            return self.toJSON()
 
84
 
 
85
    def toJSON(self):
 
86
        self.start('200 OK', [('Content-Type', 'application/json')])
 
87
        yield str(self.transform(self.dom))
 
88
 
 
89
    def toXML(self):
 
90
        self.start('200 OK', [('Content-Type', 'application/xml')])
 
91
        yield etree.tostring(self.dom)
 
92
 
 
93
    def toDOM(self, environ):
 
94
        echo = etree.Element("{http://docs.openstack.org/echo/api/v1.0}echo",
 
95
                             method=environ["REQUEST_METHOD"],
 
96
                             pathInfo=environ["PATH_INFO"],
 
97
                             queryString=environ.get('QUERY_STRING', ""))
 
98
        content = etree.Element(
 
99
            "{http://docs.openstack.org/echo/api/v1.0}content")
 
100
        content.set("type", environ["CONTENT_TYPE"])
 
101
        content.text = ""
 
102
        inReq = environ["wsgi.input"]
 
103
        for line in inReq:
 
104
            content.text = content.text + line
 
105
        echo.append(content)
 
106
        return echo
 
107
 
 
108
 
 
109
def app_factory(global_conf, **local_conf):
 
110
    return EchoApp
 
111
 
 
112
if __name__ == "__main__":
 
113
    def usage():
 
114
        print "Runs Echo, the canonical OpenStack service, " \
 
115
                "with auth middleware"
 
116
        print "Options:"
 
117
        print "-h, --help  : show this usage information"
 
118
        print "-b, --basic : run with basic auth (uses echo_basic.ini)"
 
119
        print "-r, --remote: run with remote auth on port 8100" \
 
120
                "(uses echo_remote.ini)"
 
121
        print "-i, --ini filename: run with specified ini file"
 
122
        print "-p, --port: specifies port to listen on (default is 8090)"
 
123
        print "by default will run with local, token auth (uses echo.ini)"
 
124
 
 
125
    import getopt
 
126
    try:
 
127
        opts, args = getopt.getopt(sys.argv[1:],
 
128
                                   "hbrp:i:",
 
129
                                   ["help", "basic", "remote", "port", "ini"])
 
130
    except getopt.GetoptError:
 
131
        usage()
 
132
        sys.exit()
 
133
 
 
134
    port = 0
 
135
    ini = "echo.ini"
 
136
    auth_name = "local Token Auth"
 
137
 
 
138
    for opt, arg in opts:
 
139
        if opt in ["-h", "--help"]:
 
140
            usage()
 
141
            sys.exit()
 
142
        elif opt in ["-p", "--port"]:
 
143
            port = int(arg)
 
144
        elif opt in ["-i", "--ini"]:
 
145
            auth_name = "with custom ini: %s" % arg
 
146
            ini = arg
 
147
        elif opt in ["-b", "--basic"]:
 
148
            auth_name = "Basic Auth"
 
149
            ini = "echo_basic.ini"
 
150
        elif opt in ["-r", "--remote"]:
 
151
            auth_name = "remote Token Auth"
 
152
            ini = "echo_remote.ini"
 
153
            if not port:
 
154
                port = 8100
 
155
 
 
156
    if not port:
 
157
        port = 8090
 
158
    print "Running with", auth_name
 
159
    app = loadapp("config:" + \
 
160
        os.path.join(os.path.abspath(os.path.dirname(__file__)),
 
161
        ini), global_conf={"log_name": "echo.log"})
 
162
    listener = eventlet.listen(('', port))
 
163
    pool = eventlet.GreenPool(1000)
 
164
    wsgi.server(listener, app, custom_pool=pool)