ia64/xen-unstable

view tools/python/xen/util/xmlrpclib2.py @ 10720:8922c1fbe684

[XM][ACM] Add xm subcommands to work with security resource labels.

This patch adds new xm subcommands to support working with resource
labels. The new subcommands are 'xm resources', 'xm rmlabel', 'xm
getlabel' and 'xm dry-run'. In addition, the 'xm addlabel' subcommand
now uses an updated syntax to support labeling both domains and
resources. See the xm man page for details on each subcommand.

Beyond the new subcommands, this patch allows users to immediately see
when security checks will fail by pushing some basic security checking
into the beginning of 'xm create' and 'xm block-attach'. ACM security
attributes for block devices are added to XenStore in order to support
the final security enforcement, which will be performed in the kernel
and included in a separate patch.

Signed-off-by: Bryan D. Payne <bdpayne@us.ibm.com>
Signed-off-by: Reiner Sailer <sailer@us.ibm.com>
author kfraser@localhost.localdomain
date Mon Jul 10 17:18:07 2006 +0100 (2006-07-10)
parents dab24595e529
children 58a04bfedf6b
line source
1 #============================================================================
2 # This library is free software; you can redistribute it and/or
3 # modify it under the terms of version 2.1 of the GNU Lesser General Public
4 # License as published by the Free Software Foundation.
5 #
6 # This library is distributed in the hope that it will be useful,
7 # but WITHOUT ANY WARRANTY; without even the implied warranty of
8 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
9 # Lesser General Public License for more details.
10 #
11 # You should have received a copy of the GNU Lesser General Public
12 # License along with this library; if not, write to the Free Software
13 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
14 #============================================================================
15 # Copyright (C) 2006 Anthony Liguori <aliguori@us.ibm.com>
16 # Copyright (C) 2006 XenSource Inc.
17 #============================================================================
19 """
20 An enhanced XML-RPC client/server interface for Python.
21 """
23 import string
24 import types
26 from httplib import HTTPConnection, HTTP
27 from xmlrpclib import Transport
28 from SimpleXMLRPCServer import SimpleXMLRPCServer, SimpleXMLRPCRequestHandler
29 import SocketServer
30 import xmlrpclib, socket, os, stat
32 from xen.xend.XendLogging import log
34 try:
35 import SSHTransport
36 ssh_enabled = True
37 except ImportError:
38 # SSHTransport is disabled on Python <2.4, because it uses the subprocess
39 # package.
40 ssh_enabled = False
43 # A new ServerProxy that also supports httpu urls. An http URL comes in the
44 # form:
45 #
46 # httpu:///absolute/path/to/socket.sock
47 #
48 # It assumes that the RPC handler is /RPC2. This probably needs to be improved
50 # We're forced to subclass the RequestHandler class so that we can work around
51 # some bugs in Keep-Alive handling and also enabled it by default
52 class XMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
53 protocol_version = "HTTP/1.1"
55 # this is inspired by SimpleXMLRPCRequestHandler's do_POST but differs
56 # in a few non-trivial ways
57 # 1) we never generate internal server errors. We let the exception
58 # propagate so that it shows up in the Xend debug logs
59 # 2) we don't bother checking for a _dispatch function since we don't
60 # use one
61 def do_POST(self):
62 data = self.rfile.read(int(self.headers["content-length"]))
63 rsp = self.server._marshaled_dispatch(data)
65 self.send_response(200)
66 self.send_header("Content-Type", "text/xml")
67 self.send_header("Content-Length", str(len(rsp)))
68 self.end_headers()
70 self.wfile.write(rsp)
71 self.wfile.flush()
72 if self.close_connection == 1:
73 self.connection.shutdown(1)
75 class HTTPUnixConnection(HTTPConnection):
76 def connect(self):
77 self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
78 self.sock.connect(self.host)
80 class HTTPUnix(HTTP):
81 _connection_class = HTTPUnixConnection
83 class UnixTransport(Transport):
84 def request(self, host, handler, request_body, verbose=0):
85 self.__handler = handler
86 return Transport.request(self, host, '/RPC2', request_body, verbose)
87 def make_connection(self, host):
88 return HTTPUnix(self.__handler)
91 # See _marshalled_dispatch below.
92 def conv_string(x):
93 if (isinstance(x, types.StringType) or
94 isinstance(x, unicode)):
95 s = string.replace(x, "'", r"\047")
96 exec "s = '" + s + "'"
97 return s
98 else:
99 return x
102 class ServerProxy(xmlrpclib.ServerProxy):
103 def __init__(self, uri, transport=None, encoding=None, verbose=0,
104 allow_none=1):
105 if transport == None:
106 (protocol, rest) = uri.split(':', 1)
107 if protocol == 'httpu':
108 uri = 'http:' + rest
109 transport = UnixTransport()
110 elif protocol == 'ssh':
111 global ssh_enabled
112 if ssh_enabled:
113 (transport, uri) = SSHTransport.getHTTPURI(uri)
114 else:
115 raise ValueError(
116 "SSH transport not supported on Python <2.4.")
117 xmlrpclib.ServerProxy.__init__(self, uri, transport, encoding,
118 verbose, allow_none)
120 def __request(self, methodname, params):
121 response = xmlrpclib.ServerProxy.__request(self, methodname, params)
123 if isinstance(response, tuple):
124 return tuple([conv_string(x) for x in response])
125 else:
126 return conv_string(response)
129 # This is a base XML-RPC server for TCP. It sets allow_reuse_address to
130 # true, and has an improved marshaller that logs and serializes exceptions.
132 class TCPXMLRPCServer(SocketServer.ThreadingMixIn, SimpleXMLRPCServer):
133 allow_reuse_address = True
135 def __init__(self, addr, requestHandler=XMLRPCRequestHandler,
136 logRequests=1):
137 SimpleXMLRPCServer.__init__(self, addr, requestHandler, logRequests)
139 def _marshaled_dispatch(self, data, dispatch_method = None):
140 params, method = xmlrpclib.loads(data)
141 try:
142 if dispatch_method is not None:
143 response = dispatch_method(method, params)
144 else:
145 response = self._dispatch(method, params)
147 # With either Unicode or normal strings, we can only transmit
148 # \t, \n, \r, \u0020-\ud7ff, \ue000-\ufffd, and \u10000-\u10ffff
149 # in an XML document. xmlrpclib does not escape these values
150 # properly, and then breaks when it comes to parse the document.
151 # To hack around this problem, we use repr here and exec above
152 # to transmit the string using Python encoding.
153 # Thanks to David Mertz <mertz@gnosis.cx> for the trick (buried
154 # in xml_pickle.py).
155 if (isinstance(response, types.StringType) or
156 isinstance(response, unicode)):
157 response = repr(response)[1:-1]
159 response = (response,)
160 response = xmlrpclib.dumps(response,
161 methodresponse=1,
162 allow_none=1)
163 except xmlrpclib.Fault, fault:
164 response = xmlrpclib.dumps(fault)
165 except Exception, exn:
166 import xen.xend.XendClient
167 log.exception(exn)
168 response = xmlrpclib.dumps(
169 xmlrpclib.Fault(xen.xend.XendClient.ERROR_INTERNAL, str(exn)))
171 return response
173 # This is a XML-RPC server that sits on a Unix domain socket.
174 # It implements proper support for allow_reuse_address by
175 # unlink()'ing an existing socket.
177 class UnixXMLRPCRequestHandler(XMLRPCRequestHandler):
178 def address_string(self):
179 try:
180 return XMLRPCRequestHandler.address_string(self)
181 except ValueError, e:
182 return self.client_address[:2]
184 class UnixXMLRPCServer(TCPXMLRPCServer):
185 address_family = socket.AF_UNIX
187 def __init__(self, addr, logRequests):
188 parent = os.path.dirname(addr)
189 if os.path.exists(parent):
190 os.chown(parent, os.geteuid(), os.getegid())
191 os.chmod(parent, stat.S_IRWXU)
192 if self.allow_reuse_address and os.path.exists(addr):
193 os.unlink(addr)
194 else:
195 os.makedirs(parent, stat.S_IRWXU)
196 TCPXMLRPCServer.__init__(self, addr, UnixXMLRPCRequestHandler,
197 logRequests)