From 81a9b65d7994f83194f30caf41bec3e074aef3f3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ram=C3=B3n=20M=2E=20G=C3=B3mez?= Date: Mon, 18 Jun 2018 20:47:35 +0200 Subject: [PATCH] #750: Using PEP 8 Style Guide for Python in new module; implementing basic {{{getconfig}}} operation. --- oglive/build-package.sh | 7 ++ oglive/build-packages.sh | 11 -- .../modules/server/OpenGnSys/__init__.py | 79 ++++++++---- src/opengnsys/oglive/operations.py | 113 ++++++------------ src/opengnsys/operations.py | 6 +- 5 files changed, 102 insertions(+), 114 deletions(-) create mode 100755 oglive/build-package.sh delete mode 100755 oglive/build-packages.sh diff --git a/oglive/build-package.sh b/oglive/build-package.sh new file mode 100755 index 0000000..c0e03c5 --- /dev/null +++ b/oglive/build-package.sh @@ -0,0 +1,7 @@ +#!/bin/bash + +cd $(dirname "$0") + +# Build package +dpkg-buildpackage -b -d + diff --git a/oglive/build-packages.sh b/oglive/build-packages.sh deleted file mode 100755 index 4d5eb8d..0000000 --- a/oglive/build-packages.sh +++ /dev/null @@ -1,11 +0,0 @@ -#!/bin/bash - -cd $(dirname "$0") -top=`pwd` - -[ -r ../src/VERSION ] && VERSION="$(cat ../src/VERSION)" || VERSION="1.1.0" -RELEASE="1" - -# Debian based -dpkg-buildpackage -b -d - diff --git a/src/opengnsys/modules/server/OpenGnSys/__init__.py b/src/opengnsys/modules/server/OpenGnSys/__init__.py index 24d69ee..3100d93 100644 --- a/src/opengnsys/modules/server/OpenGnSys/__init__.py +++ b/src/opengnsys/modules/server/OpenGnSys/__init__.py @@ -30,20 +30,20 @@ """ from __future__ import unicode_literals -import threading import os -import platform -import time import random import shutil import string +import threading +import time import urllib -from opengnsys.workers import ServerWorker -from opengnsys import REST, RESTError +from opengnsys import REST from opengnsys import operations from opengnsys.log import logger from opengnsys.scriptThread import ScriptExecutorThread +from opengnsys.workers import ServerWorker + # Check authorization header decorator @@ -76,12 +76,38 @@ def catch_background_error(fnc): return wrapper +def check_locked_partition(sync=False): + """ + Decorator to check if a partition is locked + """ + def outer(fnc): + def wrapper(*args, **kwargs): + part_id = 'None' + try: + this, path, get_params, post_params = args # @UnusedVariable + part_id = post_params['disk'] + post_params['part'] + if this.locked.get(part_id, False): + this.locked[part_id] = True + fnc(*args, **kwargs) + else: + return 'partition locked' + except Exception as e: + this.locked[part_id] = False + return 'error {}'.format(e) + finally: + if sync is True: + this.locked[part_id] = False + logger.debug('Lock status: {} {}'.format(fnc, this.locked)) + return wrapper + return outer + + class OpenGnSysWorker(ServerWorker): name = 'opengnsys' interface = None # Bound interface for OpenGnsys REST = None # REST object logged_in = False # User session flag - locked = {} + locked = {} # Locked partitions random = None # Random string for secure connections length = 32 # Random string length @@ -92,6 +118,7 @@ class OpenGnSysWorker(ServerWorker): t = 0 # Generate random secret to send on activation self.random = ''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(self.length)) + self.cmd = None # Ensure cfg has required configuration variables or an exception will be thrown url = self.service.config.get('opengnsys', 'remote') self.REST = REST(url) @@ -213,23 +240,15 @@ class OpenGnSysWorker(ServerWorker): :param server: :return: JSON object {"status": "status_code", "loggedin": boolean} """ - res = {'status': '', 'loggedin': self.logged_in} - if platform.system() == 'Linux': # GNU/Linux - # Check if it's OpenGnsys Client. - if os.path.exists('/scripts/oginit'): - # Check if OpenGnsys Client is busy. - if self.locked: - res['status'] = 'BSY' - else: - res['status'] = 'OPG' - else: - # Check if there is an active session. - res['status'] = 'LNX' - elif platform.system() == 'Windows': # Windows - # Check if there is an active session. - res['status'] = 'WIN' - elif platform.system() == 'Darwin': # Mac OS X ?? - res['status'] = 'OSX' + st = {'linux': 'LNX', 'macos': 'OSX', 'oglive': 'OPG', 'windows': 'WIN'} + res = {'loggedin': self.loggedin} + try: + res['status'] = st[operations.os_type.lower()] + except KeyError: + res['status'] = '' + # Check if OpenGnsys Client is busy + if res['status'] == 'OPG' and self.locked: + res['status'] = 'BSY' return res @check_secret @@ -313,3 +332,17 @@ class OpenGnSysWorker(ServerWorker): def process_client_popup(self, params): self.REST.sendMessage('popup_done', params) + + def process_getconfig(self, path, get_params, post_params, server): + """ + Returns client configuration + :param path: + :param get_params: + :param post_params: + :param server: + :return: object + """ + logger.debug('Recieved getconfig operation') + self.checkSecret(server) + # Returns raw data + return {'config': operations.get_disk_config()} diff --git a/src/opengnsys/oglive/operations.py b/src/opengnsys/oglive/operations.py index ded4379..6c67421 100644 --- a/src/opengnsys/oglive/operations.py +++ b/src/opengnsys/oglive/operations.py @@ -26,17 +26,14 @@ # 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: Ramón M. Gómez, ramongomez at us dot es -''' +""" from __future__ import unicode_literals import socket import platform import fcntl -import os -import ctypes # @UnusedImport -import ctypes.util import subprocess import struct import array @@ -44,37 +41,11 @@ import six from opengnsys import utils -def checkLockedPartition(sync=False): - ''' - Decorator to check if a partition is locked - ''' - def outer(fnc): - def wrapper(*args, **kwargs): - partId = 'None' - try: - this, path, getParams, postParams = args # @UnusedVariable - partId = postParams['disk'] + postParams['part'] - if this.locked.get(partId, False): - this.locked[partId] = True - fnc(*args, **kwargs) - else: - return 'partition locked' - except Exception as e: - this.locked[partId] = False - return 'error {}'.format(e) - finally: - if sync is True: - this.locked[partId] = False - logger.debug('Lock status: {} {}'.format(fnc, this.locked)) - return wrapper - return outer - - def _getMacAddr(ifname): - ''' + """ Returns the mac address of an interface Mac is returned as unicode utf-8 encoded - ''' + """ if isinstance(ifname, list): return dict([(name, _getMacAddr(name)) for name in ifname]) if isinstance(ifname, six.text_type): @@ -88,10 +59,10 @@ def _getMacAddr(ifname): def _getIpAddr(ifname): - ''' + """ Returns the ip address of an interface Ip is returned as unicode utf-8 encoded - ''' + """ if isinstance(ifname, list): return dict([(name, _getIpAddr(name)) for name in ifname]) if isinstance(ifname, six.text_type): @@ -108,9 +79,9 @@ def _getIpAddr(ifname): def _getInterfaces(): - ''' + """ Returns a list of interfaces names coded in utf-8 - ''' + """ max_possible = 128 # arbitrary. raise if needed. space = max_possible * 16 if platform.architecture()[0] == '32bit': @@ -134,32 +105,32 @@ def _getInterfaces(): def _getIpAndMac(ifname): ip, mac = _getIpAddr(ifname), _getMacAddr(ifname) - return (ip, mac) + return ip, mac -def _exec_ogcommand(self, ogcmd): - ''' +def _exec_ogcommand(ogcmd): + """ Loads OpenGnsys environment variables, executes the command and returns the result - ''' - ret = subprocess.check_output('source /opt/opengnsys/etc/preinit/loadenviron.sh >/dev/null; {}'.format(ogcmd), shell=True) + """ + ret = subprocess.check_output(ogcmd, shell=True) return ret def getComputerName(): - ''' + """ Returns computer name, with no domain - ''' + """ return socket.gethostname().split('.')[0] def getNetworkInfo(): - ''' + """ Obtains a list of network interfaces - @return: A "generator" of elements, that are dict-as-object, with this elements: + :return: A "generator" of elements, that are dict-as-object, with this elements: name: Name of the interface mac: mac of the interface ip: ip of the interface - ''' + """ for ifname in _getInterfaces(): ip, mac = _getIpAndMac(ifname) if mac != '00:00:00:00:00:00': # Skips local interfaces @@ -170,56 +141,44 @@ def getDomainName(): return '' -def getOgliveVersion(): - lv = platform.linux_distribution() - return lv[0] + ', ' + lv[1] +def get_oglive_version(): + """ + Returns ogLive Kernel version and architecture + :return: kernel version + """ + kv = platform.os.uname() + return kv[2] + ', ' + kv[4] def reboot(): - ''' + """ Simple reboot using OpenGnsys script - ''' + """ # Workaround for dummy thread if six.PY3 is False: import threading threading._DummyThread._Thread__stop = lambda x: 42 - _exec_ogcommand('/opt/opengnsys/scripts/reboot', shell=True) + _exec_ogcommand('/opt/opengnsys/scripts/reboot') def poweroff(): - ''' + """ Simple poweroff using OpenGnsys script - ''' + """ # Workaround for dummy thread if six.PY3 is False: import threading threading._DummyThread._Thread__stop = lambda x: 42 - _exec_ogcommand('/opt/opengnsys/scripts/poweroff', shell=True) + _exec_ogcommand('/opt/opengnsys/scripts/poweroff') -def logoff(): - pass - - -def renameComputer(newName): - pass - - -def joinDomain(domain, ou, account, password, executeInOneStep=False): - pass - - -def changeUserPassword(user, oldPassword, newPassword): - pass - - -def diskconfig(): - ''' - Returns disk configuration. - Warning: this operation may take some time. - ''' +def get_disk_config(): + """ + Returns disk configuration + Warning: this operation may take some time + """ try: _exec_ogcommand('/opt/opengnsys/interfaceAdm/getConfiguration') # Returns content of configuration file. diff --git a/src/opengnsys/operations.py b/src/opengnsys/operations.py index 9454f51..8c32ac4 100644 --- a/src/opengnsys/operations.py +++ b/src/opengnsys/operations.py @@ -27,7 +27,7 @@ # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ -@author: Adolfo Gómez, dkmaster at dkmon dot com +@author: Ramón M. Gómez, ramongomez at us dot es """ # pylint: disable=unused-wildcard-import,wildcard-import @@ -48,8 +48,8 @@ else: else: if os.path.exists('/scripts/oginit'): from .oglive.operations import * # @UnusedWildImport - osType = 'ogLive' - os_version = getOgliveVersion().replace(',','') + os_type = 'ogLive' + os_version = get_oglive_version() else: from .linux.operations import * # @UnusedWildImport os_type = 'Linux'