ok

Mini Shell

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

B

E!wd�n�@sHddlmZddlmZddlmZddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlZddlZddl
Z
ddlmZddlmZmZddlmZmZmZmZmZmZddlZddlmZddlZdd	lmZdd
l m!Z!m"Z"m#Z#m$Z$dZ%dZ&d
Z'dd�Z(dpdd�Z)dd�Z*dd�Z+dd�Z,dd�Z-dqdd�Z.dd�Z/ee0d �d!d"�Z1d#d$�Z2e3d �d%d&�Z4ee0d �d'd(�Z5edd)�ee0d �d*d+��Z6e7d,�d-d.�Z8e0e3d/�d0d1�Z9e3d �d2d3�Z:e3d �d4d5�Z;d6d7�Z<d8d9�Z=d:d;�Z>d<d=�Z?d>d?�Z@d@dA�ZAdBdC�ZBe0e3dD�dEdF�ZCe7e3dG�dHdI�ZDeee3dJ�dKdL�ZEe7d �dMdN�ZFe0ee3e3fdO�dPdQ�ZGe0ee3e3fdO�dRdS�ZHe0ee3e3fdO�dTdU�ZIe0e3e3dV�dWdX�ZJee
j
e
jKfe0dY�dZd[�ZLdre0e0e0e7ee7e0fd\�d]d^�ZMe0d �d_d`�ZNe3d �dadb�ZOe0ee7dc�ddde�ZPe0df�dgdh�ZQe0df�didj�ZRdkdl�ZSe0e0dm�dndo�ZTdS)s�)�print_function)�absolute_import)�divisionN)�	lru_cache)�ConfigParser�Error)�Dict�Any�AnyStr�Optional�Tuple�Union)�etree)�	is_ubuntu)�
check_command�run_command�exec_utility�ExternalProgramFailedz/etc/sysconfig/rhn/systemid)ZMonZTueZWedZThuZFriZSatZSunz /opt/cloudlinux/litespeed_statuscCspd}tj�|�r4yt�|�}Wntk
r2YnX||krlyt�|�Wntk
r^YnXt�||�dS)a
    Create symlink link_path -> link_value if it does not exist or
    points to different location
    :param link_value: path that symlink should point to (symlink value)
    :type link_value: str
    :param link_path: path where to create symlink
    :type link_path: str
    N)�os�path�islink�readlink�OSError�unlink�symlink)Z
link_valueZ	link_pathZlink_to�r�?/opt/alt/python37/lib/python3.7/site-packages/clcommon/utils.py�create_symlink2s	rc	Cs6g}tj�|�r2t|d|d��}|��}WdQRX|S)a
    Read file and return file's lines
    errors param may be passed to define how handle
    unicode errors, errors=None is default value of open()
    :param path: path to file
    :param unicode_errors_handle: how to handle unicode errors
    :return: list of file's lines
    �r)�errorsN)rr�isfile�open�	readlines)rZunicode_errors_handle�content�frrr�get_file_linesIs

r%c	Cs$t||��}|�|�WdQRXdS)z�
    Write lines to file
    :param content: list of lines for writing to file
    :param path: path to file
    :param mode: open mode
    :return: None
    N)r!�
writelines)rr#�moder$rrr�write_file_linesZs	r(cs:t|�}�fdd�|D�}t|�t|�k}t||d�|S)a
    Delete line from file. Return True when line(s) have been deleted, False otherwise (specified line is not found)
    :param path: path to file
    :type path: string
    :param line: line to delete without EOL ('
')
    :type line: string
    :rtype bool
    csg|]}�|�d�kr|�qS)�
)�rstrip)�.0�item)�linerr�
<listcomp>qsz)delete_line_from_file.<locals>.<listcomp>zw+)r%�lenr()rr-Z
file_linesZout_file_lines�foundr)r-r�delete_line_from_filegs
	r1cCsnt��}|dkrjy,t�d�j}|t��ks6t��|kr:dSWntk
rPYnXtdt	j
d�t	�d�dS)zH
    Check whether current user is effectively root and exit if not
    rZ
clsupergidNz'Error: root privileges required. Abort.)�file���)r�geteuid�grpZgetgrnam�gr_gid�	getgroups�getegid�KeyError�print�sys�stderr�exit)Zeuidr6rrr�is_root_or_exitxsr>cCstj�d�S)zV
    Detects is EA4 installed
    :return: True - EA4 present; False - EA4 absent
    z/etc/cpanel/ea4/is_ea4)rrr rrrr�is_ea4�sr?FTc	cs�|dkrt|�}d}|s<|�d�s0|s0d�|�}t�|�}nd}xh|D]`}|rv|rf|�|�dkrf|}q�|�|�r�|}n|�|�r�|}|r�|dk	r�|Vn
