File: //lib64/python3.9/site-packages/lsm/__pycache__/_transport.cpython-39.opt-1.pyc
a
    V��d�  �                   @   s�   d dl Z d dlZd dlZd dlZd dlZd dlmZmZ d dlmZ	 d dl
mZ d dl
m
Z G dd� de�Zdd	� ZG d
d� dej�Zedkr�e��  dS )
�    N)�LsmError�ErrorNumber)�	SocketEOF)�DataDecoder)�DataEncoderc                   @   s|   e Zd ZdZdZdd� Zdd� Zdd� Zd	d
� Ze	dd� �Z
d
d� Zdd� Zdd� Z
dd� Zddd�Zddd�Zdd� ZdS )�	TransPorta�  
    Provides wire serialization by using json.  Loosely conforms to json-rpc,
    however a length header was added so that we would have the ability to use
    non sax like json parsers, which are more abundant.
    <Zero padded 10 digit number [1..2**32] for the length followed by
    valid json.
    Notes:
    id field (json-rpc) is present but currently not being used.
    This is available to be expanded on later.
    �
   c                 C   sT   |dk rt d��t� }t|�|k rJ| j�|t|� �}|s@t� �||7 }q|�d�S )z�
        Reads l number of bytes before returning.  Will raise a SocketEOF
        if socket returns zero bytes (i.e. socket no longer connected)
        �   z Trying to read less than 1 byte!�utf-8)�
ValueError�	bytearray�len�sZrecv�
_SocketEOF�decode)�self�l�data�r� r   �4/usr/lib64/python3.9/site-packages/lsm/_transport.py�	_read_all#   s    
zTransPort._read_allc                 C   sP   |du st |�dk rtd��t�tt |��| j�| }| j�t|�d��� dS )z]
        Sends the json formatted message by pre-appending the length
        first.
        Nr	   zMsg argument emptyr
   )	r
   r   �str�zfill�HDR_LENr   Zsendall�bytes�encode)r   �msgr   r   r   r   �	_send_msg5   s    zTransPort._send_msgc              
   C   sx   z| � | j�}| � t|��}W nT tjyV } zttjdt|���W Y d}~n&d}~0  t	yr   ttjd��Y n0 |S )zk
        Reads header first to get the length and then the remaining
        bytes of the message.
        z.Error while reading a message from the plug-inNz3Error while reading a message from the plug-in, EOF)
r   r   �int�socket�errorr   r   �TRANSPORT_COMMUNICATIONr   r   )r   Z	num_bytesr   �er   r   r   �	_recv_msgC   s    ��
zTransPort._recv_msgc                 C   s
   || _ d S )N)r   )r   Zsocket_descriptorr   r   r   �__init__V   s    zTransPort.__init__c                 C   s�   zZt � t jt j�}tj�| �rLt�| tjtjB �r>|�	| � qXt
tjd��nt
tj
d��W n  t jyz   t
tjd��Y n0 |S )zE
        Returns a connected socket from the passed in path.
        z-Permissions are incorrect for IPC socket filezPlug-in appears to not existz*Unable to connect to lsmd, daemon started?)r    �AF_UNIX�SOCK_STREAM�os�path�exists�access�R_OK�W_OKZconnectr   r   ZPLUGIN_SOCKET_PERMISSIONZPLUGIN_NOT_EXISTr!   ZPLUGIN_IPC_FAIL)r)   r   r   r   r   �
get_socketY   s"