%PDF- %PDF-
Mini Shell

Mini Shell

Direktori : /opt/alt/python37/lib/python3.7/site-packages/ssa/internal/__pycache__/
Upload File :
Create Path :
Current File : //opt/alt/python37/lib/python3.7/site-packages/ssa/internal/__pycache__/utils.cpython-37.pyc

B

r�b�7�@s�dZddlZddlZddlZddlZddlZddlZddlZddlm	m
Zddlm
Z
ddlmZddlmZmZddlmZddlmZmZmZmZmZmZmZddlmZmZdd	lmZddl Z dd
l!m"Z"ddl#m$Z$ddl%m&Z&d
dl'm(Z(d
dl'm)Z)d
dl*m+Z+e�,d�Z-e
dddg�Z.e/e.d�dd�Z0e1d�dd�Z2dd�dd�Z3dTe/e4e/d�dd �Z5e/e/d!�d"d#�Z6e/d$d%�d&d'�Z7e/d�d(d)�Z8dUe/e/d+�d,d-�Z9e/d�d.d/�Z:e;e<d0�d1d2�Z=e/ee/d3�d4d5�Z>ee/d�d6d7�Z?ee/d�d8d9�Z@e4d�d:d;�ZAe4d�d<d=�ZBe4d�d>d?�ZCe4dd@�dAdB�ZDe4d�dCdD�ZEe/d�dEdF�ZFe/ee/efe4dG�dHdI�ZGedVe;ddJ�dKdL��ZHedWe;e;e;ddO�dPdQ��ZIdRdS�ZJdS)Xz>
This module contains helpful utility functions for SSA Agent
�N)�
namedtuple)�contextmanager)�date�	timedelta)�LooseVersion)�socket�fromfd�AF_UNIX�SOCK_STREAM�AF_INET�AF_INET6�
SOCK_DGRAM)�Optional�Union)�urlparse)�AtexitIntegration)�LoggingIntegration)�get_kmodlve_module_version�)�
sentry_dsn)�storage_file)�SSAError�utils�URL�domain_nameZuri_path)�url�returncCsJt|�}|jrd|j��nd}|jr2|j�|��nd}t|j�dd�|�S)z�
    Split URL into domain_name and uripath including query string
    :param url: URL of format protocol://domain/path;parameters?query#fragment
    :return: namedtuple URL(domain_name, uripath)
    �?��/zwww.)r�query�pathr�netloc�replace)rZ	fragments�qs�uri�r&�C/opt/alt/python37/lib/python3.7/site-packages/ssa/internal/utils.py�	url_split,sr()rc
s|t�d�y,t�t����fdd����D�SQRXWn@tk
rv}z"tjdt|�dt|�id�t	�Sd}~XYnXdS)zS
    Try to load stats from file.
    In case of fail instantiate empty struct
    zLoading data from storage...csi|]}�||�qSr&r&)�.0�item)�dbr&r'�
<dictcomp>Asz(load_collected_stats.<locals>.<dictcomp>Nz$Failed to load data from storage: %s�err)�extra)
�logger�info�shelve�openr�keys�OSError�error�str�dict)�er&)r+r'�load_collected_stats9s
 r9c	s�tttd�dd�}dd���fdd�}dd	�d
d�}ttjtjd�}t|d
�}tjt|d||gd�t�	��}d|�i|_
WdQRXdS)u�
    Initialize Sentry client
    shutdown_timeout=0 disables Atexit integration as stated in docs:
    'it’s easier to disable it by setting the shutdown_timeout to 0'
    https://docs.sentry.io/platforms/python/default-integrations/#atexit
    On the other hand, docs say, that
    'Setting this value too low will most likely cause problems
    for sending events from command line applications'
    https://docs.sentry.io/error-reporting/configuration/?platform=python#shutdown-timeout
    )�event�hintrcSs|d�ddi�|S)z�
        Add extra data into sentry event
        :param event: original event
        :param hint: additional data caught
        :return: updated event
        r.zssa.versionz	0.2-3.el7)�update)r:r;r&r&r'�add_infoUszsentry_init.<locals>.add_infoc	SsRt|t��>}y|�|df�|��d}Wntk
rBd}YnXWdQRX|S)aI
        address_family - we can choose constants represent the address
                           (and protocol) families
                           (AF_INET for ipv4 and AF_INET6 for ipv6)
        private_ip - specify some private ip address. For instance:
                     ipv4 -> 10.255.255.255 or ipv6 -> fc00::
        rrN)rr
�connect�getsockname�	Exception)Zaddress_familyZ
private_ip�sZIPr&r&r'�
try_get_ip_szsentry_init.<locals>.try_get_ipcs8tdftdff}x"|D]\}}�||�}|r|SqWdS)zq
        We are trying to get an IPv4 or IPv6 address.
        In case of failure we'll return 127.0.0.1
        z10.255.255.255zfc00::z	127.0.0.1)rr)Z
