summaryrefslogtreecommitdiffstats
path: root/Monitoring/src/main/python/Driver
diff options
context:
space:
mode:
Diffstat (limited to 'Monitoring/src/main/python/Driver')
-rw-r--r--Monitoring/src/main/python/Driver/Driver$py.classbin0 -> 3412 bytes
-rw-r--r--Monitoring/src/main/python/Driver/Driver.py17
-rw-r--r--Monitoring/src/main/python/Driver/Driver.py.old17
-rw-r--r--Monitoring/src/main/python/Driver/REST.py94
-rw-r--r--Monitoring/src/main/python/Driver/SOAPClient$py.classbin0 -> 3755 bytes
-rw-r--r--Monitoring/src/main/python/Driver/SOAPClient.py18
-rw-r--r--Monitoring/src/main/python/Driver/SOAPClient.py.old18
-rw-r--r--Monitoring/src/main/python/Driver/SshExec$py.classbin0 -> 12676 bytes
-rw-r--r--Monitoring/src/main/python/Driver/SshExec.py187
-rw-r--r--Monitoring/src/main/python/Driver/SshExec.py.old92
-rw-r--r--Monitoring/src/main/python/Driver/SshTunnel.py113
-rw-r--r--Monitoring/src/main/python/Driver/SshTunnel.py.old113
-rw-r--r--Monitoring/src/main/python/Driver/__init__$py.classbin0 -> 2058 bytes
-rw-r--r--Monitoring/src/main/python/Driver/__init__.py0
-rw-r--r--Monitoring/src/main/python/Driver/__init__.py.old0
-rw-r--r--Monitoring/src/main/python/Driver/test.py128
-rw-r--r--Monitoring/src/main/python/Driver/test.py.old122
17 files changed, 919 insertions, 0 deletions
diff --git a/Monitoring/src/main/python/Driver/Driver$py.class b/Monitoring/src/main/python/Driver/Driver$py.class
new file mode 100644
index 0000000..1bcb0c2
--- /dev/null
+++ b/Monitoring/src/main/python/Driver/Driver$py.class
Binary files differ
diff --git a/Monitoring/src/main/python/Driver/Driver.py b/Monitoring/src/main/python/Driver/Driver.py
new file mode 100644
index 0000000..a1f7dad
--- /dev/null
+++ b/Monitoring/src/main/python/Driver/Driver.py
@@ -0,0 +1,17 @@
+'''
+Created on Oct 28, 2011
+
+@author: steger, jozsef
+@organization: ELTE
+@contact: steger@complex.elte.hu
+'''
+
+class Driver(object):
+ '''
+ @summary: an empty driver to serve as an ancient class
+ @author: steger, jozsef
+ '''
+ pass
+
+class DriverError(Exception):
+ pass \ No newline at end of file
diff --git a/Monitoring/src/main/python/Driver/Driver.py.old b/Monitoring/src/main/python/Driver/Driver.py.old
new file mode 100644
index 0000000..a1f7dad
--- /dev/null
+++ b/Monitoring/src/main/python/Driver/Driver.py.old
@@ -0,0 +1,17 @@
+'''
+Created on Oct 28, 2011
+
+@author: steger, jozsef
+@organization: ELTE
+@contact: steger@complex.elte.hu
+'''
+
+class Driver(object):
+ '''
+ @summary: an empty driver to serve as an ancient class
+ @author: steger, jozsef
+ '''
+ pass
+
+class DriverError(Exception):
+ pass \ No newline at end of file
diff --git a/Monitoring/src/main/python/Driver/REST.py b/Monitoring/src/main/python/Driver/REST.py
new file mode 100644
index 0000000..aed2241
--- /dev/null
+++ b/Monitoring/src/main/python/Driver/REST.py
@@ -0,0 +1,94 @@
+'''
+Created on Feb 4, 2013
+
+@author: Sandor Laki, rewritten for jython
+@organization: ELTE
+@contact: laki@complex.elte.hu
+'''
+
+from Driver import Driver
+from Credential.credentialtypes import UsernamePassword
+import urllib2, base64
+
+from javax.net.ssl import TrustManager, X509TrustManager
+from jarray import array
+from javax.net.ssl import SSLContext
+
+class TrustAllX509TrustManager(X509TrustManager):
+ def checkClientTrusted(self, chain, auth):
+ pass
+
+ def checkServerTrusted(self, chain, auth):
+ pass
+
+ def getAcceptedIssuers(self):
+ return None
+
+# It is not threadsafe, since setDefault is a global function...
+def setSSLTrusted():
+ trust_managers = array([TrustAllX509TrustManager()], TrustManager)
+ TRUST_ALL_CONTEXT = SSLContext.getInstance("SSL")
+ TRUST_ALL_CONTEXT.init(None, trust_managers, None)
+ DEFAULT_CONTEXT = SSLContext.getDefault()
+ SSLContext.setDefault(TRUST_ALL_CONTEXT)
+
+class RESTDriver(Driver):
+ '''
+ @summary: implements REST driver to fetch using http GET
+ @cvar timeout: timeout of connection
+ @type timeout: float
+ @cvar cache: a cache directory
+ @type cache: str
+ @ivar url: a default document locator to be reused
+ @type url: str
+ @ivar proxy: an interface to the http server
+ @type proxy: httplib2.Http
+ '''
+ timeout = 10
+
+ def __init__(self, url, credential = None, validate_ssl = False):
+ '''
+ @summary: initializes a proxy to the http service and saves a default document locator
+ @param url: the default document locator
+ @type url: str
+ @param credential: an authentication secret
+ @type credential: L{Credential} or None
+ @param validate_ssl: whether to apply strick certificate validation, default is False
+ @type validate_ssl: bool
+ '''
+ self.url = url
+ self.proxy = urllib2.Request(self.url)
+ if isinstance(credential, UsernamePassword):
+ base64string = base64.encodestring('%s:%s' % (credential.username, credential.password)).replace('\n', '')
+ self.proxy.add_header("Authorization", "Basic %s" % base64string)
+# self.proxy = Http(cache = self.cache, timeout = self.timeout)
+# self.proxy.disable_ssl_certificate_validation = not validate_ssl
+# if isinstance(credential, UsernamePassword):
+# # use password authentication
+# self.proxy.add_credentials(credential.username, credential.password)
+
+ def fetch(self, url = None):
+ '''
+ @summary: retrieve the document
+ @param url: the document locator, if not present the default is used
+ @type url: str or None
+ @return: the remote document
+ @rtype: str or None
+ @note: if the remote content cached is not changed, None is returned
+ '''
+ if url is None:
+ url = self.url
+ try:
+ resp = urllib2.urlopen(self.proxy)
+ return resp.read()
+ except Exception, e:
+ print "Error: %s" % e
+ return None
+# status, response = self.proxy.request(uri = url, method = "GET")
+# if status.status == 200:
+# return response
+# if status.status == 304:
+# self.logger.warning("remote content @ %s was not changed" % url)
+# return None
+# self.logger.error("%s -- retrieving @%s failed: %s" % (status, url, response))
+# return None
diff --git a/Monitoring/src/main/python/Driver/SOAPClient$py.class b/Monitoring/src/main/python/Driver/SOAPClient$py.class
new file mode 100644
index 0000000..ff46733
--- /dev/null
+++ b/Monitoring/src/main/python/Driver/SOAPClient$py.class
Binary files differ
diff --git a/Monitoring/src/main/python/Driver/SOAPClient.py b/Monitoring/src/main/python/Driver/SOAPClient.py
new file mode 100644
index 0000000..e61888d
--- /dev/null
+++ b/Monitoring/src/main/python/Driver/SOAPClient.py
@@ -0,0 +1,18 @@
+'''
+Created on Sep 2, 2011
+
+@author: laki, sandor
+@organization: ELTE
+@contact: laki@complex.elte.hu
+@author: steger, jozsef
+'''
+
+import suds
+import suds.transport
+from Driver import Driver
+
+class SOAPClient(Driver, suds.client.Client):
+ pass
+SOAPSecurity=suds.wsse.Security
+SOAPUsernameToken=suds.wsse.UsernameToken
+SOAPHttpAuthenticated=suds.transport.http.HttpAuthenticated
diff --git a/Monitoring/src/main/python/Driver/SOAPClient.py.old b/Monitoring/src/main/python/Driver/SOAPClient.py.old
new file mode 100644
index 0000000..e61888d
--- /dev/null
+++ b/Monitoring/src/main/python/Driver/SOAPClient.py.old
@@ -0,0 +1,18 @@
+'''
+Created on Sep 2, 2011
+
+@author: laki, sandor
+@organization: ELTE
+@contact: laki@complex.elte.hu
+@author: steger, jozsef
+'''
+
+import suds
+import suds.transport
+from Driver import Driver
+
+class SOAPClient(Driver, suds.client.Client):
+ pass
+SOAPSecurity=suds.wsse.Security
+SOAPUsernameToken=suds.wsse.UsernameToken
+SOAPHttpAuthenticated=suds.transport.http.HttpAuthenticated
diff --git a/Monitoring/src/main/python/Driver/SshExec$py.class b/Monitoring/src/main/python/Driver/SshExec$py.class
new file mode 100644
index 0000000..c627e9b
--- /dev/null
+++ b/Monitoring/src/main/python/Driver/SshExec$py.class
Binary files differ
diff --git a/Monitoring/src/main/python/Driver/SshExec.py b/Monitoring/src/main/python/Driver/SshExec.py
new file mode 100644
index 0000000..5de7051
--- /dev/null
+++ b/Monitoring/src/main/python/Driver/SshExec.py
@@ -0,0 +1,187 @@
+from __future__ import with_statement
+'''
+Created on Feb 29, 2012
+
+@summary: A Jython compatible ssh driver
+@author: Sandor Laki
+@organization: ELTE
+@contact: lakis@inf.elte.hu
+'''
+
+
+from java.io import BufferedReader
+from java.io import IOException
+from java.io import InputStream
+from java.io import InputStreamReader
+from java.io import File
+from jarray import zeros
+from java.lang import String
+from com.jcraft.jsch import JSch
+from StringIO import StringIO
+#import libssh2
+#import socket
+from tempfile import mkstemp
+from os import close, write, unlink, path, access, R_OK
+#from SshKeygen import SshKeygen
+from threading import Lock
+from Credential.credentialtypes import Credential, UsernameRSAKey,\
+ UsernamePassword
+from Driver import Driver
+import org.python.core.util.FileUtil as FileUtil
+import java.lang.Exception
+#from org.slf4j import Logger
+#from org.slf4j import LoggerFactory
+#import org.python.core.PyFile as PyFile
+#driverlock = Lock()
+
+class SshExec(Driver):
+ '''
+ @summary: this class handles control of a monitoring tool over an ssh channel
+ @author: steger, jozsef
+ @todo: get rid of global lock if possible
+ @note: if no global lock is there, a lot os segmentation faults occur in a concurrent session opening and program execution
+ '''
+ #lock = Lock() #driverlock
+# log = LoggerFactory.getLogger("eu.novi.monitoring.Driver.SshExec")
+
+ def __init__(self, host, credential, port = 22, command = "echo helloworld @ `hostname`", known_host = None):
+ '''
+ @summary: initiates a class to execute a single remote command via ssh protocol, tekes care of opening ssh session
+ @param host: name of the hos machine
+ @type host: string
+ @param credential: authentication details
+ @type credential: Credential
+ @param port: port of the ssh service
+ @type port: integer
+ @param command: the remote command to execute later
+ @type command: string
+ @raise Exception: wrong authentication type
+
+ @note: only a single command can be run by the class
+
+
+ @todo: check what happens with commands run in the background
+ '''
+ self.lock = Lock()
+ self.session = None
+ self.channel = None
+ if host is None: return
+
+ if not isinstance(credential, Credential):
+ raise Exception("wrong type of credential")
+ with self.lock:
+ self._result = ""
+# self.session = libssh2.Session()
+# self.session.set_banner()
+ self.command = command
+ self.fn_pub = None
+# self.pemfile = None
+
+ try:
+ self.jsch = JSch()
+# self.log.info("Host:%s Username:%s Port:%s Command:%s" % (host, credential.username, port, self.command))
+ print "h:%s un:%s p:%s" % (host, credential.username, port)
+ self.session = self.jsch.getSession(credential.username, host, port)
+ #self.jsch.setKnownHosts("/home/maven/.ssh/known_hosts")
+
+ if isinstance(credential, UsernameRSAKey):
+ privatekey = credential.rsakey
+# self.log.info("Credential: %s" % privatekey)
+ self.jsch.addIdentity(privatekey)
+ self.session.setConfig("StrictHostKeyChecking", "no")
+ self.session.setTimeout(5000);
+ print "identity file %s\n" % privatekey
+ PATH=privatekey
+ if path.exists(PATH) and path.isfile(PATH) and access(PATH, R_OK):
+ print "File exists and is readable"
+# self.log.info("Privatekey exists and is readable")
+ else:
+# self.log.info("RSA key is missing: %s" % PATH)
+ raise Exception("RSA key file is missing or not readable: %s" % PATH)
+
+# publickey_srt = SshKeygen.convert_key_from_file(privatekey)
+# fd, publickey = mkstemp(suffix = ".pub", prefix = "rsa", text = True)
+# write(fd, "ssh-rsa %s" % publickey_srt)
+# close(fd)
+# self.fn_pub = publickey
+# self.session._session.userauth_publickey_fromfile(credential.username, publickey, privatekey, credential.password)
+ elif isinstance(credential, UsernamePassword):
+ self.session.setPassword( credential.password )
+ else:
+ raise Exception("wrong type of credential")
+
+ self.session.connect()
+ except java.lang.Exception, e:
+# self.log.info("Connection error")
+ print "Connection Error"
+ print "Exc:%s" % e
+ self.session = None
+ self.channel = None
+ #raise e
+
+# self.channel = self.session.open_session()
+
+ def execute(self):
+ '''
+ @summary: invokes the remote command to run. The standard output of the command is stored in the result variable.
+ '''
+ with self.lock:
+# self.log.info("Execute:%s" % self.command)
+ if self.session is None: return StringIO("")
+ self.channel = self.session.openChannel("exec")
+ self.channel.setCommand(self.command)
+ self.channel.setInputStream(None)
+
+ stdo = self.channel.getInputStream()
+# br = BufferedReader( InputStreamReader( stdo ) )
+ self.channel.connect()
+
+ return FileUtil.wrap( stdo )
+
+# buffer = 4096
+# buf = zeros(1024,'b')
+# while True:
+# while stdo.available()>0:
+# i=stdo.read(buf,0,1024)
+# if i<0: break
+# self._result += str(String(buf,0,i))
+# if channel.isClosed(): break
+# channel.disconnect()
+# return StringIO(self._result)
+
+# def _get_result(self):
+# '''
+# @summary: the copy of the standard output of the remote command
+# @return: the standard output of the remote command
+# @rtype: string
+# '''
+# return str(self._result)
+
+ def close(self):
+ '''
+ @summary: the destructor takes care of closing the session and removing the public key file stored temporary
+ '''
+ with self.lock:
+ if self.channel is not None:
+ self.channel.disconnect()
+ self.channel = None
+ if self.session is not None:
+ self.session.disconnect()
+# if self.fn_pub is not None:
+# unlink(self.fn_pub)
+
+# result = property(_get_result,None,None)
+
+ def __del__(self):
+ self.close()
+
+ def _isConnected(self):
+ try:
+ if self.channel is not None: return True
+ else: return False
+ except:
+ return False
+
+ isConnected = property(_isConnected,None, None)
+
+
diff --git a/Monitoring/src/main/python/Driver/SshExec.py.old b/Monitoring/src/main/python/Driver/SshExec.py.old
new file mode 100644
index 0000000..5de3b14
--- /dev/null
+++ b/Monitoring/src/main/python/Driver/SshExec.py.old
@@ -0,0 +1,92 @@
+'''
+Created on Jul 18, 2011
+
+@author: steger, jozsef
+@organization: ELTE
+@contact: steger@complex.elte.hu
+'''
+
+from Driver import Driver, DriverError
+from paramiko import SSHClient, RSAKey, SSHException, AutoAddPolicy
+from Credential.credentialtypes import UsernamePassword, UsernameRSAKey
+from time import sleep
+
+class SshDriver(Driver):
+ timeout = 5
+ trials = 3
+ wait = .2
+
+ def __init__(self):
+ self.client = None
+
+ def __del__(self):
+ self.close()
+
+ def connect(self, host, credential, port = 22, known_host = None):
+ self.client = SSHClient()
+ if known_host is None:
+ self.client.set_missing_host_key_policy( AutoAddPolicy() )
+ else:
+ self.client.load_host_keys(filename = known_host)
+ if isinstance(credential, UsernamePassword):
+ # use password authentication
+ self.client.connect(hostname = host, port = port,
+ username = credential.username, password =credential.password,
+ timeout = self.timeout, look_for_keys = False, compress = True)
+ elif isinstance(credential, UsernameRSAKey):
+ # use the RSA key
+ if credential.password:
+ pw = credential.password
+ else:
+ pw = None
+ key = RSAKey(password = pw, filename = credential.rsakey)
+ n = self.trials
+ while n:
+ try:
+ self.client.connect(hostname = host, port = port,
+ username = credential.username, pkey = key,
+ timeout = self.timeout, look_for_keys = False, compress = True)
+ break
+ except SSHException, e:
+ if e.message.startswith("Error reading SSH protocol banner"):
+ n -= 1
+ print "WW: retry to connect @%s in %f seconds" % (host, self.wait)
+ sleep(self.wait)
+ else:
+ raise
+ if not self.isConnected:
+ self.close()
+ raise DriverError("Cannot connect @%s " % host)
+ self.host = host
+
+ def close(self):
+ try:
+ self.client.close()
+ except:
+ pass
+ finally:
+ self.client = None
+
+ @property
+ def isConnected(self):
+ try:
+ return self.client.get_transport().is_active()
+ except:
+ return False
+
+class SshExec(SshDriver):
+ def __init__(self, host, credential, port = 22, command = "echo helloworld @ `hostname`", known_host = None):
+ SshDriver.__init__(self)
+ self.connect(host, credential, port, known_host)
+ self.command = command
+
+ def execute(self, command = None):
+ if not self.isConnected:
+ raise DriverError("Not connected")
+ if command is None:
+ command = self.command
+ _, stout, sterr = self.client.exec_command(command = command)
+ e = sterr.read()
+ if len(e):
+ print "EE: execution @%s '%s' failed: %s" % (self.host, command, e)
+ return stout
diff --git a/Monitoring/src/main/python/Driver/SshTunnel.py b/Monitoring/src/main/python/Driver/SshTunnel.py
new file mode 100644
index 0000000..83649df
--- /dev/null
+++ b/Monitoring/src/main/python/Driver/SshTunnel.py
@@ -0,0 +1,113 @@
+'''
+Created on Jan 14, 2013
+
+@author: steger
+'''
+
+import select
+import SocketServer
+import sys
+
+import paramiko
+
+#FIXME: let an SshTunnel instance launch a new thread;
+#TODO: docs
+#TODO: localport could be retrieved from a pool
+
+class ForwardServer (SocketServer.ThreadingTCPServer):
+ daemon_threads = True
+ allow_reuse_address = True
+
+
+class Handler (SocketServer.BaseRequestHandler):
+
+ def handle(self):
+ try:
+ chan = self.ssh_transport.open_channel('direct-tcpip',
+ (self.chain_host, self.chain_port),
+ self.request.getpeername())
+ except Exception, e:
+ print('Incoming request to %s:%d failed: %s' % (self.chain_host,
+ self.chain_port,
+ repr(e)))
+ return
+ if chan is None:
+ print('Incoming request to %s:%d was rejected by the SSH server.' %
+ (self.chain_host, self.chain_port))
+ return
+
+ print('Connected! Tunnel open %r -> %r -> %r' % (self.request.getpeername(),
+ chan.getpeername(), (self.chain_host, self.chain_port)))
+ while True:
+ r, w, x = select.select([self.request, chan], [], [])
+ if self.request in r:
+ data = self.request.recv(1024)
+ if len(data) == 0:
+ break
+ chan.send(data)
+ if chan in r:
+ data = chan.recv(1024)
+ if len(data) == 0:
+ break
+ self.request.send(data)
+ chan.close()
+ self.request.close()
+ print ('Tunnel closed from %r' % (self.request.getpeername(),))
+
+
+
+
+class SshTunnel(object):
+ '''
+This class establishes a connection to the requested SSH server and sets up local port
+forwarding (the openssh -L option) from a local port through a tunneled
+connection to a destination reachable from the SSH server machine.
+ '''
+ def __init__(self):
+ pass
+
+ def setup(self, localport = 4000, username = 'root', server = 'localhost', serverport = 22, remoteserver = 'localhost', remoteport = 22, keyfile = None, password = None,
+ look_for_keys = False):
+ '''
+ Constructor
+ '''
+ client = paramiko.SSHClient()
+ client.load_system_host_keys()
+ client.set_missing_host_key_policy(paramiko.WarningPolicy())
+
+ print ('Connecting to ssh host %s:%d ...' % (server, serverport))
+ try:
+ client.connect(server, serverport, username = username, key_filename = keyfile,
+ look_for_keys = look_for_keys, password = password)
+ except Exception, e:
+ print '*** Failed to connect to %s:%d: %r' % (server, serverport, e)
+ sys.exit(1)
+
+ print ('Now forwarding port %d to %s:%d ...' % (localport, remoteserver, remoteport))
+
+ try:
+ # this is a little convoluted, but lets me configure things for the Handler
+ # object. (SocketServer doesn't give Handlers any way to access the outer
+ # server normally.)
+ class SubHander (Handler):
+ chain_host = remoteserver
+ chain_port = remoteport
+ ssh_transport = client.get_transport()
+ self.service = ForwardServer(('', localport), SubHander)
+ self.service.serve_forever()
+ except KeyboardInterrupt:
+ print 'C-c: Port forwarding stopped.'
+ sys.exit(0)
+
+ def teardown(self):
+ print "ENDE"
+ self.service.shutdown()
+
+
+if __name__ == '__main__':
+ T = SshTunnel()
+ from threading import Timer
+ t = Timer(5.0, T.teardown)
+ t.start() # after 30 seconds, "hello, world" will be printed
+ T.setup(username = 'novi_novi', server = 'novilab.elte.hu', remoteserver = 'complex.elte.hu', keyfile = '/home/steger/Private/ssh/novi_rsa')
+ \ No newline at end of file
diff --git a/Monitoring/src/main/python/Driver/SshTunnel.py.old b/Monitoring/src/main/python/Driver/SshTunnel.py.old
new file mode 100644
index 0000000..83649df
--- /dev/null
+++ b/Monitoring/src/main/python/Driver/SshTunnel.py.old
@@ -0,0 +1,113 @@
+'''
+Created on Jan 14, 2013
+
+@author: steger
+'''
+
+import select
+import SocketServer
+import sys
+
+import paramiko
+
+#FIXME: let an SshTunnel instance launch a new thread;
+#TODO: docs
+#TODO: localport could be retrieved from a pool
+
+class ForwardServer (SocketServer.ThreadingTCPServer):
+ daemon_threads = True
+ allow_reuse_address = True
+
+
+class Handler (SocketServer.BaseRequestHandler):
+
+ def handle(self):
+ try:
+ chan = self.ssh_transport.open_channel('direct-tcpip',
+ (self.chain_host, self.chain_port),
+ self.request.getpeername())
+ except Exception, e:
+ print('Incoming request to %s:%d failed: %s' % (self.chain_host,
+ self.chain_port,
+ repr(e)))
+ return
+ if chan is None:
+ print('Incoming request to %s:%d was rejected by the SSH server.' %
+ (self.chain_host, self.chain_port))
+ return
+
+ print('Connected! Tunnel open %r -> %r -> %r' % (self.request.getpeername(),
+ chan.getpeername(), (self.chain_host, self.chain_port)))
+ while True:
+ r, w, x = select.select([self.request, chan], [], [])
+ if self.request in r:
+ data = self.request.recv(1024)
+ if len(data) == 0:
+ break
+ chan.send(data)
+ if chan in r:
+ data = chan.recv(1024)
+ if len(data) == 0:
+ break
+ self.request.send(data)
+ chan.close()
+ self.request.close()
+ print ('Tunnel closed from %r' % (self.request.getpeername(),))
+
+
+
+
+class SshTunnel(object):
+ '''
+This class establishes a connection to the requested SSH server and sets up local port
+forwarding (the openssh -L option) from a local port through a tunneled
+connection to a destination reachable from the SSH server machine.
+ '''
+ def __init__(self):
+ pass
+
+ def setup(self, localport = 4000, username = 'root', server = 'localhost', serverport = 22, remoteserver = 'localhost', remoteport = 22, keyfile = None, password = None,
+ look_for_keys = False):
+ '''
+ Constructor
+ '''
+ client = paramiko.SSHClient()
+ client.load_system_host_keys()
+ client.set_missing_host_key_policy(paramiko.WarningPolicy())
+
+ print ('Connecting to ssh host %s:%d ...' % (server, serverport))
+ try:
+ client.connect(server, serverport, username = username, key_filename = keyfile,
+ look_for_keys = look_for_keys, password = password)
+ except Exception, e:
+ print '*** Failed to connect to %s:%d: %r' % (server, serverport, e)
+ sys.exit(1)
+
+ print ('Now forwarding port %d to %s:%d ...' % (localport, remoteserver, remoteport))
+
+ try:
+ # this is a little convoluted, but lets me configure things for the Handler
+ # object. (SocketServer doesn't give Handlers any way to access the outer
+ # server normally.)
+ class SubHander (Handler):
+ chain_host = remoteserver
+ chain_port = remoteport
+ ssh_transport = client.get_transport()
+ self.service = ForwardServer(('', localport), SubHander)
+ self.service.serve_forever()
+ except KeyboardInterrupt:
+ print 'C-c: Port forwarding stopped.'
+ sys.exit(0)
+
+ def teardown(self):
+ print "ENDE"
+ self.service.shutdown()
+
+
+if __name__ == '__main__':
+ T = SshTunnel()
+ from threading import Timer
+ t = Timer(5.0, T.teardown)
+ t.start() # after 30 seconds, "hello, world" will be printed
+ T.setup(username = 'novi_novi', server = 'novilab.elte.hu', remoteserver = 'complex.elte.hu', keyfile = '/home/steger/Private/ssh/novi_rsa')
+ \ No newline at end of file
diff --git a/Monitoring/src/main/python/Driver/__init__$py.class b/Monitoring/src/main/python/Driver/__init__$py.class
new file mode 100644
index 0000000..3dd4a49
--- /dev/null
+++ b/Monitoring/src/main/python/Driver/__init__$py.class
Binary files differ
diff --git a/Monitoring/src/main/python/Driver/__init__.py b/Monitoring/src/main/python/Driver/__init__.py
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/Monitoring/src/main/python/Driver/__init__.py
diff --git a/Monitoring/src/main/python/Driver/__init__.py.old b/Monitoring/src/main/python/Driver/__init__.py.old
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/Monitoring/src/main/python/Driver/__init__.py.old
diff --git a/Monitoring/src/main/python/Driver/test.py b/Monitoring/src/main/python/Driver/test.py
new file mode 100644
index 0000000..0a502b2
--- /dev/null
+++ b/Monitoring/src/main/python/Driver/test.py
@@ -0,0 +1,128 @@
+from __future__ import with_statement
+'''
+Created on Aug 10, 2011
+
+@author: steger
+'''
+
+import site
+site.addsitedir('../site-packages')
+
+import unittest2
+from random import randint
+from Example.Resources import PLnodes
+from threading import Thread
+from Example.credentials import noviCredential, sonomaCredential
+from SshExec import SshExec
+from SOAPClient import SOAPClient
+
+class Test(unittest2.TestCase):
+ testnodes = map(lambda x: x.get_ipaddress("eth0")[0], PLnodes)
+ cred_novi = noviCredential
+ url_sonoma = "http://complex.elte.hu/~steger/sonoma/user.wsdl"
+ cred_sonoma = sonomaCredential
+
+
+ def setUp(self):
+ pass
+
+ def tearDown(self):
+ pass
+
+ def gettestnode(self):
+ '''
+ @summary: Return a test node IP address chosen random
+ @return: ip address
+ @rtype: string
+ '''
+ return self.testnodes[randint(1, len(self.testnodes))-1]
+
+ def test_helloworldWithMaster(self):
+ '''
+ @summary: Execute remote command in the name of the testuser authenticated with the master key
+ '''
+ proc = SshExec(host = self.gettestnode(), credential = self.cred_novi)
+ result = proc.execute().read()
+ print "alma %s" % result
+ self.assertTrue(result.startswith("helloworld @ "), "Remote command output differs from expected")
+
+ def echoWithMaster(self, address):
+ '''
+ @summary: Execute remote echo command in the name of the testuser authenticated with the master key
+ @param address: ip address of the remote machine
+ @type address: string
+ '''
+ try:
+ n = randint(0, 10000)
+ command = "echo %d" % n
+ proc = SshExec(host = address, credential = self.cred_novi, command = command)
+ result = proc.execute().read()
+ self.assertTrue(result.strip() == str(n), "Remote command @%s output differs from expected: (%s != %d)" % (address, result, n))
+ except Exception, e:
+ self.assertFalse(True, "Got an error %s" % e)
+
+ def test_echoWithMaster(self):
+ '''
+ @summary: Execute remote echo command in the name of the testuser authenticated with the master key
+ '''
+ self.echoWithMaster(self.gettestnode())
+
+ def test_distributedEcho(self):
+ '''
+ @summary: Execute parallel remote echo commands in a distributed fashion
+ '''
+ threads = []
+ for n in self.testnodes:
+ t = Thread(target = self.echoWithMaster, args = (n,))
+ t.daemon = True
+ t.start()
+ threads.append(t)
+ while len(threads):
+ t = threads.pop()
+ t.join(5)
+
+ def test_parallelEcho(self):
+ '''
+ @summary: Execute parallel remote echo commands in a test node
+ '''
+ N = 20
+ n = self.gettestnode()
+ threads = []
+ while N:
+ N -= 1
+ t = Thread(target = self.echoWithMaster, args = (n,))
+ t.daemon = True
+ t.start()
+ threads.append(t)
+ while len(threads):
+ t = threads.pop()
+ t.join(5)
+
+ def test_stress(self):
+ '''
+ @summary: Consecutively execute parallel remote echo commands in a distributed fashion
+ '''
+ threads = []
+ for n in self.testnodes:
+ N = randint(5, 20)
+ while N:
+ N -= 1
+ t = Thread(target = self.echoWithMaster, args = (n,))
+ t.daemon = True
+ t.start()
+ threads.append(t)
+ while len(threads):
+ t = threads.pop()
+ t.join(5)
+
+ def test_soap(self):
+ '''
+ @summary: Run SONoMA getNodeList
+ '''
+ client = SOAPClient(self.url_sonoma)
+ resources = client.service.getNodeList(filter = "AVAILABLE")
+ self.assertGreater(len(resources), 0, "sonoma reports no nodes")
+
+if __name__ == "__main__":
+ import sys;sys.argv = ['', 'Test.test_stress']
+ unittest2.main()
diff --git a/Monitoring/src/main/python/Driver/test.py.old b/Monitoring/src/main/python/Driver/test.py.old
new file mode 100644
index 0000000..7e93fee
--- /dev/null
+++ b/Monitoring/src/main/python/Driver/test.py.old
@@ -0,0 +1,122 @@
+'''
+Created on Aug 10, 2011
+
+@author: steger
+'''
+import unittest
+from random import randint
+from Example.Resources import PLnodes
+from threading import Thread
+from Example.credentials import noviCredential, sonomaCredential
+from SshExec import SshExec
+from SOAPClient import SOAPClient
+
+class Test(unittest.TestCase):
+ testnodes = map(lambda x: x.get_ipaddress("eth0")[0], PLnodes)
+ cred_novi = noviCredential
+ url_sonoma = "http://complex.elte.hu/~steger/sonoma/user.wsdl"
+ cred_sonoma = sonomaCredential
+
+
+ def setUp(self):
+ pass
+
+ def tearDown(self):
+ pass
+
+ def gettestnode(self):
+ '''
+ @summary: Return a test node IP address chosen random
+ @return: ip address
+ @rtype: string
+ '''
+ return self.testnodes[randint(1, len(self.testnodes))-1]
+
+ def test_helloworldWithMaster(self):
+ '''
+ @summary: Execute remote command in the name of the testuser authenticated with the master key
+ '''
+ proc = SshExec(host = self.gettestnode(), credential = self.cred_novi)
+ result = proc.execute().read()
+ self.assertTrue(result.startswith("helloworld @ "), "Remote command output differs from expected")
+
+ def echoWithMaster(self, address):
+ '''
+ @summary: Execute remote echo command in the name of the testuser authenticated with the master key
+ @param address: ip address of the remote machine
+ @type address: string
+ '''
+ try:
+ n = randint(0, 10000)
+ command = "echo %d" % n
+ proc = SshExec(host = address, credential = self.cred_novi, command = command)
+ result = proc.execute().read()
+ self.assertTrue(result.strip() == str(n), "Remote command @%s output differs from expected: (%s != %d)" % (address, result, n))
+ except Exception, e:
+ self.assertFalse(True, "Got an error %s" % e)
+
+ def test_echoWithMaster(self):
+ '''
+ @summary: Execute remote echo command in the name of the testuser authenticated with the master key
+ '''
+ self.echoWithMaster(self.gettestnode())
+
+ def test_distributedEcho(self):
+ '''
+ @summary: Execute parallel remote echo commands in a distributed fashion
+ '''
+ threads = []
+ for n in self.testnodes:
+ t = Thread(target = self.echoWithMaster, args = (n,))
+ t.daemon = True
+ t.start()
+ threads.append(t)
+ while len(threads):
+ t = threads.pop()
+ t.join(5)
+
+ def test_parallelEcho(self):
+ '''
+ @summary: Execute parallel remote echo commands in a test node
+ '''
+ N = 20
+ n = self.gettestnode()
+ threads = []
+ while N:
+ N -= 1
+ t = Thread(target = self.echoWithMaster, args = (n,))
+ t.daemon = True
+ t.start()
+ threads.append(t)
+ while len(threads):
+ t = threads.pop()
+ t.join(5)
+
+ def test_stress(self):
+ '''
+ @summary: Consecutively execute parallel remote echo commands in a distributed fashion
+ '''
+ threads = []
+ for n in self.testnodes:
+ N = randint(5, 20)
+ while N:
+ N -= 1
+ t = Thread(target = self.echoWithMaster, args = (n,))
+ t.daemon = True
+ t.start()
+ threads.append(t)
+ while len(threads):
+ t = threads.pop()
+ t.join(5)
+
+ def test_soap(self):
+ '''
+ @summary: Run SONoMA getNodeList
+ '''
+ client = SOAPClient(self.url_sonoma)
+ resources = client.service.getNodeList(filter = "AVAILABLE")
+ self.assertGreater(len(resources), 0, "sonoma reports no nodes")
+
+if __name__ == "__main__":
+ #import sys;sys.argv = ['', 'Test.test_helloworldWithMaster']
+ unittest.main() \ No newline at end of file