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/lvestats/lib/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Command :


[ Back ]     

Current File : /opt/cloudlinux/venv/lib64/python3.11/site-packages/lvestats/lib/dbengine.py
# coding=utf-8
#
# 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 logging
import pathlib

import sqlalchemy.engine
from sqlalchemy import delete, func
from sqlalchemy.engine.reflection import Inspector
from sqlalchemy.engine.url import make_url
from sqlalchemy.ext.declarative.clsregistry import _ModuleMarker
from sqlalchemy.orm import RelationshipProperty, sessionmaker

from clcommon import mysql_lib
from clcommon.clexception import FormattedException
from lvestats.orm import Base, history
from lvestats.orm import LVE_STATS_2_TABLENAME_PREFIX
from lvestats.utils.dbmigrator import alembic_migrate

DEFAULT_DB_PATH = '/var/lve/lvestats2.db'
MYSQL, POSTGRESQL, SQLITE = 'mysql', 'postgresql', 'sqlite'
SUPPORTED_DATABASES = [MYSQL, POSTGRESQL, SQLITE]
DB_CLIENT_LIBRARY_MAP = {
    MYSQL: 'pymysql',
    POSTGRESQL: 'psycopg2',
}

__author__ = 'shaman'


def find_not_existing_tables_or_views(engine, names):
    """
    Checks if views exist.
    :param sqlalchemy.engine.base.Engine engine:
    :return:
    """
    inspector = Inspector.from_engine(engine)
    existing = set(inspector.get_view_names())
    not_existing = {LVE_STATS_2_TABLENAME_PREFIX + n for n in names} - existing
    return tuple(x.replace(LVE_STATS_2_TABLENAME_PREFIX, '') for x in tuple(not_existing))


def get_list_of_tables_without_views():
    """
    Used to call engine.create_all() without views that are described as Table()
    :return:
    """
    tables = dict(Base.metadata.tables).values()
    tables_for_disabled_features = []

    burstable_limits_feature_flag = '/opt/cloudlinux/flags/enabled-flags.d/burstable-limits.flag'
    if not pathlib.Path(burstable_limits_feature_flag).exists():
        tables_for_disabled_features.append(LVE_STATS_2_TABLENAME_PREFIX + 'bursting_events')

    return [t for t in tables if t.name not in tables_for_disabled_features]


class MakeDbException(FormattedException):
    pass


class DatabaseConfigError(FormattedException):
    pass


def cfg_get_uri(cfg, check_support=True):
    """
    Extract and validate database connection uri from config
    :param dict cfg:
    :param bool check_support:
    :return str:
    """
    # check present "db_type"
    db_type = cfg.get('db_type')
    if db_type is None:
        raise DatabaseConfigError(
            {'message': '"%(config_variable)s" not in config', 'context': {'config_variable': 'db_type'}}
        )

    # check supported databases
    if check_support and db_type not in SUPPORTED_DATABASES:
        raise DatabaseConfigError(
            {
                'message': 'Incorrect database type %(database_type)s. You should only use %(database_types)s. '
                'The correct db_type for mariadb is "mysql"',
                'context': {'database_type': db_type, 'database_types': '", "'.join(SUPPORTED_DATABASES)},
            }
        )

    # check present "connect_string"
    connect_string = cfg.get('connect_string')
    if db_type != SQLITE and connect_string is None:
        raise DatabaseConfigError(
            {'message': '"%(config_variable)s" not in config', 'context': {'config_variable': 'connect_string'}}
        )

    # generate database uri
    if db_type == SQLITE:
        uri = f'{db_type}:///{cfg.get("sqlite_db_path", DEFAULT_DB_PATH)}'
    else:
        client_library = get_db_client_library_name(db_type)
        uri = f'{db_type}+{client_library}://{connect_string}'
        uri = get_fixed_uri(db_type, uri)
    return uri


def make_db_engine(cfg, just_print=False, debug=False, pool_class=None, check_support=True):
    """
    Create sqlalchemy database engine
    :param dict cfg:
    :param bool just_print:
    :param bool debug:
    :param pool_class:
    :param bool check_support:
    :return:
    """
    log = logging.getLogger('init_db_engine')

    try:
        connect_string = cfg_get_uri(cfg, check_support=check_support)
    except DatabaseConfigError as e:
        msg = 'Unable to configure database connection. %(error)s'
        context = {'error': str(e)}
        log.error(msg, context)
        raise MakeDbException({'message': msg, 'context': context}) from e

    log.info('Connecting to database: %s', cfg['db_type'])

    if debug is False and 'debug' in cfg:
        debug = cfg['debug']

    if just_print:
        def dump(sql, *multiparams, **params):
            print(sql)

        engine = sqlalchemy.engine.create_engine(connect_string, strategy='mock', executor=dump)
    else:
        engine = sqlalchemy.engine.create_engine(connect_string, echo=debug, poolclass=pool_class)

    return engine