|dk	r�Pd}qFW|dk	r�|VdS)a
    Grep pattern in file
    :param multiple_search: if True - search all match,
                            False - search first match
    :param pattern: pattern for search
    :param path: path to file
    :param data_from_file: read data from file for parsing
    :param fixed_string: if True - search only fixed string,
           False - search by regexp
    :param match_any_position: if True - search any match position,
           False - search only from string begin
    :return: Generator with matched strings
    N�^z^{}r3)r%�
startswith�format�re�compile�find�search)	�patternr�fixed_stringZmatch_any_position�multiple_search�data_from_file�resultZpattern_compr-rrr�grep�s.



rLcCs
t�t�S)z-
    :rtype: lxml.etree._ElementTree obj
    )r�parse�RHN_SYSTEMID_FILErrrr�_parse_systemid_file�srO)�returncCsby>t�}x2|�d�D]$}|�d�j|kr|�d�djSqWWnttttjfk
r\dSXdS)z`
    find a member in xml by name and return value
    :type name: str
    :rtype: str|None
    �member�name�valuerN)	rO�iterrE�text�IOError�
IndexErrorr9rZ
ParseError)rRZrhn_systemid_xmlrQrrr�get_rhn_systemid_value�srXc
Cs�dd|d�}tj�|�s|SyLtjd|gdddd���}tjd|gdddd���}d|d	<||d
<Wn<tjtfk
r�}zd||f}||d
<Wdd}~XYnX|S)
aZ
    This function is written for detect file system in which file is stored on.
    E.g., the file can be stored in NFS and this can affect the normal operation of the file.
    We want to receive information about FS in emergency situations during reading or writing
    :param file_path: path to file, for which we want to detect file system
    :return: dict, which contains two keys:
            key 'success' can be equals to False if we got error or True if we got normal result
            key 'details' can contais error string if key 'success' is False or result if key 'success' is True
    FzFile "%s" isn't exists)�success�detailsz%df %s | tail -n 1 | awk '{print $NF}'Tz	/bin/bash)�shell�
executablerUzmount | grep "on %s type"rYrZz6We can't get file system for file "%s". Exception "%s"N)rr�exists�
subprocess�check_output�strip�CalledProcessErrorr)Z	file_pathrKZmount_point�data�errrrr�*get_file_system_in_which_file_is_stored_on�s.rdcCsDtddd�}y|�d�|�dd�}Wntk
r>d}YnX|S)z�
    Checks if testing is enabled in /etc/yum.repos.d/cloudlinux.repo config
    :return: bool value if testing enabled or not
    NF)Z
interpolation�strictz /etc/yum.repos.d/cloudlinux.repozcloudlinux-updates-testingZenabled)r�readZ
getbooleanr)�parserZresrrr�is_testing_enabled_repos

rhcCs�t�r
dSddddddd�}t��}x |D]}|r*||kr*||Sq*Wtd�}d	}|d	kr`d	}n6d
|krnd}n(d|kr|d}nd|kr�d}nd
|kr�d}|S)a
    Returns cl version taking into account release version
    E.g: release =
        2.6.32-896.16.1.lve1.4.54.el6.x86_64
        5.14.0-162.6.1.el9_1.x86_64
    el6 = cl6
    el8 = cl8
    ........
    ubuntu+cl_extesions = cl8
    :return appropriate version string
    �cl8�cl6Zcl6hZcl7Zcl7hZcl9)zel6.zel6h.zel7.zel7h.zel8.z.el9Z
