Sindbad~EG File Manager

Current Path : /proc/thread-self/root/opt/alt/python37/lib/python3.7/site-packages/clcommon/cpapi/plugins/
Upload File :
Current File : //proc/thread-self/root/opt/alt/python37/lib/python3.7/site-packages/clcommon/cpapi/plugins/ispmanager.py

# -*- coding: utf-8 -*-

from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
import re
import os
import grp

from typing import Dict  # NOQA

try:
    import MySQLdb
except ImportError:
    MySQLdb = None
from clcommon.cpapi.cpapiexceptions import NoPackage
from clcommon.cpapi.cpapiexceptions import NotSupported, NoDBAccessData
from clcommon.cpapi.GeneralPanel import GeneralPanelPluginV1
from clcommon.const import Feature

__cpname__ = 'ISPManager'


def _is_5_version():
    return os.path.isfile('/usr/local/mgr5/sbin/mgrctl')


# WARN: Probably will be deprecated for our "official" plugins.
# See pluginlib.detect_panel_fast()
def detect():
    return os.path.isfile('/usr/local/ispmgr/bin/ispmgr') or _is_5_version()


ISP_DB_CONF = '/usr/local/ispmgr/etc/ispmgr.conf'
ISP5_DB_CONF = '/usr/local/mgr5/etc/ispmgr.conf.d/db.conf'

SECTION_PATTERN = r'(\S+) "([^"]+)" {([^}]+)}'
KEYWORDS_PATTERN = r'(\S+)\s+(\S+)'


def conf_pars(sectype, secname=None, seckeys=None, path=ISP_DB_CONF):
    """
    /usr/local/ispmgr/etc/ispmgr.conf parser
    :param sectype: Type sector for example: Service or DbServer or Account
    :param secname: Name sector. May be different
    :param seckeys: Name key for retrieving and filtering
    :param path: path to config file default /usr/local/ispmgr/etc/ispmgr.conf
    :return: list
    """
    seckeys_filter = dict()
    seckeys_extracted = None
    if seckeys:
        seckeys_extracted = list()
        for key_val in seckeys:
            key_val_splited = key_val.split()
            if len(key_val_splited) == 2:
                seckeys_filter.update(dict([key_val_splited]))
                seckeys_extracted.append(key_val_splited[0])
            elif len(key_val_splited) == 1:
                seckeys_extracted.append(key_val_splited[0])
    conf_stream = open(path)
    result_list = list()
    for stype, sname, sbody in re.findall(SECTION_PATTERN, conf_stream.read()):
        blst = re.findall(KEYWORDS_PATTERN, sbody)
        if stype == sectype and secname in (None, secname):
            result = dict([(k, v)
                           for k, v in blst
                           if seckeys_extracted is None or k in seckeys_extracted])

            if set(seckeys_filter.items()).issubset(set(result.items())):
                result_list.append(result)

    conf_stream.close()
    return result_list


def _db_access_5():
    try:
        with open(ISP5_DB_CONF) as db_conf:
            cnf = dict(re.findall(KEYWORDS_PATTERN, db_conf.read()))
            return {'pass': cnf['DBPassword'], 'login': cnf['DBUser'], 'host': cnf['DBHost'], 'db': 'mysql'}
    except IOError:
        raise NoDBAccessData('Can not open config file %s' % (KEYWORDS_PATTERN,))
    except IndexError:
        raise NoDBAccessData('Can not find database access data in config file %s' % (KEYWORDS_PATTERN,))


def db_access(_conf_path=ISP_DB_CONF):
    if _is_5_version():
        # ISP Manager 5
        return _db_access_5()
    # ISP Manager 4
    access = dict()
    access_list = conf_pars(sectype='DbServer', seckeys=('Hostname', 'Password', 'Type mysql', 'User'), path=_conf_path)
    for access_from_conf in access_list:
        try:
            access['pass'] = access_from_conf['Password']
            access['login'] = access_from_conf['User']
            access['host'] = access_from_conf['Hostname']
            access['db'] = 'mysql'
            return access
        except KeyError:
            pass
    raise NoDBAccessData('Can not find database access data for localhost in config file %s' % (_conf_path,))


def _dbname_dblogin_pairs(access):
    if not MySQLdb:
        raise NoPackage('Can not connect to database; MySQL-client libraries package not installed.')
    dbhost = access.get('host', 'localhost')
    dblogin = access['login']
    dbpass = access['pass']
    db = MySQLdb.connect(host=dbhost, user=dblogin, passwd=dbpass, db='mysql')
    cursor = db.cursor()
    sql = r"SELECT db.Db, db.User FROM db  GROUP BY db.User, db.Db"
    cursor.execute(sql)
    data = cursor.fetchall()
    db.close()
    return data


def cpusers():
    raise NotSupported({
        'message': '%(action)s is not currently supported.',
        'context': {'action': 'Getting all users registered in the Control Panel'}
    })