ipversionsZaddr_famZpriv_ip�ip)rBr&r'�get_ipos
zsentry_init.<locals>.get_ipN)rcSsdS)Nr&)�pending�timeoutr&r&r'�nope{�zsentry_init.<locals>.nope)�levelZevent_level)�callbackzalt-php-ssa@0.2-3.el7)ZdsnZbefore_send�releaseZintegrationsZ
ip_address)r7r�logging�INFO�WARNINGr�
sentry_sdk�initr�configure_scope�user)r=rDrGZsentry_loggingZ
silent_atexit�scoper&)rBr'�sentry_initIs



rTF)�fname�as_errorrc
Cs�y>tj|tjddd�yt�|d�Wntk
r:YnX|Stk
r~}z"t�|r^tj	ntjdt
|��Wdd}~XYnXdS)zz
    Try to configure logging into given fname
    If as_error True, log the exception as ERROR, otherwise -- as INFO
    z%(asctime)s %(message)sz%m/%d/%Y %I:%M:%S %p)�filenamerI�format�datefmti�z$No logging configuration applied: %sN)rL�basicConfigrM�os�chmod�PermissionErrorr4r/�log�ERRORr6)rUrVr8r&r&r'�set_logging_into_file�s
r`)�lognamerc
Cslt�t|�dkrhyt�tj�|��Wn2tk
rZ}zt�dt	|��dSd}~XYnXt|dd�}|S)zP
    Configure logging
    :param logname: path to log
    :return: logpath
    NzFailed to create logdir %srT)rV)
rTr`r[�makedirsr!�dirnamer@r/�warningr6)rar8r&r&r'�configure_logging�srez
socket object)�
sock_locationrc	Cs`ttj�dd��}|dkrHt�� tt�}|�|�|��WdQRXnt	dtt
�}|��|S)z�
    Create world-writable socket in given sock_location
    or reuse existing one
    :param sock_location: socket address
    :return: socket object
    �
LISTEN_FDSrN�)�intr[�environ�get�umask_0rr	�bind�listenrr
)rfrgZsockobjr&r&r'�
create_socket�s
rocCst��tdd�}|�d�S)zC
    Returns date of previous day in a format "day.month.year"
    r)�daysz%d.%m.%Y)r�todayr�strftime)Z	yesterdayr&r&r'�previous_day_date�srs�%d.%m.%Y)�datestrrcCstj�||�}|�d�S)z+
    Convert date to format YYYY-mm-dd
    z%Y-%m-%d)�datetime�strptimerr)ruZ	formatstrZ_dater&r&r'�format_date�srxc
Cs�yHt�d�}|��}|�d�j}t���}|�d|�WdQRX|�d�St	tj
fk
r�}zt�dt
|��Wdd}~XYnXdS)ze
    Obtain system ID from /etc/sysconfig/rhn/systemid
    :return: system ID without ID- prefix
    z/etc/sysconfig/rhn/systemidz(.//member[name='system_id']/value/stringZ	system_idNzID-z Failed to retrieve system_id: %s)�ET�parse�getroot�find�textrOrQZset_tag�lstripr4�
ParseErrorr/rdr6)�tree�rootZwhole_idrSr8r&r&r'�read_sys_id�s


r�)�durationrcCstt|dd��S)zQ
    Cast duration from microseconds to seconds leaving 2 digits after point
    i@Bz0.2f)�floatrX)r�r&r&r'�
duration_cast�sr�)�filepathrc	CsVy$t|��}|����}WdQRXWntk
r8dSXd�|�d�dd��pTdS)zDGet version of package from file. alt-php-ssa/alt-php-xray supportedN�.�z0.0-0)r2�read�stripr4�join�split)r�Zv_file�versionr&r&r'�pkg_version�s
r�cCstd�S)z"Get version of alt-php-ssa packagez/usr/share/clos_ssa/version)r�r&r&r&r'�ssa_version�sr�cCstd�S)z#Get version of alt-php-xray packagez/usr/share/alt-php-xray/version)r�r&r&r&r'�xray_version�sr�c	Cs@t�}|dkrdSyt|�td�kSttfk
r:dSXdS)zb
    Check version of alt-php-xray package.
    Autotracing in X-Ray is supported since 0.4-1
    NFz0.4-1)r�r�	TypeError�AttributeError)Zversion_numberr&r&r'�is_xray_version_supported�sr�c
CsFd}ttt��.}y|�|�Wnttfk
r6dSXWdQRXdS)z Check if User Agent is listeningz$/opt/alt/php-xray/run/xray-user.sockFNT)rr	r
r>�ConnectionErrorr4)Zuser_agent_sockrAr&r&r'�is_xray_user_agent_active
sr�c	CsXd}tj�|�sdSy(t�|d��}t|���dkSQRXWntjk
rRdSXdS)z@Check if there are no active X-Ray tasks (== empty task storage)z/usr/share/alt-php-xray/tasksT�crNF)r[r!�isfile�dbmr2�lenr3r5)Zxray_tasks_storageZ
xray_tasksr&r&r'�no_xray_active_taskssr�)�enabledrc
Cs�t�d|�y:tdddd��"}|�|r*dnd�t�d�Wd	QRXWn4tk
rz}zt�d
|t|��Wd	d	}~XYnXd	S)zb
    Switch on/off throttle statistics gathering by kmodlve
    :param enabled: True or False
    zSwitching schedstats: %sz!/proc/sys/kernel/sched_schedstats�wbr)�mode�	buffering�1�0zDone OKNz(Failed to set sched_schedstats to %s: %s)r/r0r2�writer4r6)r��fr8r&r&r'�switch_schedstats%s
r�cCs0td�}td�}t�}|r$t||�Stt�|�S)z�
    Check kmodlve module version or kernel version in order to determine
    if it provides the detection of IO throttling
    z2.0-23z1.5.58)rr�compare_versions_ge�extract_kernel_version)Zkmod_min_versionZkernel_min_versionZkmod_currentr&r&r'�$is_io_throttling_detection_available5s
r�cCs@t�d�}t��}y|�|��d�}Wntk
r:dSX|S)zO
    Get kernel version in the form of "major-minor" from current platform
    zlve([.0-9]*).elrz0.0.0)�re�compile�platformrK�search�groupr�)�patternrKZversion_numr&r&r'r�Bs
r�)�
first_version�second_versionrc
CsJyt|�|kStk
rD}ztd|�d|�d���Wdd}~XYnXdS)zE
    Comparing two versions using the greater or equal operator.
    zAUnable to compare required versions: unexpected versions format "z" and "�"N)rr�r)r�r�r8r&r&r'r�Os
r�)�maskrccst�|�}dVt�|�dS)z,
    Context manager for dropping umask
    N)r[�umask)r��prevr&r&r'rl\s
rlr�T)�
target_uid�
target_gidr�rc	csdt��}t��}yt�|�}Wntk
r6d}YnX|dkrT|dkrN|}n|j}|dkrp|dkrj|}n|j}|dk	r�t�|�}||kr�t�|�t	�
d|�|r�t��|kr�td��||k�rt�
|�t	�
d|�|�rt��|k�r||kr�t�|�td��dV||k�r,t�
|�t	�
d|�||k�rLt�|�t	�
d|�|dk	�r`t�|�dS)aH
    Context manager to drop privileges during some operation
    and then restore them back.
    If target_uid or target_gid are given, use input values.
    Otherwise, stat target_uid and target_gid from given target_path.
    If no target_path given, use current directory.
    Use mask if given.
    :param target_uid: uid to set
    :param target_gid: gid to set
    :param target_path: directory or file to stat for privileges,
                       default -- current directory
    :param mask: umask to use
    :param with_check: check the result of switching privileges
    NzDropped GID privs to %sz6Unable to execute required operation: permission issuezDropped UID privs to %szRestored UID privs to %szRestored GID privs to %s)r[�getuid�getgid�statr4�st_uid�st_gidr��setegidr/�debug�getegidr�seteuid�geteuid)	r�r�Ztarget_pathr�Z