os_releaseN�6�7�8�9)r�platform�releaserX)Zcheck_vals_decoderrpZ	check_valZret_valrrr�get_cl_versions2
rq)�maxsizec	CsLytdg���}Wntjtfk
r,dSX|dkrD|�d�dSdSdS)a�
    Returns virtualization type on current system.
    It is reachable via virt-what utility.
    E.g.: 'kvm', 'bhyve', 'openvz', 'qemu'
    All acceptable outputs are listed here:
    https://people.redhat.com/~rjones/virt-what/virt-what.txt

    Output will be returned with at least two rows
    Sample:
        > kvm
        >
    Furthermore, there is a possibility for multiple text rows
    Sample:
        > xen
        > xen-domU
    That's why, the result will be taken from a first row.
    If the output is empty, and there were no errors, the machine
    is either non-virtual, or virt-what tool isn't familiar with it's
    hypervisor. But the list of supported hypervisors and containers
    covers all popular VMs types.

    :return: virt_type - Optional[AnyStr]
        - appropriate virtualization type string,
        - 'physical' if there is no virtualization,
        - None if there was an error
    z/usr/sbin/virt-whatN�r)rZphysical)rr`r^ra�FileNotFoundError�split)Zvirt_what_outputrrr�
get_virt_type@srv)�pidcCs.yt�|d�Wntk
r$dSXdSdS)z�
    Checks for a process existence by os.kill command
    If os.kill will be used as os.kill(pid, 0), it will
    just check for a presence of such PID

    And if such pid can't be reached with kill method,
    there will be raised OSError
    rFTN)r�killr)rwrrr�	check_pidgs
	ry)�
pid_file_pathrPc	CsNtj�|�rJt|��0}ytt|������Stk
r>YnXWdQRXdS)z�Check if process running using pid file
    Arguments:
        pid_file_path: path to the pid file of service

    Returns:
        bool: True or False
    NF)	rrr r!ry�intrfr`�
ValueError)rzr$rrr�is_process_runningxs
r}c	CsTt��dkrd}t|�Stj�t�s(dStt��}|����}WdQRX|dkSdS)a
    Detects that server works under Litespeed.
    Note: be careful when modifying this method.
    It is used in X-Ray, ask @dkavchuk or someone else from C-Projects team
    for details.
    return: True - LS working; False - LS not running (stopped or absent)
    rz/tmp/lshttpd/lshttpd.pidFN�0)	rr4r}rr]�LITESPEED_STATUS_FOR_USERSr!rfr`)rzr$�statusrrr�is_litespeed_running�s
r�cCsd}t|�S)zHCheck if nginx is running

    Returns:
        Bool: True or False
    z/run/nginx.pid)r})rzrrr�is_nginx_running�sr�cCst�r
dSdS)zU
    Return proper passenger package according to apache version
    :rtype: str
    zapache24-passengerzalt-mod-passenger)r?rrrr�get_passenger_package_name�sr�cCsBy(t�rtdd|g�ntdd|g�Wntk
r<dSXdS)z_
    Checks that package installed on server
    :param package_name: str
    :rtype: bool
    �dpkgz-sZrpmz-qFT)rrr)Zpackage_namerrr�is_package_installed�sr�cCst�rt�St�SdS)z�
    Pick the package manager to check depending on the OS.
    If we're not on Ubuntu, assume a CL variant with RPM.

    :return: Error string, if any, None otherwise.
    N)r�get_apt_db_errors�get_rpm_db_errorsrrrr�get_package_db_errors�sr�c
CsxyHtjddgdtjtjdd�}|��\}}|jdkrFd|�d|�d	�SWn*ttfk
rr}zt|�Sd
}~XYnXd
S)z�
    Check the dpkg DB as described in https://man7.org/linux/man-pages/man1/dpkg.1.html
    See `--audit`.

    :return: Error string, if any, None otherwise.
    r�z--auditFT)r[�stdoutr<rUrzdpkg audit error: r)�.N)r^�Popen�PIPE�communicate�
returncoderrV�str)�prc�std_out�std_errrcrrrr��s
r�c
Cs�d}yNtjddddgtjtjdd�}|��\}}|jdkrPd	|�d
|�d|��SWn*ttfk
r|}zt|�Sd}~XYnXdS)
zx
    Check RPM DB consistency.

    :return: None - No RPM DB errors
            string_message - Error description
    zjhttps://cloudlinux.zendesk.com/hc/en-us/articles/115004075294-Fix-rpmdb-Thread-died-in-Berkeley-DB-libraryz/bin/rpmz--dbpathz/var/lib/rpmz
--verifydbT)r�r<rUrzRPM DB check error: r)z.
See doc: N)r^r�r�r�r�rrVr�)Zdoc_linkr�r�r�rcrrrr��s

r�cCst��t_t��t_dS)a(
    Upon process exit, Sentry sometimes prints:

        Sentry is attempting to send 1 pending error messages
        Waiting up to 10 seconds
        Press Ctrl-C to quit

    This causes broken JSON in output.
    See also this issue: https://github.com/getsentry/raven-python/issues/904
    N)�io�StringIOr;r�r<rrrr�!silence_stdout_until_process_exit	s
r�c	Cs2d|d@}t�|��t�||�WdQRXdS)a
    Create directories with desired permissions

    Changed in version 3.7: The mode argument no longer affects
    the file permission bits of newly-created intermediate-level directories.
    Because it we use umask while creating dirs

    :param mod: desired permissions
    i�N)�secureioZ	set_umaskr�makedirs)r�modZinverted_modrrr�mod_makedirss
r�)�usernamerPcCs(yt�|�Wntk
r"dSXdS)z,
    Check user existence in the system
    FT)�pwd�getpwnamr9)r�rrr�is_user_present's
r�)�uidrPcCs(yt�|�Wntk
r"dSXdS)z+
    Check uid existence in the system
    FT)r��getpwuidr9)r�rrr�is_uid_present2s
r�)rrPc
Cs:yt�|�j}Wntttfk
r*dSXt�|�}|S)z+
    Check that file by path is socket
    N)r�lstat�st_modertrVr�stat�S_ISSOCK)rr'Z	is_socketrrr�is_socket_file=s
r�cCs:tjddddd�}|����d}|dkr.dnt|�}|S)z?
    Get number of system run level by command `runlevel`.
    z/sbin/runlevelTz	/bin/bash)r[r\rU��S)r^r_r`rur{)�outputrK�levelrrr�get_system_runlevelJsr�)�service_namerPc	Cs�t�}ytjd|��dddd�}Wntjtfk
