diff options
author | Ramón M. Gómez <ramongomez@us.es> | 2019-01-29 10:11:38 +0100 |
---|---|---|
committer | Ramón M. Gómez <ramongomez@us.es> | 2019-01-29 10:11:38 +0100 |
commit | 3f59ea6b3143ba850ce03161d08c2813d9f352f4 (patch) | |
tree | 4a29e93022bd189c9563970970fcefbdf5e97743 | |
parent | 867e44e54d8a558a9d668069b6a5e106b417c2e0 (diff) |
#877: OGAgent can connect to an alternate server, and fixing some Python code cleanup.
4 files changed, 59 insertions, 32 deletions
diff --git a/admin/Sources/Clients/ogagent/src/cfg/ogagent.cfg b/admin/Sources/Clients/ogagent/src/cfg/ogagent.cfg index 8888e88a..3fa38ab2 100644 --- a/admin/Sources/Clients/ogagent/src/cfg/ogagent.cfg +++ b/admin/Sources/Clients/ogagent/src/cfg/ogagent.cfg @@ -8,6 +8,8 @@ path=test_modules/server # Remote OpenGnsys Service remote=https://192.168.2.10/opengnsys/rest +# Alternate OpenGnsys Service (comment out to enable this option) +#altremote=https://10.0.2.2/opengnsys/rest # Log Level, if ommited, will be set to INFO log=DEBUG diff --git a/admin/Sources/Clients/ogagent/src/opengnsys/RESTApi.py b/admin/Sources/Clients/ogagent/src/opengnsys/RESTApi.py index 5caaf8c4..d785dfa7 100644 --- a/admin/Sources/Clients/ogagent/src/opengnsys/RESTApi.py +++ b/admin/Sources/Clients/ogagent/src/opengnsys/RESTApi.py @@ -26,9 +26,9 @@ # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -''' +""" @author: Adolfo Gómez, dkmaster at dkmon dot com -''' +""" # pylint: disable-msg=E1101,W0703 @@ -43,7 +43,8 @@ from .log import logger from .utils import exceptionToMessage -VERIFY_CERT = False +VERIFY_CERT = False # Do not check server certificate +TIMEOUT = 5 # Connection timout, in seconds class RESTError(Exception): @@ -66,30 +67,34 @@ try: except Exception: pass # In fact, isn't too important, but wil log warns to logging file + class REST(object): - ''' + """ Simple interface to remote REST apis. The constructor expects the "base url" as parameter, that is, the url that will be common on all REST requests Remember that this is a helper for "easy of use". You can provide your owns using requests lib for example. Examples: v = REST('https://example.com/rest/v1/') (Can omit trailing / if desired) v.sendMessage('hello?param1=1¶m2=2') - This will generate a GET message to https://example.com/rest/v1/hello?param1=1¶m2=2, and return the deserialized JSON result or an exception + This will generate a GET message to https://example.com/rest/v1/hello?param1=1¶m2=2, and return the + deserialized JSON result or an exception v.sendMessage('hello?param1=1¶m2=2', {'name': 'mario' }) - This will generate a POST message to https://example.com/rest/v1/hello?param1=1¶m2=2, with json encoded body {'name': 'mario' }, and also returns + This will generate a POST message to https://example.com/rest/v1/hello?param1=1¶m2=2, with json encoded + body {'name': 'mario' }, and also returns the deserialized JSON result or raises an exception in case of error - ''' + """ + def __init__(self, url): - ''' + """ Initializes the REST helper url is the full url of the REST API Base, as for example "https://example.com/rest/v1". @param url The url of the REST API Base. The trailing '/' can be included or omitted, as desired. - ''' + """ self.endpoint = url - + if self.endpoint[-1] != '/': self.endpoint += '/' - + # Some OSs ships very old python requests lib implementations, workaround them... try: self.newerRequestLib = requests.__version__.split('.')[0] >= '1' @@ -105,37 +110,39 @@ class REST(object): pass def _getUrl(self, method): - ''' + """ Internal method Composes the URL based on "method" @param method: Method to append to base url for composition - ''' + """ url = self.endpoint + method return url def _request(self, url, data=None): - ''' + """ Launches the request @param url: The url to obtain - @param data: if None, the request will be sent as a GET request. If != None, the request will be sent as a POST, with data serialized as JSON in the body. - ''' + @param data: if None, the request will be sent as a GET request. If != None, the request will be sent as a POST, + with data serialized as JSON in the body. + """ try: if data is None: logger.debug('Requesting using GET (no data provided) {}'.format(url)) - # Old requests version does not support verify, but they do not checks ssl certificate by default + # Old requests version does not support verify, but it do not checks ssl certificate by default if self.newerRequestLib: - r = requests.get(url, verify=VERIFY_CERT) + r = requests.get(url, verify=VERIFY_CERT, timeout=TIMEOUT) else: - r = requests.get(url) - else: # POST + r = requests.get(url) + else: # POST logger.debug('Requesting using POST {}, data: {}'.format(url, data)) if self.newerRequestLib: - r = requests.post(url, data=data, headers={'content-type': 'application/json'}, verify=VERIFY_CERT) + r = requests.post(url, data=data, headers={'content-type': 'application/json'}, + verify=VERIFY_CERT, timeout=TIMEOUT) else: r = requests.post(url, data=data, headers={'content-type': 'application/json'}) - r = json.loads(r.content) # Using instead of r.json() to make compatible with oooold rquests lib versions + r = json.loads(r.content) # Using instead of r.json() to make compatible with old requests lib versions except requests.exceptions.RequestException as e: raise ConnectionError(e) except Exception as e: @@ -144,17 +151,17 @@ class REST(object): return r def sendMessage(self, msg, data=None, processData=True): - ''' + """ Sends a message to remote REST server @param data: if None or omitted, message will be a GET, else it will send a POST @param processData: if True, data will be serialized to json before sending, else, data will be sent as "raw" - ''' + """ logger.debug('Invoking post message {} with data {}'.format(msg, data)) if processData and data is not None: data = json.dumps(data) - + url = self._getUrl(msg) logger.debug('Requesting {}'.format(url)) - + return self._request(url, data) diff --git a/admin/Sources/Clients/ogagent/src/opengnsys/config.py b/admin/Sources/Clients/ogagent/src/opengnsys/config.py index c86c6979..d1f3ede6 100644 --- a/admin/Sources/Clients/ogagent/src/opengnsys/config.py +++ b/admin/Sources/Clients/ogagent/src/opengnsys/config.py @@ -33,7 +33,6 @@ from __future__ import unicode_literals from ConfigParser import SafeConfigParser -from .log import logger config = None diff --git a/admin/Sources/Clients/ogagent/src/opengnsys/modules/server/OpenGnSys/__init__.py b/admin/Sources/Clients/ogagent/src/opengnsys/modules/server/OpenGnSys/__init__.py index 8ef866ad..850dfb0f 100644 --- a/admin/Sources/Clients/ogagent/src/opengnsys/modules/server/OpenGnSys/__init__.py +++ b/admin/Sources/Clients/ogagent/src/opengnsys/modules/server/OpenGnSys/__init__.py @@ -47,6 +47,7 @@ from opengnsys import operations from opengnsys.log import logger from opengnsys.scriptThread import ScriptExecutorThread + # Error handler decorator. def catchBackgroundError(fnc): def wrapper(*args, **kwargs): @@ -57,9 +58,10 @@ def catchBackgroundError(fnc): this.REST.sendMessage('error?id={}'.format(kwargs.get('requestId', 'error')), {'error': '{}'.format(e)}) return wrapper + class OpenGnSysWorker(ServerWorker): name = 'opengnsys' - interface = None # Binded interface for OpenGnsys + interface = None # Bound interface for OpenGnsys loggedin = False # User session flag locked = {} random = None # Random string for secure connections @@ -106,7 +108,7 @@ class OpenGnSysWorker(ServerWorker): except OSError: pass # Copy file "HostsFile.FirstOctetOfIPAddress" to "HostsFile", if it exists - # (used in "exam mode" of the University of Seville) + # (used in "exam mode" from the University of Seville) hostsFile = os.path.join(operations.get_etc_path(), 'hosts') newHostsFile = hostsFile + '.' + self.interface.ip.split('.')[0] if os.path.isfile(newHostsFile): @@ -114,14 +116,28 @@ class OpenGnSysWorker(ServerWorker): # Generate random secret to send on activation self.random = ''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(self.length)) # Send initialization message - self.REST.sendMessage('ogagent/started', {'mac': self.interface.mac, 'ip': self.interface.ip, 'secret': self.random, 'ostype': operations.osType, 'osversion': operations.osVersion}) + try: + try: + self.REST.sendMessage('ogagent/started', {'mac': self.interface.mac, 'ip': self.interface.ip, + 'secret': self.random, 'ostype': operations.osType, + 'osversion': operations.osVersion}) + except: + # Trying to initialize on alternative server, if defined + # (used in "exam mode" from the University of Seville) + self.REST = REST(self.service.config.get('opengnsys', 'altremote')) + self.REST.sendMessage('ogagent/started', {'mac': self.interface.mac, 'ip': self.interface.ip, + 'secret': self.random, 'ostype': operations.osType, + 'osversion': operations.osVersion, 'alt_url': True}) + except: + logger.error('Initialization error') def onDeactivation(self): """ Sends OGAgent stopping notification to OpenGnsys server """ logger.debug('onDeactivation') - self.REST.sendMessage('ogagent/stopped', {'mac': self.interface.mac, 'ip': self.interface.ip, 'ostype': operations.osType, 'osversion': operations.osVersion}) + self.REST.sendMessage('ogagent/stopped', {'mac': self.interface.mac, 'ip': self.interface.ip, + 'ostype': operations.osType, 'osversion': operations.osVersion}) def processClientMessage(self, message, data): logger.debug('Got OpenGnsys message from client: {}, data {}'.format(message, data)) @@ -133,7 +149,8 @@ class OpenGnSysWorker(ServerWorker): user, sep, language = data.partition(',') logger.debug('Received login for {} with language {}'.format(user, language)) self.loggedin = True - self.REST.sendMessage('ogagent/loggedin', {'ip': self.interface.ip, 'user': user, 'language': language, 'ostype': operations.osType, 'osversion': operations.osVersion}) + self.REST.sendMessage('ogagent/loggedin', {'ip': self.interface.ip, 'user': user, 'language': language, + 'ostype': operations.osType, 'osversion': operations.osVersion}) def onLogout(self, user): """ @@ -200,6 +217,7 @@ class OpenGnSysWorker(ServerWorker): """ logger.debug('Received reboot operation') self.checkSecret(server) + # Rebooting thread. def rebt(): operations.reboot() @@ -212,6 +230,7 @@ class OpenGnSysWorker(ServerWorker): """ logger.debug('Received poweroff operation') self.checkSecret(server) + # Powering off thread. def pwoff(): time.sleep(2) |