with_checkZprev_uidZprev_gid�	stat_infor�r&r&r'�set_privilegesfsN










r�cCsGdd�d�}||�S)Nc@s eZdZdZdd�Zdd�ZdS)zsingleton.<locals>.__Singletonzm
        A singleton wrapper class. Its instances would be created
        for each decorated class.
        cSs||_d|_dS)N)�_wrapped�	_instance)�self�_clsr&r&r'�__init__�sz'singleton.<locals>.__Singleton.__init__c_s|jdkr|j||�|_|jS)z,Returns a single instance of decorated classN)r�r�)r��args�kwargsr&r&r'�__call__�s
z'singleton.<locals>.__Singleton.__call__N)�__name__�
__module__�__qualname__�__doc__r�r�r&r&r&r'�__Singleton�sr�r&)Zsome_clsr�r&r&r'�	singleton�sr�)F)rt)r)NNr�NT)Kr�rvr�rLr[r�r�r1Zxml.etree.ElementTree�etree�ElementTreery�collectionsr�
contextlibrrr�distutils.versionrrrr	r
rrr
�typingrr�urllib.parserrOZsentry_sdk.integrations.atexitrZsentry_sdk.integrations.loggingr�clcommon.utilsr�	constantsrr�
exceptionsr�	getLoggerr/rr6r(r7r9rT�boolr`rerorsrxr�rir�r�r�r�r�r�r�r�r�r�r�r�rlr�r�r&r&r&r'�<module>
sd$

>


	D

Zerion Mini Shell 1.0