r<dSX|����}xJ|dd�D]:}|���d�}|dd	k}t|d
�}||krXd|fSqXWdS)z�
    Returns state of a service (present and enabled) for init.d system.
    Returns False, False if a service doesn't exist
    Returns True, False if a service exists and it's not enabled
    Returns True, True if a service exists and it's enabled
    zLANG=C /sbin/chkconfig --list Tz	/bin/bash)r[r\rU)FFr�N�:Zonr)TF)r�r^r_rartr`rur{)r�Zrunlevelr�Zoutput_listZ
state_infoZ
state_listZ	is_activeZstate_runlevelrrr�#_get_service_state_on_init_d_system]s"r�cCs�ytjd|�d�ddd�dStjtfk
r�y8tjdd|gtjtjd	�}|��|jd
krddSdSWntjtfk
r�dSXYnXd
S)z�
    Returns state of service (present and enabled) for systemd system
    Returns False, False if a service doesn't exist
    Returns True, False if a service exists and it's not enabled
    Returns True, True if a service exists and it's enabled
    z/usr/bin/systemctl is-enabled z
 &> /dev/nullTz	/bin/bash)r[r\)TTz/usr/bin/systemctlr�)r<r�)r�)TF)FFN)r^Z
check_callrartr�ZDEVNULLr�r�)r��prrr�$_get_service_state_on_systemd_systems(


r�cCs8t�}|r"d|kr"t|d�\}}nt|d�\}}||fS)zc
    Returns state of service (present and enabled)
    :param service_name: name of a service
    rj)r�)rqr�r�)r�Zcl_verZ
is_presentZ
is_enabledrrr�service_is_enabled_and_present�sr�)�process_file_path�strict_matchrPc	Cs~tj�|�std|�d���x\t�dg�D]L}y.|s@||��ksV|rZ|d�|���krZdSWq*tjk
rtw*Yq*Xq*WdS)a�
    Check that a file in path is running.
    You can get false-postive if parameter `strict_match` == False, process is
    not running, but someone on server open file by path `process_file_path`
    in an editor
    :param process_file_path: path to a file which is run
    :param strict_match: we use parameter `process_file_path` as full cmd line
                         with args for comparing if `strict_match` == True.
    :return: True if it's running, False - is not,
    zProcess file in path "z" does not exist�cmdline� TF)	rrr]rt�psutilZprocess_iterr��joinZ
NoSuchProcess)r�r�Zprocessrrr�process_is_running�sr�)�dtrPcCs0t|tjtjf�s$tdt|�����t|��S)z�
    Getting string representation of weekday from datetime.datetime or datetime.date.
    Returns shortened version of weekday from WEEK_DAYS.
    zFRequire object of type datetime.datetime or datetime.date, but passed )�
isinstance�datetime�date�	TypeError�type�	WEEK_DAYSZweekday)r�rrr�get_weekday�sr�)�config_path�apache_module_name�
param_name�defaultrPc
s�d|�d�}g}t|�}d}x>|D]6}|��}||kr<d}q"|rJ|dkrJP|r"|�|�q"Wtt�dd|d��}	�fdd�|	D�}
|
s�|d	k	r�|d
fS|
s�|d	kr�dd|�d
|��fS|
d�d�}t|d�}|d
fS)a
    Helper to parse httpd config for details about mpm module used
    :param config_path: path for configuration file with modules
    :param apache_module_name: expected mpm module. Can be `event`,
        `worker`, `prefork`
    :param param_name: name of parameter to find
    :param default: default value for parameter, if there won't be record
    :return: tuple with param value and text result of operation

    Example of config file content:
    <IfModule mpm_prefork_module>
    .................
        MaxRequestWorkers   450
    </IfModule>
    --
    <IfModule mpm_worker_module>
    .................
        MaxRequestWorkers      300
    </IfModule>
    --
    <IfModule mpm_event_module>
    .................
        MaxRequestWorkers     2048
    </IfModule>
    z<IfModule mpm_z_module>FTz</IfModule>)rIrHrJcs"g|]}|�����r|���qSr)r`rA)r+Z	directive)r�rrr.sz/find_module_param_in_config.<locals>.<listcomp>NZOKrz.MaxRequestWorkers directive not found for mpm_z_module module in r3r�)r%r`�append�listrLrur{)
r�r�r�r�Zif_module_lineZ
section_linesZ	mpm_linesZis_section_foundr-Zgrep_result_listZmrw_list�partsZmax_request_workersr)r�r�find_module_param_in_config�s:


r�c
Csjd}tj�|�sdSy6t|d��}|����}WdQRX|�dd�\}}Wnttt	fk
rddSX|S)zp
    Return kmodlve module's version.
    Content of '/sys/module/kmodlve/version' looks like '2.0-30.el8'.
    z/sys/module/kmodlve/versionrsrNr�r�)
rrr r!rfr`�rsplitrrVr|)Zkmodlve_module_file_pathr$�moduleZmodule_version�_rrr�get_kmodlve_module_version/sr�cCs8ddi}t�}||krdS||}t�}||kr4dSdS)a
    Find out if system has version of the kernel
    (according to kmodlve module's version)
    where fs.proc_can_see_other_uid and hidepid options are synchronized.
    They are only synchronized if kmodlve module's version
    is equal to version in synced_kmodlve_versions.
    riz2.0-30FT)rqr�)Zsynced_kmodlve_versionsZ