def _dbname_cplogin_pairs_iter(cplogin_lst=None, _conf_path=ISP_DB_CONF):
    """
    Extract (database name <=> control panel login) pairs from ISPmanager config file
    :param cplogin_lst:
    :param _conf_path:
    :return:
    """
    conf_stream = open(_conf_path)
    grpid_login_dict = dict([(grp_tuple[2], grp_tuple[0]) for grp_tuple in grp.getgrall()])
    for line_numb, line in enumerate(conf_stream):
        if line.startswith('DbAssign '):
            line_splited = line.split()
            if len(line_splited) >= 3:
                dbname, user_uid = line_splited[2:]
                try:
                    cplogin = grpid_login_dict.get(int(user_uid))
                    if cplogin is None:
                        print('WARNING: can not find group name with id %s; line %d in file %s'
                              % (user_uid, line_numb, _conf_path))
                except ValueError:  # if can not convert user_uid to int
                    print('WARNING: can not pars line %d in file %s' % (line_numb, _conf_path))
                    cplogin = None
                if cplogin and (cplogin_lst is not None or cplogin in cplogin_lst):
                    yield dbname, cplogin
    conf_stream.close()


def get_user_login_url(domain):
    return 'https://{domain}:1500'.format(domain=domain)


class PanelPlugin(GeneralPanelPluginV1):
    def __init__(self):
        super(PanelPlugin, self).__init__()

    def getCPName(self):
        """
        Return panel name
        :return:
        """
        return __cpname__

    def get_cp_description(self):
        """
        Retrieve panel name and it's version
        :return: dict: { 'name': 'panel_name', 'version': 'panel_version', 'additional_info': 'add_info'}
            or None if can't get info
        """
        ####################################################################
        # ISP Manager v4 and v5 (master and node) check
        # ISPmanager v5 check and detect its type - master/node
        # ISP Manager support recommendation:
        # Node has package ispmanager-node-common-5.56.0-3.el6.x86_64
        # Master has packages ispmanager-business-common-5.56.0-3.el6.x86_64 and
        #  ispmanager-business-5.56.0-3.el6.x86_64, may have ispmanager-node-common-5.56.0-3.el6.x86_64
        try:
            import subprocess
            cp_node_type = None
            if os.path.isfile('/usr/local/mgr5/sbin/mgrctl'):
                # ISP Manager v5
                # detect full ISP5 version as package version - ISP support recommendation
                p = subprocess.Popen(['/bin/rpm', '-q', '--queryformat', '[%{VERSION}]', 'ispmanager-business-common'],
                                     stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
                cp_version, _ = p.communicate()
                if p.returncode != 0 or not cp_version:
                    # detect full ISP5 version as package version - ISP support recommendation
                    p = subprocess.Popen(['/bin/rpm', '-q', '--queryformat', '[%{VERSION}]', 'ispmanager-node-common'],
                                         stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
                    cp_version, _ = p.communicate()
                    if p.returncode != 0 or not cp_version:
                        p = subprocess.Popen(
                            ['/bin/rpm', '-q', '--queryformat', '[%{VERSION}]', 'ispmanager-lite-common'],
                            stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
                        cp_version, _ = p.communicate()
                        if p.returncode != 0 or not cp_version:
                            # should never happen :)
                            raise Exception('Failed to detect version of ISP manager')
                        else:
                            cp_node_type = "Lite"
                    else:
                        # no such package found -- this is ISP5 node
                        cp_node_type = "Node"
                else:
                    # Output absent - package found -- this is ISP5 master
                    cp_node_type = "Master"
            else:
                # ISPmanager v4 check
                p = subprocess.Popen(['/usr/local/ispmgr/bin/ispmgr', '-v'], stdout=subprocess.PIPE,
                                     stderr=subprocess.PIPE, text=True)
                out, _ = p.communicate()
                cp_version = out.replace('\n', '').split()[1]
            return {'name': __cpname__, 'version': cp_version, 'additional_info': cp_node_type}
        except:
            return None

    def db_access(self):
        """
        Getting root access to mysql database.
        For example {'login': 'root', 'db': 'mysql', 'host': 'localhost', 'pass': '9pJUv38sAqqW'}

        :return: root access to mysql database
        :rtype: dict
        :raises: NoDBAccessData
        """
        return db_access()

    @staticmethod
    def useraliases(cpuser, domain):
        """
        Return aliases from user domain
        :param str|unicode cpuser: user login
        :param str|unicode domain:
        :return list of aliases
        """
        return []

    def cpusers(self):
        """
        Generates a list of cpusers registered in the control panel

        :return: list of cpusers registered in the control panel
        :rtype: tuple
        """
        return cpusers()

    def get_user_login_url(self, domain):
        """
        Get login url for current panel;
        :type domain: str
        :rtype: str
        """
        return get_user_login_url(domain)

    def get_supported_cl_features(self) -> Dict[str, bool]:
        supported_features = super(PanelPlugin, self).get_supported_cl_features()
        return {
            **supported_features,
            Feature.PHP_SELECTOR: True,
            Feature.RUBY_SELECTOR: False,
            Feature.PYTHON_SELECTOR: False,
            Feature.NODEJS_SELECTOR: False,
            Feature.LSAPI: True,
            Feature.GOVERNOR: True,
            Feature.CAGEFS: True,
            Feature.RESELLER_LIMITS: False,
            Feature.WPOS: False,
        }

Sindbad File Manager Version 1.0, Coded By Sindbad EG ~ The Terrorists