def set_server_port(self,port): """validate the port passed to the constructor; must be an int between 1 and 65534 """ if port >= 1 and port <= 65535: cpem.log_event('debug',"setting self.server_port=%s" % (port)) self.server_port = port else: cpem.log_event('error','port out of range') raise TypeError,'port out of range'
def refresh_plugins(CPEM_Server, path='%s/plugins/' % (os.getcwd()), pluginName=''): """refresh_plugins() handles re-loading plugins, on-demand, either reloading all plugins or reloading only specified plugins """ #TODO (CJS: 2011/10/16) - need to be able to selectively re-initialize an individual plugin. cpem.log_event('info', 'refresh plugins called') init_plugins(CPEM_Server, path) cpem.log_event('info', 'plugins now refreshed')
def init_plugins(CPEM_Server, path='%s%splugins%s' % (os.getcwd(), os.sep, os.sep)): """init_plugins( CPEMSERVER, PATH ) handles initializing plugins; i.e. finding them in the plugins directory, and registering them with our RPC server. """ sys.path.append(path) for loader, packageName, ispkg in pkgutil.iter_modules([path]): try: f, filename, description = imp.find_module(packageName) #print 'D: f="%s", filename="%s" and description="%s"' % ( f, filename, description ) try: loaded = imp.load_module(packageName, f, filename, description) try: for f in get_functions(loaded): if f.__name__ is 'init': # this is the initialization routine for the plugin, execute it cpem.log_event('info', 'hit init in %s' % (packageName)) #TODO: CJS 2011/03/29 - just execute the init function immediately. pass elif f.__name__ is 'schedule': # this is the special routine for the plugin to register scheduled events. cpem.log_event( 'info', 'hit scheduler in %s' % (packageName)) pass else: funcName = '%s_%s' % (packageName, f.__name__) CPEM_Server.register_function(f, funcName) except Exception, e: cpem.log_event('error', 'a plugin caused us to fail.') raise except Exception, e: cpem.log_event( 'error', 'found the module at %s, but could not import it. (%s)' % (filename, e[0])) raise except Exception, e: cpem.log_event( 'error', 'failed to load the "%s" plugin (%s%s), skipping it! (Python says, "%s")' % (packageName, path, packageName, e[0])) raise
def __init__(self,server_address,HandlerClass,certFile='certs/cert.pem',keyFile='certs/key.pem',logRequests=False): """Secure XML-RPC server. It it very similar to SimpleXMLRPCServer but it uses HTTPS for transporting XML data. """ cpem.log_event('debug',"starting SecureXMLRPCServer") self.logRequests = logRequests #turn off the BaseHTTPServer logging... because we dun need it. SimpleXMLRPCServer.SimpleXMLRPCDispatcher.__init__(self,True,None) ThreadedBaseServer(self,SocketServer.BaseServer.__init__(self,server_address,HandlerClass)) ctx = SSL.Context(SSL.SSLv23_METHOD) ctx.use_privatekey_file (keyFile) ctx.use_certificate_file(certFile) self.socket = SSL.Connection(ctx,socket.socket(self.address_family,self.socket_type)) self.server_bind() self.server_activate() cpem.log_event('debug','server setup complete') def shutdown_request(self,request): request.shutdown()
def signal_handle_sigterm(): #TODO: safely close out our database connections cpem.log_event('debug', "PeerDisk daemon caught sigterm or sigint") sys.exit(1)
def load_plugin(server, plugin): """load_plugin() registers the functions of a plugin with the XMLRPC server. """ sys.path.append(path) for loader, packageName, ispkg in pkgutil.iter_modules([path]): pkgutil.it try: f, filename, description = imp.find_module(packageName) #print 'D: f="%s", filename="%s" and description="%s"' % ( f, filename, description ) try: loaded = imp.load_module(packageName, f, filename, description) try: for f in get_functions(loaded): if f.__name__ is 'init': ''' typically, we want to execute the init function immediately. ''' cpem.log_event( 'info', 'hit plugin init in %s' % (packageName)) #TODO: CJS 2011/03/29 - implement this so it executes the init routine immediately. pass elif f.__name__ is 'schedule': ''' schedule routines in the plugins allow us to register a scheduled event so that we can execute events regularly or periodically ''' cpem.log_event( 'info', 'hit scheduler in %s' % (packageName)) #TODO: CJS 2011/04/09 - implement this pass else: ''' found a normal function, we'll just register this for use ''' funcName = '%s_%s' % (packageName, f.__name__) try: CPEM_Server.register_function(f, funcName) cpem.log_event( 'info', 'registered plugin function %s' % (funcName)) except: cpem.log_event( 'warn', 'failed to register function %s' % (funcName)) raise except Exception, e: cpem.log_event( 'error', 'there was a problem loading the %s plugin: %s' % (packageName, e[0])) raise except Exception, e: cpem.log_event( 'error', 'could not import %s plugin: %s' % (filename, e[0])) raise except Exception, e: cpem.log_event( 'error', 'could not load the %s plugin (%s%s), skipping it. Python say: %s' % (packageName, path, packageName, e[0])) raise
def do_POST(self): """do_POST() #TODO: document this. """ client_ip,client_port = self.client_address cpem.log_event('info','client connection from %s:%d' % (client_ip,client_port)) try: data = self.rfile.read(int(self.headers["content-length"])) cpem.log_event('debug','client request: %s' % data) response = self.server._marshaled_dispatch(data,getattr(self,'_dispatch',None)) cpem.log_event('debug','response to client: %s' % response) except: # something goed boom cpem.log_event('error','oops! something went wrong ') self.send_response(500) self.end_headers() else: # we received a valid XML response cpem.log_event('debug',"valid XML response received.") try: self.send_response(200) self.send_header("Content-type","text/xml") self.send_header("Content-length",str(len(response))) self.end_headers() cpem.log_event('debug',"response headers sent") self.wfile.write(response) cpem.log_event('debug',"response sent") self.wfile.flush() cpem.log_event('debug',"buffer flushed") self.connection.shutdown() #do we need to do a full shutdown? except: cpem.log_event('error',"Something went wrong sending the response")
def set_key_file(self,keyfile): """verifies that the key file exists """ #TODO: implement this cpem.log_event('debug',"setting self.cert_key=%s" % (keyfile)) self.cert_key = keyfile
def set_cert_file(self,certfile): """verifies that the file exists """ #TODO: implement this cpem.log_event('debug',"setting self.cert_file=%s" % (certfile)) self.cert_file = certfile
def set_server_host(self,host): """Takes an IP or hostname and, if its valid, set self.host to the passed value. """ #TODO: validate this-- it can be a host or an IP cpem.log_event('debug',"setting self.server_host=%s" % (host)) self.server_host = host
def __init__(self,HandlerClass=SecureXMLRpcRequestHandler,host='0.0.0.0',port=3170,cert='certs/sslcert.crt',key='certs/sslcert.crt'): cpem.log_event('debug',"entering CPEMServer constructor") try: self.set_server_host(host) self.set_server_port(port) self.set_cert_file(cert) self.set_key_file(key) except: cpem.log_event('critical','error occurred during setup') raise cpem.log_event('debug',"cleared initial cpem .set_* routines") try: cpem.log_event('debug',"starting SecureXMLRPCServer") self.server = SecureXMLRPCServer((self.server_host,self.server_port),HandlerClass,self.cert_file,self.cert_key) cpem.log_event('debug',"SecureXMLRPCServer started") self.server.register_introspection_functions() cpem.log_event('debug',"register_introspection_fuctions() completed") init_plugins(self.server) cpem.log_event('debug',"plugins loaded") self.server.serve_forever() except Exception,e: cpem.log_event('error',"failed to setup server: %s" % (e[0]))