cl_versionZsynced_versionZcurrent_versionrrr�)proc_can_see_other_uid_and_hidepid_synced@sr�)�pid_filenamerPc
CsZy6t|d��"}t|�����}t�|d�WdQRXWntttfk
rTd}YnX|S)z�
    Detrmines working daemon process pid
    :param pid_filename: PID filename
    :return: PID from file or None if error (file not found, etc)
    rrN)	r!r{rfr`rrxrrVr|)r��pfrwrrr�get_process_pidSs
r�)r�c	Cs*t|d��}|�t����WdQRXdS)z
    Writes pid file
    zw+N)r!�writer�getpid)r�r�rrr�write_pid_filecsr�c	Cs,yt�|�Wnttfk
r&YnXdS)z
    Remove PID file
    N)r�removerrV)r�rrr�remove_pid_fileksr�cs��fdd�}|S)a
    Set user's real uid and gid to specified ones.
    Checking equality of real and effective uids is needed
    because this function may be used by root
    with effective uid dropped to user's uid.
    In that case it is needed to set effective uid back to 0 first.
    cs:t��}t��}||kr"t�|�t���t���dS)N)r�getuidr4�seteuid�setgid�setuid)Zreal_uidZeff_uid)�gidr�rr�func~s

zdemote.<locals>.funcr)r�r�r�r)r�r�r�demoteus	
r�)�dirpathrPcCsvtj�|�std|�d���dd|g}t|�}y |�d�d}|�d�d}Wn"tk
rptd	|����YnX|S)
zK
    Get mount point for dirpath directory from output of `df` utility
    zDirectory "z" does not existz/bin/dfz-hr)r�r�r3z)Utility "df" returned unexpected output:
)rr�isdirrrrurW)r�Zfs_info_cmdZfs_infoZmountpoint_infoZ
mounted_onrrr�get_mount_point�s
r�)N)NFTFN)N)UZ
__future__rrrr�r�rCr�rr;r5r^ror��	functoolsrZconfigparserrr�typingrr	r
rrr
r�Zlxmlrr�Zclcommon.lib.cleditionrZclcommon.utils_cmdrrrrrNr�rrr%r(r1r>r?rLrOr�rXrd�boolrhrqrvr{ryr}r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�rrrr�<module>s� 	



,,*&


"'
I


Zerion Mini Shell 1.0