sslxmlrpc_client.py.in 8.69 KB
Newer Older
1 2
#! /usr/bin/env python
#
3
# Copyright (c) 2004-2013 University of Utah and the Flux Group.
4
# 
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
# {{{EMULAB-LICENSE
# 
# This file is part of the Emulab network testbed software.
# 
# This file is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or (at
# your option) any later version.
# 
# This file is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public
# License for more details.
# 
# You should have received a copy of the GNU Affero General Public License
# along with this file.  If not, see <http://www.gnu.org/licenses/>.
# 
# }}}
# 
24 25 26

import sys
import getopt
27 28 29 30 31 32 33 34 35 36
import os, os.path
import xmlrpclib

TBROOT = "@prefix@"
TBPATH = os.path.join(TBROOT, "lib")

if TBPATH not in sys.path:
    sys.path.append(TBPATH)
    pass

37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
from emulabclient import *

from M2Crypto.m2xmlrpclib import SSL_Transport
from M2Crypto import SSL

##
# The package version number
#
PACKAGE_VERSION = 0.1

# Default server and port
XMLRPC_SERVER   = "@BOSSNODE@"
XMLRPC_PORT     = 3069

# User supplied server name.
xmlrpc_server   = XMLRPC_SERVER
xmlrpc_port     = XMLRPC_PORT

# The default RPC module to invoke.
module          = "experiment"

58 59 60
# The default path
path            = TBROOT

61 62 63
# Where to find the default certificate in the users home dir.
default_cert    = "/.ssl/emulab.pem"
certificate     = None;
64 65 66 67

# Debugging output.
debug           = 0

68 69 70
# Raw XML mode
rawmode         = 0

71 72 73 74 75 76
##
# Print the usage statement to stdout.
#
def usage():
    print "Make a request to the Emulab XML-RPC (SSL-based) server."
    print ("Usage: " + sys.argv[0] 
77
                     + " [-hV] [-s server] [-m module] "
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
                     + "<method> [param=value ...]")
    print
    print "Options:"
    print "  -h, --help\t\t  Display this help message"
    print "  -V, --version\t\t  Show the version number"
    print "  -s, --server\t\t  Set the server hostname"
    print "  -p, --port\t\t  Set the server port"
    print "  -c, --cert\t\t  Set the certificate to use"
    print "  -m, --module\t\t  Set the RPC module (defaults to experiment)"
    print
    print "Required arguments:"
    print "  method\t\t  The method to execute on the server"
    print "  params\t\t\t  The method arguments in param=value format"
    print
    print "Example:"
    print ("  "
           + sys.argv[0]
95
           + " -s boss.emulab.net echo str=\"Hello World!\"")
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
    return

#
# Process a single command line
#
def do_method(server, method_and_args):
    # Get a pointer to the function we want to invoke.
    methodname = method_and_args[0]
    if methodname.count(".") == 0:
        methodname = module + "." + methodname
        pass
    
    meth = getattr(server, methodname)

    # Pop off the method, and then convert the rest of the arguments.
    # Be sure to add the version.
    method_and_args.pop(0)

    #
    # Convert all params (name=value) into a Dictionary. 
    # 
    params = {}
    for param in method_and_args:
        plist = string.split(param, "=", 1)
        if len(plist) != 2:
            print ("error: Parameter, '"
                   + param
                   + "', is not of the form: param=value!")
            return -1
        value = plist[1]

        #
        # If the first character of the argument looks like a dictionary,
        # try to evaluate it.
        #
131 132 133
        if value.startswith("{"):
            value = eval(value);
            pass
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
    
        params[plist[0]] = value
        pass
    meth_args = [ PACKAGE_VERSION, params ]

    #
    # Make the call. 
    #
    try:
        response = apply(meth, meth_args)
        pass
    except xmlrpclib.Fault, e:
        print e.faultString
        return -1

    #
    # Parse the Response, which is a Dictionary. See EmulabResponse in the
    # emulabclient.py module. The XML standard converts classes to a plain
    # Dictionary, hence the code below. 
    # 
    if len(response["output"]):
        print response["output"]
        pass

    rval = response["code"]

    #
    # If the code indicates failure, look for a "value". Use that as the
    # return value instead of the code. 
    # 
    if rval != RESPONSE_SUCCESS:
        if response["value"]:
            rval = response["value"]
            pass
        pass

    if debug and response["value"]:
        print str(response["value"])
        pass
        
    return rval

