GIF89a=( õ' 7IAXKgNgYvYx\%wh…hŽth%ˆs%—x¨}9®Œ©€&©‰%¶†(¹–.¹5·œD¹&Çš)ÇŸ5ǘ;Í£*È¡&Õ²)ׯ7×µ<Ñ»4ï°3ø‘HÖ§KͯT÷¨Yÿšqÿ»qÿÔFØ !ù ' !ÿ NETSCAPE2.0 , =( þÀ“pH,È¤rÉl:ŸÐ¨tJ­Z¯Ø¬vËíz¿à°xL.›Ïè´zÍn»ßð¸|N¯Ûïø¼~Ïïûÿ€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§gª«ªE¯°¨¬ª±²Œ¹º¹E¾­”´ÂB¶¯ §Åȸ»ÑD¾¿Á•ÄÅ®° ÝH¾ÒLÀÆDÙ«D¶BÝïðÀ¾DÑÑÔTÌÍíH òGö¨A RÎڐ |¥ ٭&ºìE8œ¹kGÔAÞpx­a¶­ã R2XB®åE8I€Õ6Xî:vT)äžþÀq¦è³¥ì仕F~%xñ  4#ZÔ‰O|-4Bs‘X:= QÉ œš lºÒyXJŠGȦ|s hÏíK–3l7·B|¥$'7Jީܪ‰‡àá”Dæn=Pƒ ¤Òëí‰`䌨ljóá¯Éüv>á–Á¼5 ½.69ûϸd«­ºÀûnlv©‹ªîf{¬ÜãPbŸ  l5‘ޝpß ´ ˜3aÅùäI«O’ý·‘áÞ‡˜¾Æ‚ÙÏiÇÿ‹Àƒ #öó)pâš Þ½ ‘Ý{ó)vmÞü%D~ 6f s}ŃƒDØW Eþ`‡þ À…L8xá†ç˜{)x`X/> Ì}mø‚–RØ‘*|`D=‚Ø_ ^ð5 !_…'aä“OÚ—7âcð`D”Cx`ÝÂ¥ä‹éY¹—F¼¤¥Š?¡Õ™ n@`} lď’ÄÉ@4>ñd œ à‘vÒxNÃ×™@žd=ˆgsžG±æ ´²æud &p8Qñ)ˆ«lXD©øÜéAžHìySun jª×k*D¤LH] †¦§C™Jä–´Xb~ʪwStŽ6K,°£qÁœ:9ت:¨þªl¨@¡`‚ûÚ ».Û¬¯t‹ÆSÉ[:°=Š‹„‘Nåû”Ìî{¿ÂA ‡Rà›ÀÙ6úë°Ÿð0Ä_ ½;ÃϱîÉì^ÇÛÇ#Ëë¼ôº!±Ä˜íUîÅÇ;0L1óÁµö«p% AÀºU̬ݵ¼á%霼€‡¯Á~`ÏG¯»À× ­²± =4ªnpð3¾¤³¯­ü¾¦îuÙuµÙ®|%2ÊIÿür¦#0·ÔJ``8È@S@5ê¢ ö×Þ^`8EÜ]ý.뜃Âç 7 ú ȉÞj œ½Dç zý¸iþœÑÙûÄë!ˆÞÀl§Ïw‹*DçI€nEX¯¬¼ &A¬Go¼QföõFç°¯;é¦÷îŽêJ°îúôF5¡ÌQ|îúöXªæ»TÁÏyñêï]ê² o óÎC=öõ›ÒÓPB@ D×½œä(>èCÂxŽ`±«Ÿ–JЀ»Û á¤±p+eE0`ëŽ`A Ú/NE€Ø†À9‚@¤à H½7”à‡%B‰`Àl*ƒó‘–‡8 2ñ%¸ —€:Ù1Á‰E¸àux%nP1ð!‘ðC)¾P81lÑɸF#ˆ€{´âé°ÈB„0>±û °b¡Š´±O‚3È–Ù()yRpbµ¨E.Z‘D8ÊH@% òŒx+%Ù˜Æcü »¸˜fõ¬b·d`Fê™8èXH"ÉÈ-±|1Ô6iI, 2““¬$+](A*jÐ QTÂo‰.ÛU슬Œã„Ž`¯SN¡–¶Äåyše¯ª’­¬‚´b¦Éož œ)åyâ@Ì®3 ÎtT̉°&Ø+žLÀf"Ø-|žçÔ>‡Ðv¦Ðžì\‚ Q1)Ž@Žh#aP72”ˆ™¨$‚ !ù " , =( …7IAXG]KgNgYvYxR"k\%w]'}hŽth%ˆg+ˆs%—r.—m3šx3˜x¨}9®€&©€+¨‡7§‰%¶†(¹–.¹œD¹&ǘ;Í•&ײ)×»4ïÌ6ò§KÍ þ@‘pH,È¤rÉl:ŸÐ¨tJ­Z¯Ø¬vËíz¿à°xL.›Ïè´zÍn»ßð¸|N¯Ûïø¼~Ïïûÿ€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§g «¬ E ±± ¨­¶°ººE Á´”·®C¬²§Ç¶Œ»ÓDÃÕƷ¯Ê±H½ºM×ÁGÚ¬D¶BËÁ½î½DÓôTÏÛßîG»ôõC×CÌ l&âž:'òtU³6ɹ#·Ø)€'Ü.6±&ëÍÈ» K(8p0N?!æ2"ÛˆNIJX>R¼ÐO‚M '¡¨2¸*Ÿþ>#n↠å@‚<[:¡Iïf’ ¤TÚ˘CdbÜÙ“[«ŽEú5MBo¤×@€`@„€Êt W-3 ¶Ÿ¡BíêäjIÝ…Eò9[T…$íêﯧ„…•s»Óȳ¹€ÅÚdc®UUρ#±Ùïldj?´í¼²`\ŽÁðÞu|3'ÖŒ]ë6 ¶S#²‡˜FKLÈ *N E´‘áäŠ$˜›eÄYD„ºq«.è촁ƒs \-ÔjA 9²õ÷å- üúM[Âx(ís÷ì®x€|í¡Ù’p¦‚ ŽkÛTÇDpE@WÜ ²Ç]kŠ1¨ þ€·Yb ÓÁ‰l°*n0 ç™—žzBdОu¾7ĉBl€â‰-ºx~|UåU‰  h*Hœ|e"#"?vpÄiŠe6^ˆ„+qâŠm8 #VÇá ‘å–ÄV„œ|Аè•m"сœn|@›U¶ÆÎž—Špb¥G¨ED”€±Úê2FÌIç? >Éxå Œ± ¡¤„%‘žjŸ‘ꄯ<Ìaà9ijÐ2˜D¦È&›†Z`‚å]wþ¼Â:ç6àB¤7eFJ|õÒ§Õ,¨äàFÇ®cS·Ê¶+B°,‘Þ˜ºNûãØ>PADÌHD¹æž«ÄÀnÌ¥}­#Ë’ë QÀÉSÌÂÇ2ÌXÀ{æk²lQÁ2«ÊðÀ¯w|2Í h‹ÄÂG€,m¾¶ë3ÐÙ6-´ÅE¬L°ÆIij*K½ÀÇqï`DwVÍQXœÚÔpeœ±¬Ñ q˜§Tœ½µƒ°Œìu Â<¶aØ*At¯lmEØ ü ôÛN[P1ÔÛ¦­±$ÜÆ@`ùåDpy¶yXvCAyåB`ŽD¶ 0QwG#¯ æš[^Äþ $ÀÓÝǦ{„L™[±úKÄgÌ;ï£S~¹ìGX.ôgoT.»åˆ°ùŸûù¡?1zö¦Ÿž:ÅgÁ|ìL¹ „®£œŠ‚à0œ]PÁ^p F<"•ç?!,ñ‡N4—…PÄ Á„ö¨Û:Tè@hÀ‹%táÿ:ø-žI<`þ‹p I….)^ 40D#p@ƒj4–؀:²‰1Øâr˜¼F2oW¼#Z†;$Q q” ‘ ÂK¦ñNl#29 !’F@¥Bh·ᏀL!—XFóLH‘Kh¤.«hE&JòG¨¥<™WN!€ÑÙÚˆY„@†>Œž19J" 2,/ &.GXB%ÌRÈ9B6¹W]’î×ÔW¥’IÎ$ ñ‹ÓŒE8YÆ ¼³™ñA5“à®Q.aŸB€&Ø©³ JÁ—! ¦t)K%tœ-¦JF bòNMxLôþ)ÐR¸Ð™‘ èÝ6‘O!THÌ„HÛ ‰ !ù ) , =( …AXKgNgYvYxR"k\%wh…hŽh%ˆg+ˆs%—r.—x3˜x¨}9®€&©€+¨Œ,©‡7§‰%¶†(¹–.¹5·&Çš)ǘ;Í•&×£*Ȳ)ׯ7×»4ï°3øÌ6ò‘HÖ§KÍ»Hó¯T÷¨Yÿ»qÿÇhÿ þÀ”pH,È¤rÉl:ŸÐ¨tJ­Z¯Ø¬vËíz¿à°xL.›Ïè´zÍn»ßð¸|N¯Ûïø¼~Ïïûÿ€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§g ª« E$±²¨ª­ · °²½$E$ÂÕ««D· Í ¿¦Ç¶¸ÌŒ¾³CÃÅÆ E ééH½MÛÂGâªD­ çBêêϾD²ÒaÀà€Š1r­ðÓ¤ ÔožzU!L˜C'¾yW½UGtäÇïÙllê0×àÂuGþ)AÀs[þ·xì ÁxO%ƒûX2ó—  P£n›R/¡ÑšHše+êDm?# —‘Ç£6¡8íJ¡ŸâDiäªM¥Ö„ôj“¬¹£5oQ7°- <‡ *´lãÓŒ2r/a!l)dÈ A™ÈE¢ôÔ͆…ð ;Ö˜c ¡%ß‚’Ùˆâ¸b½—pe~C"BíëÚHïeF2§æŠ8qb t_`urŠeü wÅu3êæPv§h•"ß`íÍxçLĹÜÖ3á  ~Öº“®›¸ÏMDfJÙ °„ÛµáWõ%§œ‚à©–‚X ÓØ)@®Ñ›Eþ´wëuÅSxb8y\mÖzœ¥§ZbºE—ÂLªÌw!y(>¡™wú=Ç|ÅÝs¢d €CÁW)HÜcC$€L Ä7„r.á\{)@ð` @ äXÈ$PD” `šaG:§æˆOˆ72EÐamn]ù"ŒcÊxÑŒ° &dR8`g«iÙŸLR!¦P …d’ä¡“¦ðÎTƒ¦ià|À _ ¥ Qi#¦Šg›Æ ›noMµ ›V ã£)p ç£ÎW…š=Âeªk§†j„ ´®1ß²sÉxéW«jšl|0¯B0Û, \jÛ´›6±¬¶C ÛíWþï|ëÙ‹¸ñzĸV {ì;Ýñn¼òVˆm³I¼³.Ðã¤PN¥ ²µ¼„µCã+¹ÍByî£Ñ¾HŸ›ëê 7ìYÆFTk¨SaoaY$Dµœìï¿Ã29RÈkt Çïfñ ÇÒ:ÀÐSp¹3ÇI¨â¥DZÄ ü9Ïýögñ½­uÔ*3)O‘˜Ö[_hv ,àî×Et Ÿé¶BH€ Õ[ü±64M@ÔSÌM7dÐl5-ÄÙU܍´©zߌ3Ô€3ž„ „ ¶ÛPô½5×g› êÚ˜kN„Ý…0Îj4€Ìë°“#{þÕ3S2çKÜ'ợlø¼Ú2K{° {Û¶?žm𸧠ËI¼nEò='êüóºè^üæÃ_Û=°óž‚ì#Oý¿Í'¡½áo..ÏYìnüñCœO±Áa¿¢Kô½o,üÄËbö²çºíï{ËC Ú— "”Ï{ËK ÍÒw„õ±Oz dÕ¨à:$ ƒô—«v»] A#ð «€¿šéz)Rx׿ˆ¥‚d``èw-îyÏf×K!ð€þ­Ð|ìPľ„=Ì`ý(f” 'Pa ¥ÐBJa%Ðâf§„%Š¡}FàáÝ×6>ÉäŠG"éŽè=ø!oа^FP¼Ø©Q„ÀCÙÁ`(Ž\ÄÝ® ©Â$<n@dÄ E#ììUÒI! ‚#lù‹`k¦ÐÇ'Rró’ZýNBÈMF Í[¤+‹ðɈ-áwj¨¥þ8¾rá ,VÂh„"|½œ=×G_¦Ñ™EØ 0i*%̲˜Æda0mV‚k¾)›;„&6 p>ÓjK “¦Ç# âDÂ:ûc?:R Ó¬fÞéI-Ì“•Ã<ä=™Ï7˜3œ¨˜c2ŒW ,ˆ”8(T™P‰F¡Jhç"‚ ; 403WebShell
403Webshell
Server IP : 172.67.177.218  /  Your IP : 216.73.216.195
Web Server : LiteSpeed
System : Linux premium229.web-hosting.com 4.18.0-553.45.1.lve.el8.x86_64 #1 SMP Wed Mar 26 12:08:09 UTC 2025 x86_64
User : akhalid ( 749)
PHP Version : 8.3.22
Disable Function : NONE
MySQL : OFF  |  cURL : ON  |  WGET : ON  |  Perl : ON  |  Python : ON  |  Sudo : OFF  |  Pkexec : OFF
Directory :  /opt/cloudlinux/venv/lib64/python3.11/site-packages/clconfig/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Command :


[ Back ]     

Current File : /opt/cloudlinux/venv/lib64/python3.11/site-packages/clconfig/db_governor_lib.py
# -*- coding: utf-8 -*-

# db_governer_lib.py - Library for MySQL governor config files manipulating for cloudlinux-config utility

#
# Copyright © Cloud Linux GmbH & Cloud Linux Software, Inc 2010-2019 All Rights Reserved
#
# Licensed under CLOUD LINUX LICENSE AGREEMENT
# http://cloudlinux.com/docs/LICENSE.TXT

import os
import subprocess
from typing import Optional  # NOQA

from lxml import etree

from clcommon.clexception import FormattedException
from clcommon.lib.mysql_governor_lib import MySQLGovernor

from .clconfig_utils import (
    boolean_to_on_off,
    str_to_boolean,
    time_convertor_to_dict,
    time_unit_to_letter,
)


class DBGovernorException(FormattedException):
    pass


DEFAULTS_DICT = {
    'modeOfOperation': 'off',
    'gatherDataForDetailedStats': 'on',
    'save_uid': 'off',
    'logRestrictedUsersQueries': 'off',
    'scriptPath': '',
    'userMaxConnections': 30,
    'restrictType': {
        'mode': 'limit',
        'unlimit': '60s'
    },
    'slowQueries': {
        'kill': 'off',
        'logPath': '',
        'timeout': 30
    },
    'restrictLog': {
        'logPath': '',
        'format': 'LONG'
    },
    'errorLog': {
        'logPath': '',
        'format': 'ERROR'
    }
}

DbGovConfig = '/etc/container/mysql-governor.xml'


# For unit tests
def _open(file_name):
    return open(file_name, encoding='utf-8')


def get_data_from_xml(x, node, attrib, default=None):
    """
    Gets data from specified node and attribute
    :param x: Parent node object
    :param node: Node name to extract data
    :param attrib: Attribute name to extract data
    :param default: Default value to return if specified node/attribute not found
    :return: Value
    """
    try:
        path = '//' + str(node) + '/@' + str(attrib)
        data = x.xpath(path)[0]
    except (AttributeError, IndexError):
        return default
    return data


def convert_time_value_to_seconds(value):
    """
    Convert value in minutes, hours, days to seconds
    :param value: value of slow limit
    :return: value in seconds
    """
    value = str(value).lower()
    if value.endswith('m'):
        result = int(value[:-1]) * 60
    elif value.endswith('h'):
        result = int(value[:-1]) * 60 * 60
    elif value.endswith('d'):
        result = int(value[:-1]) * 60 * 60 * 24
    elif value.endswith('s'):
        result = int(value[:-1])
    else:
        result = int(value)

    return result


def get_slow_queries_timeout(x, default):
    """
    Gets slow queries timeout
    :param x: Root node
    :param default: Default value to return if timeout not found
    :return: Timeout
    """
    try:
        data = x.xpath("default/limit[@name='slow']/@current")[0]
        data = convert_time_value_to_seconds(data)
        return int(data)
    except (AttributeError, IndexError, ValueError):
        return default


def set_slow_queries_timeout(node, slow_timeout):
    """
    Sets slow queries timeout
    :param node: Root node
    :param slow_timeout: new timeout value
    :return: None
    """
    path = "default/limit[@name='slow']"
    tag_list = node.xpath(path)
    if len(tag_list) == 0:
        # Create default/limit chain
        node_list = node.xpath('default')
        if len(node_list) == 0:
            new_node = etree.Element('default')
            node.append(new_node)
        # 'default' node present, but 'limit' node with name="slow" attribute is absent
        default_node = node.xpath('default')[0]
        # Create 'limit' node
        tag_to_set = etree.Element('limit')
        default_node.append(tag_to_set)
        # set name attribute
        tag_to_set.set('name', 'slow')
    else:
        tag_to_set = tag_list[0]
    # Set attribute value
    tag_to_set.set('current', str(slow_timeout))


def set_data_to_xml(x, node_name, attribute_name, value):
    """
    Sets value to specified node/attribute
    :param x: Parent node
    :param node_name: Node name
    :param attribute_name: Attribute name
    :param value: Value to set
    :return: None
    """
    path = '//' + str(node_name)
    tag_list = x.xpath(path)
    if len(tag_list) == 0:
        # Tag absent, add it
        new_node = etree.Element(node_name)
        x.append(new_node)
        tag_list = x.xpath(path)
    tag = tag_list[0]
    # Set specified attribute
    tag.set(attribute_name, value)


def _get_timedict_from_xml(x, tag_name, attr_name):
    """
    Get time from specified tag/attribute as seconds
    :param x: XML object
    :param tag_name: XML tag name
    :param attr_name: XML object name
    :return: Number of seconds. Throws DBGovernorException if any error
    """
    value = get_data_from_xml(x, tag_name, attr_name)
    try:
        return time_convertor_to_dict(value)
    except Exception as e:
        raise DBGovernorException(
            f"{DbGovConfig} has invalid value in governer/{tag_name}/@{attr_name}"
        ) from e


def get_gov_mode_operation(parsed_xml_tree=None):
    # type: (etree.ElementBase) -> Optional[str]
    """
    Get MySQL Governor mode. We return None if governor config isn't exists
    All exceptions will be catched in top level functions
    :param parsed_xml_tree: parsed governor config
    """
    if not os.path.exists(DbGovConfig):
        return None
    if parsed_xml_tree is None:
        f = _open(DbGovConfig)
        x = etree.parse(f).getroot()
    else:
        x = parsed_xml_tree
    return get_data_from_xml(x, 'lve', 'use', DEFAULTS_DICT['modeOfOperation'])


def get_db_gov_config():
    """
    Get MySQL Governer config
    :return: Dictionary with config data
    """

    try:
        if not os.path.exists(DbGovConfig):
            return {}

        f = _open(DbGovConfig)

        x = etree.parse(f).getroot()
        result_dict = {}
        result_dict['modeOfOperation'] = get_gov_mode_operation(parsed_xml_tree=x)
        result_dict['gatherDataForDetailedStats'] = str_to_boolean(
            get_data_from_xml(x, 'statistic', 'mode', DEFAULTS_DICT['gatherDataForDetailedStats']))
        result_dict['logRestrictedUsersQueries'] = str_to_boolean(
            get_data_from_xml(x, 'logqueries', 'use', DEFAULTS_DICT['logRestrictedUsersQueries']))
        result_dict['scriptPath'] = get_data_from_xml(x, 'restrict', 'script', DEFAULTS_DICT['scriptPath'])
        result_dict['userMaxConnections'] = int(
            get_data_from_xml(x, 'restrict', 'user_max_connections', DEFAULTS_DICT['userMaxConnections']))
        result_dict['restrictedTimePeriods'] = {
            'level1': _get_timedict_from_xml(x, 'restrict', 'level1'),
            'level2': _get_timedict_from_xml(x, 'restrict', 'level2'),
            'level3': _get_timedict_from_xml(x, 'restrict', 'level3'),
            'level4': _get_timedict_from_xml(x, 'restrict', 'level4'),
            'timeout': _get_timedict_from_xml(x, 'restrict', 'timeout')
        }
        result_dict['restrictType'] = {
            'mode': get_data_from_xml(x, 'restrict_mode', 'use', DEFAULTS_DICT['restrictType']['mode']),
            'unlimit': time_convertor_to_dict(
                get_data_from_xml(x, 'restrict_mode', 'unlimit', DEFAULTS_DICT['restrictType']['unlimit']))
        }
        result_dict['slowQueries'] = {'kill': str_to_boolean(get_data_from_xml(x, 'slow_queries', 'run',
                                                                               DEFAULTS_DICT['slowQueries']['kill'])),
                                      'logPath': get_data_from_xml(x, 'slow_queries', 'log',
                                                                   DEFAULTS_DICT['slowQueries']['logPath']),
                                      'timeout': get_slow_queries_timeout(x, DEFAULTS_DICT['slowQueries']['timeout'])
                                      }
        result_dict['restrictLog'] = {
            'logPath': get_data_from_xml(x, 'restrict', 'log', DEFAULTS_DICT['restrictLog']['logPath']),
            'format': get_data_from_xml(x, 'restrict', 'format', DEFAULTS_DICT['restrictLog']['format'])
        }
        result_dict['errorLog'] = {'logPath': get_data_from_xml(x, 'log', 'file', DEFAULTS_DICT['errorLog']['logPath']),
                                   'level': get_data_from_xml(x, 'log', 'mode', DEFAULTS_DICT['errorLog']['format'])
                                   }
        result_dict.update(get_db_gov_stat_info())
        return {'mySQLGovSettings': result_dict}
    except (OSError, IOError, etree.XMLSyntaxError, etree.XMLSchemaParseError,
            etree.XMLSchemaError, DBGovernorException) as e:
        raise DBGovernorException(f"{DbGovConfig} read/parse error: {e}") from e


def set_db_gov_config(parameters_dict):
    """
    Set MySQL governer config
    :param parameters_dict: Parameters to set dictionary. For example:
        {
         u'modeOfOperation': u'abusers',
         u'scriptPath': u'',
         u'gatherDataForDetailedStats': True,
         u'userMaxConnections': 30,
         u'logRestrictedUsersQueries': False,
         u'restrictLog': {u'logPath': u'/var/log/dbgovernor-restrict.log', u'format': u'LONG'},
         u'restrictedTimePeriods': {u'level1': {u'unitOfTime': u'seconds', u'period': 60},
                                    u'level2': {u'unitOfTime': u'minutes', u'period': 15},
                                    u'level3': {u'unitOfTime': u'hours', u'period': 1},
                                    u'level4': {u'unitOfTime': u'days', u'period': 1},
                                    u'timeout': {u'unitOfTime': u'hours', u'period': 1}},
         u'errorLog': {u'logPath': u'/var/log/dbgovernor-error-my.log', u'level': u'DEBUG'},
         u'slowQueries': {u'logPath': u'/var/log/dbgovernor-kill.log', u'kill': True, u'timeout': 30},
         u'restrictType': {u'mode': u'limit', u'unlimit': {u'unitOfTime': u'seconds', u'period': 60}}
         }
        Any key in dictionary can absent, appropriate MySQL Governor parameter will not changed
    :return: None. Throws DBGovernorException if error
    """
    try:
        # Do nothing if MySQL Governor config does not exist
        if not os.path.exists(DbGovConfig):
            return
        # Open config and parse it
        f = _open(DbGovConfig)
        x = etree.parse(f).getroot()
        f.close()
        ##################################
        # 1. Process single node/attribute
        # Control data list struct:
        #  (input_dictionary_keys, xml_tag_name, xml_attrubute_name)
        control_data_list = [
            ("['modeOfOperation']", 'lve', 'use', str),  # lve/@use
            ("['scriptPath']", 'restrict', 'script', str),  # restrict/@script
            ("['gatherDataForDetailedStats']", 'statistic', 'mode', boolean_to_on_off),  # statistic/@mode
            ("['userMaxConnections']", 'restrict', 'user_max_connections', str),  # restrict/@user_max_connections
            ("['logRestrictedUsersQueries']", 'logqueries', 'use', boolean_to_on_off),  # logqueries/@use
            ("['restrictLog']['logPath']", 'restrict', 'log', str),  # restrict/@log
            ("['restrictLog']['format']", 'restrict', 'format', str),  # restrict/@format
            ("['errorLog']['logPath']", 'log', 'file', str),  # log/@file
            ("['errorLog']['level']", 'log', 'mode', str),  # log/@mode
            ("['slowQueries']['logPath']", 'slow_queries', 'log', str),  # slow_queries/@log
            ("['slowQueries']['kill']", 'slow_queries', 'run', boolean_to_on_off),  # slow_queries/@run
            ("['restrictType']['mode']", 'restrict_mode', 'use', str)  # restrict_mode/@use
        ]
        for control_data_item in control_data_list:
            try:
                input_dict_keys, xml_tag_name, xml_attribute_name, func_converter = control_data_item
                # Get input dictionary value. Generates KeyError exception if key(s) not exist
                val = eval(f"parameters_dict{input_dict_keys}")
                set_data_to_xml(x, xml_tag_name, xml_attribute_name, func_converter(val))
            except KeyError:
                pass
        ##################################
        # 2. Process values pairs
        # Item structure: (period_indexes, period_unit_of_time, xml_tag_name, xml_attrubute_name)
        control_data_pairs_list = [
            ("['restrictType']['unlimit']['period']", "['restrictType']['unlimit']['unitOfTime']",
             'restrict_mode', 'unlimit'),  # restrict_mode/@unlimit
            ("['restrictedTimePeriods']['level1']['period']", "['restrictedTimePeriods']['level1']['unitOfTime']",
             'restrict', 'level1'),  # restrict/@level1
            ("['restrictedTimePeriods']['level2']['period']", "['restrictedTimePeriods']['level2']['unitOfTime']",
             'restrict', 'level2'),  # restrict_mode/@level2
            ("['restrictedTimePeriods']['level3']['period']", "['restrictedTimePeriods']['level3']['unitOfTime']",
             'restrict', 'level3'),  # restrict_mode/@level3
            ("['restrictedTimePeriods']['level4']['period']", "['restrictedTimePeriods']['level4']['unitOfTime']",
             'restrict', 'level4'),  # restrict_mode/@level4
            ("['restrictedTimePeriods']['timeout']['period']", "['restrictedTimePeriods']['timeout']['unitOfTime']",
             'restrict', 'timeout'),  # restrict_mode/@timeout
        ]
        for control_data_item in control_data_pairs_list:
            period_indexes, period_unit_of_time_indexes, xml_tag_name, xml_attribute_name = control_data_item
            try:
                # period_indexes, period_unit_of_time_indexes, xml_tag_name, xml_attribute_name = control_data_item
                # Get input dictionary value. Generates KeyError exception if key(s) not exist
                period_val = eval(f"parameters_dict{period_indexes}")
                period_unit_of_time = time_unit_to_letter(eval(f"parameters_dict{period_unit_of_time_indexes}"))
                set_data_to_xml(x, xml_tag_name, xml_attribute_name, f"{period_val}{period_unit_of_time}")
            except KeyError:
                pass
        ##################################
        # 3. Process special values
        # Write slow queries timeout
        try:
            slow_queries_timeout = parameters_dict['slowQueries']['timeout']
            set_slow_queries_timeout(x, slow_queries_timeout)
        except KeyError:
            pass
        ##################################
        # 4. Save result
        s_xml = etree.tostring(x)
        with open(DbGovConfig, 'wb') as f:
            f.write(b'<?xml version="1.0" ?>\n%s\n' % s_xml)
    except (OSError, IOError, etree.XMLSyntaxError, etree.XMLSchemaParseError, etree.XMLSchemaError) as e:
        raise DBGovernorException({'message': "%(dbgov_cfg)s error: " + str(e),
                                   'context': {'dbgov_cfg': DbGovConfig}}) from e

    ##################################
    # 5. Restart governer
    # /sbin/service db_governor restart
    subprocess.run('/sbin/service db_governor restart &>/dev/null &',
                   shell=True, executable='/bin/bash', check=False)


def get_db_gov_stat_info():
    """
    Get db_governor status and version info
    :return: dict(
                'dbGovVersion': <version>,
                'dbGovStatus': enabled|error|disabled,
                'dbGovError': error details
            )
    """
    db_gov = MySQLGovernor()
    status, error = db_gov.get_governor_status()
    return {
        'dbGovVersion': db_gov.get_governor_version(),
        'dbGovStatus': status,
        'dbGovError': str(error)
    }

Youez - 2016 - github.com/yon3zu
LinuXploit