~ubuntu-branches/ubuntu/precise/keystone/precise-security

« back to all changes in this revision

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

  • Committer: Bazaar Package Importer
  • Author(s): Chuck Short
  • Date: 2011-08-23 10:18:22 UTC
  • Revision ID: james.westby@ubuntu.com-20110823101822-enve6zceb3lqhuvj
Tags: upstream-1.0~d4~20110823.1078
ImportĀ upstreamĀ versionĀ 1.0~d4~20110823.1078

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