#
# Process program arguments.
# 
try:
    # Parse the options,
    opts, req_args =  getopt.getopt(sys.argv[1:],
182
                      "dhVc:s:m:p:r",
183
                      [ "help", "version", "rawmode", "server=", "module=",
184
                        "cert=", "port=", "path="])
185 186 187 188 189 190 191 192 193 194 195 196
    # ... act on them appropriately, and
    for opt, val in opts:
        if opt in ("-h", "--help"):
            usage()
            sys.exit()
            pass
        elif opt in ("-V", "--version"):
            print PACKAGE_VERSION
            sys.exit()
            pass
        elif opt in ("-s", "--server"):
	    xmlrpc_server = val
197 198 199 200 201 202
            #
            # Allow port spec here too.
            #
            if val.find(":") > 0:
                xmlrpc_server,xmlrpc_port = string.split(val, ":", 1)
                pass
203 204 205 206 207 208 209 210 211 212 213 214 215
            pass
        elif opt in ("-p", "--port"):
	    xmlrpc_port = val
            pass
        elif opt in ("-c", "--cert"):
	    certificate = val
            pass
        elif opt in ("-m", "--module"):
	    module = val
            pass
        elif opt in ("-d", "--debug"):
	    debug = 1
            pass
216 217 218
        elif opt in ("--path",):
	    path = val
            pass
219 220 221
        elif opt in ("-r", "--rawmode"):
	    rawmode = 1
            pass
222 223 224 225 226 227 228 229
        pass
    pass
except getopt.error, e:
    print e.args[0]
    usage()
    sys.exit(2)
    pass

230
class MySSL_Transport(SSL_Transport):
231 232 233 234
    def parse_response(self, file):
        # compatibility interface
        return self._parse_response(file, None)

235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271
    def _parse_response(self, file, sock):
        stuff = ""
        
        while 1:
            if sock:
                response = sock.recv(1024)
            else:
                response = file.read(1024)
            if not response:
                break
            stuff += response
        return stuff
        pass
    pass

class MyServerProxy(xmlrpclib.ServerProxy):
    def raw_request(self, xmlgoo):

        #
        # I could probably play tricks with the getattr method, but
        # not sure what those tricks would be! If I try to access the
        # members by name, the getattr definition in the ServerProxy class
        # tries to turn that into a method lookup at the other end. 
        #
        transport = self.__dict__["_ServerProxy__transport"]
        host      = self.__dict__["_ServerProxy__host"]
        handler   = self.__dict__["_ServerProxy__handler"]
        
        response = transport.request(host, handler, xmlgoo)

        if len(response) == 1:
            response = response[0]

        return response

    pass

272 273 274
#
# Vanilla SSL CTX initialization.
#
275 276 277
if certificate == None:
    certificate = os.environ["HOME"] + default_cert
    pass
278 279 280 281 282 283 284 285 286 287 288
if not os.access(certificate, os.R_OK):
    print "Certificate cannot be accessed: " + certificate
    sys.exit(-1);
    pass
    
ctx = SSL.Context('sslv23')
ctx.load_cert(certificate, certificate)
ctx.set_verify(SSL.verify_none, 16)
ctx.set_allow_unknown_ca(0)

# This is parsed by the Proxy object.
289
URI = "https://" + xmlrpc_server + ":" + str(xmlrpc_port) + path
290
if debug:
291
    print >>sys.stderr, URI
292
    pass
293

294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315
if rawmode:
    # Get a handle on the server,
    server = MyServerProxy(URI, MySSL_Transport(ctx));

    stuff = ""
    while (True):
        foo = sys.stdin.read(1024 * 16)
        if foo == "":
            break
        stuff += foo
        pass

    #
    # Make the call. 
    #
    try:
        response = server.raw_request(stuff)
        pass
    except xmlrpclib.Fault, e:
        print e.faultString
        sys.exit(-1);
        pass
316

317 318 319 320 321
    print str(response);
    sys.exit(0);
elif len(req_args):
    # Get a handle on the server,
    server = xmlrpclib.ServerProxy(URI, SSL_Transport(ctx));
322 323 324
    # Method and args are on the command line.
    sys.exit(do_method(server, req_args))
else:
325 326
    # Get a handle on the server,
    server = xmlrpclib.ServerProxy(URI, SSL_Transport(ctx));
327 328 329 330 331 332 333 334 335 336 337 338 339 340 341
    # Prompt the user for input.
    try:
        while True:
            line = raw_input("$ ")
            tokens = line.split(" ")
            if len(tokens) >= 1 and len(tokens[0]) > 0:
                print str(do_method(server, tokens))
                pass
            pass
        pass
    except EOFError:
        pass
    print
    pass