def validate_database(engine, hide_logging=False, base=Base):
    log = logging.getLogger('validate_database')
    if hide_logging:
        log.propagate = False
        log.addHandler(logging.NullHandler())
    result = {"table_error": False, "column_error": False, "missing_tables": [], "orm_tables": []}
    database_inspection = Inspector.from_engine(engine)
    real_tables = database_inspection.get_table_names()
    for _, _class in list(base._decl_class_registry.items()):  # pylint: disable=protected-access
        if isinstance(_class, _ModuleMarker):
            continue
        table = _class.__tablename__
        result['orm_tables'].append(table)
        if table in real_tables:
            real_columns = [c["name"] for c in database_inspection.get_columns(table)]
            mapper = sqlalchemy.inspect(_class)
            for column_prop in mapper.attrs:
                if isinstance(column_prop, RelationshipProperty):
                    # We have no relationships
                    pass
                else:
                    for column in column_prop.columns:
                        if column.key not in real_columns:
                            log.critical(
                                "Model %s declares column %s which does not exist in database %s",
                                _class,
                                column.key,
                                engine,
                            )
                            result["column_error"] = True
        else:
            log.critical("Model %s declares table %s which does not exist in database %s", _class, table, engine)
            result["table_error"] = True
            result["missing_tables"].append(table)
    if result["table_error"]:
        log.critical("You can run 'lve-create-db --create-missing-tables' command to recreate missing tables.")
    if result["column_error"]:
        log.critical("You can try to recreate malformed table, or ask CloudLinux support for help.")
    return result


def check_need_create_db(engine):
    inspect_result = validate_database(engine, hide_logging=True)
    return inspect_result['missing_tables'] == inspect_result['orm_tables']


def create_db(engine):
    Base.metadata.create_all(engine, tables=get_list_of_tables_without_views())
    # write revision version to database only after create all tables
    alembic_migrate(engine, stamp=True)


def setup_db(engine, create_missing_tables=False, cfg=None):
    if create_missing_tables or check_need_create_db(engine):
        create_db(engine)
    else:
        alembic_migrate(engine, lve_stats_cfg=cfg)


def drop_tables(engine):
    Base.metadata.drop_all(engine)


def clear_rows(engine, server_id=None):
    conn_ = engine.connect()
    trans = conn_.begin()  # delete all rows in one transaction
    try:
        for _, table_object in list(Base.metadata.tables.items()):
            if server_id is None:
                delete_query = delete(table_object)
            elif isinstance(server_id, (list, tuple)):
                delete_query = delete(table_object, table_object.c.server_id in server_id)
            else:
                delete_query = delete(table_object, table_object.c.server_id == server_id)
            conn_.execute(delete_query)
        trans.commit()
    except Exception:
        trans.rollback()
        raise


def recreate_db(engine):
    drop_tables(engine)
    create_db(engine)


def find_lost_keep_alive(session, server_id, from_timestmp=None, to_timestamp=None):
    # query for find timestmps with lost keepalive records
    # SELECT created FROM lve_stats2_history WHERE server_id = 'server_id'
    # GROUP BY created HAVING max(id) > 0 AND min(id) > 0
    lost_keepalive = (
        session.query(history.created)
        .filter(history.server_id == server_id)
        .group_by(history.created)
        .having(func.max(history.id) > 0)
        .having(func.min(history.id) > 0)
    )
    if to_timestamp is not None:
        lost_keepalive = lost_keepalive.filter(history.created <= to_timestamp)
    if from_timestmp is not None:
        lost_keepalive = lost_keepalive.filter(history.created >= from_timestmp)
    return [record_[0] for record_ in lost_keepalive]


def fix_lost_keep_alive(session, server_id, from_timestmp=None, to_timestamp=None, log_=None):
    lost_keep_alive = find_lost_keep_alive(session, server_id, from_timestmp, to_timestamp)
    if not lost_keep_alive:
        return
    # add losted keep alive records
    v2_keepalive_row = {col: 0 for col in list(history.__table__.columns.keys())}
    v2_keepalive_row[history.server_id.key] = server_id

    for timestamp in lost_keep_alive:
        history_keepalive = history(**v2_keepalive_row)
        history_keepalive.created = timestamp  # setup timestamp
        session.add(history_keepalive)
    session.commit()
    if log_:
        log_.info('Was fixed %s losted keep alive records: %s', len(lost_keep_alive), lost_keep_alive)


def fix_db(engine, cfg, from_timestmp=None, to_timestamp=None, log_=None):
    # autocommit=True using for clear cache in mariadb between queries
    session = sessionmaker(bind=engine)()
    fix_lost_keep_alive(session, cfg['server_id'], from_timestmp=from_timestmp, to_timestamp=to_timestamp, log_=log_)
    session.close()


def get_db_client_library_name(db_type):
    """
    Get database Python client library name
    :param str db_type:
    :return str:
    """
    client_library = DB_CLIENT_LIBRARY_MAP.get(db_type)
    if client_library is None:
        raise DatabaseConfigError(
            {
                'message': 'The client library to connect to the "%(database_type)s" ' 'database cannot be detected',
                'context': {
                    'database_type': db_type,
                },
            }
        )
    return client_library


def get_fixed_uri(db_type, uri):
    """
    Get fixed URI for the specified database
    :param str db_type:
    :param str uri:
    :return str:
    """
    if db_type != MYSQL:
        return uri

    u = make_url(uri)
    return str(mysql_lib.get_rfc1738_db_uri(u))

Youez - 2016 - github.com/yon3zu
LinuXploit