U
    ]1                     @   s  d Z ddlmZ ddlZddlZddlZddlZddlZddlZddl	Z	ddl
mZ ddlmZ ddlmZ ddlmZ ddlmZ d	Zd
ZeeZdd Zdd Zdd ZG dd dejZG dd dejjZG dd dejZdd Zdd Z dd Z!dS )a  Logging utilities for Certbot.

The best way to use this module is through `pre_arg_parse_setup` and
`post_arg_parse_setup`. `pre_arg_parse_setup` configures a minimal
terminal logger and ensures a detailed log is written to a secure
temporary file if Certbot exits before `post_arg_parse_setup` is called.
`post_arg_parse_setup` relies on the parsed command line arguments and
does the full logging setup with terminal and rotating file handling as
configured by the user. Any logged messages before
`post_arg_parse_setup` is called are sent to the rotating file handler.
Special care is taken by both methods to ensure all errors are logged
and properly flushed before program exit.

    )print_functionN)messages)	constants)errors)util)osz%(message)sz.%(asctime)s:%(levelname)s:%(name)s:%(message)sc                  C   s   t  } | tt | tj t| }t }|tt	 |t
j t }|tj || || ttj tjt|dtjk| jdt_dS )a  Setup logging before command line arguments are parsed.

    Terminal logging is setup using
    `certbot.constants.QUIET_LOGGING_LEVEL` so Certbot is as quiet as
    possible. File logging is setup so that logging messages are
    buffered in memory. If Certbot exits before `post_arg_parse_setup`
    is called, these buffered messages are written to a temporary file.
    If Certbot doesn't exit, `post_arg_parse_setup` writes the messages
    to the normal log files.

    This function also sets `logging.shutdown` to be called on program
    exit which automatically flushes logging handlers and
    `sys.excepthook` to properly log/display fatal exceptions.

    z--debugdebuglog_pathN)TempHandlersetFormatterlogging	FormatterFILE_FMTsetLevelDEBUGMemoryHandlerColoredStreamHandlerCLI_FMTr   QUIET_LOGGING_LEVEL	getLogger
addHandlerr   Zatexit_registerZshutdown	functoolspartialpre_arg_parse_except_hooksysargvpath
excepthook)temp_handlermemory_handlerZstream_handlerroot_logger r"   -/usr/lib/python3/dist-packages/certbot/log.pypre_arg_parse_setup(   s$    

  r$   c                 C   s  t | dt\}}tj|}t }d }}|jD ]"}t|t	rF|}q2t|t
r2|}q2d}|dk	rj|dk	srt||| || |j}	|| |jdd |  |	  | jrtj}
n| j d }
||
 td|
 td| tjt| j|d	t_dS )
a  Setup logging after command line arguments are parsed.

    This function assumes `pre_arg_parse_setup` was called earlier and
    the root logging configuration has not been modified. A rotating
    file logging handler is created and the buffered log messages are
    sent to that handler. Terminal logging output is set to the level
    requested by the user.

    :param certbot.interface.IConfig config: Configuration object

    zletsencrypt.logNz9Previously configured logging handlers have been removed!Tforce
   zRoot logging level set at %dzSaving debug log to %sr   )setup_log_file_handlerr   r   r   dirnamer   r   handlers
isinstancer   r   AssertionErrorr   ZremoveHandlertargetZ	setTargetflushclosequietr   r   Zverbose_countr   loggerr	   infor   r   post_arg_parse_except_hookr   r   )configZfile_handlerZ	file_pathlogs_dirr!   r    Zstderr_handlerhandlermsgr   levelr"   r"   r#   post_arg_parse_setupN   sB      






  r9   c              
   C   s   t | jd| j tj| j|}ztjj	|d| j
d}W n4 tk
rn } ztt j|W 5 d}~X Y nX |  |tj tj|d}|| ||fS )a  Setup file debug logging.

    :param certbot.interface.IConfig config: Configuration object
    :param str logfile: basename for the log file
    :param str fmt: logging format string

    :returns: file handler and absolute path to the log file
    :rtype: tuple

    i  i   )ZmaxBytesZbackupCountN)fmt)r   Zset_up_core_dirr5   Zstrict_permissionsr   r   joinr   r*   ZRotatingFileHandlerZmax_log_backupsIOErrorr   ErrorZPERM_ERR_FMTformatZ
doRolloverr   r   r   r   )r4   Zlogfiler:   Zlog_file_pathr6   errorZhandler_formatterr"   r"   r#   r(   |   s     
$
r(   c                       s.   e Zd ZdZd fdd	Z fddZ  ZS )r   a6  Sends colored logging output to a stream.

    If the specified stream is not a tty, the class works like the
    standard `logging.StreamHandler`. Default red_level is
    `logging.WARNING`.

    :ivar bool colored: True if output should be colored
    :ivar bool red_level: The level at which to output

    Nc                    s8   t t| | |d kr"tj n| | _tj| _	d S )N)
superr   __init__r   stderrisattycoloredr   ZWARNING	red_levelselfstream	__class__r"   r#   rA      s
    zColoredStreamHandler.__init__c                    s:   t t| |}| jr6|j| jkr6dtj|tj	fS |S )zFormats the string representation of record.

        :param logging.LogRecord record: Record to be formatted

        :returns: Formatted, string representation of record
        :rtype: str

         )
r@   r   r>   rD   ZlevelnorE   r;   r   ZANSI_SGR_REDZANSI_SGR_RESET)rG   recordoutrI   r"   r#   r>      s    	zColoredStreamHandler.format)N)__name__
__module____qualname____doc__rA   r>   __classcell__r"   r"   rI   r#   r      s   
r   c                       sD   e Zd ZdZd fdd	Z fddZd fd	d
	Zdd Z  ZS )r   zBuffers logging messages in memory until the buffer is flushed.

    This differs from `logging.handlers.MemoryHandler` in that flushing
    only happens when flush(force=True) is called.

    N'  c                    s   t t| j||d d S )N)r-   )r@   r   rA   )rG   r-   ZcapacityrI   r"   r#   rA      s    zMemoryHandler.__init__c                    s   | j }tt|   || _ dS )z;Close the memory handler, but don't set the target to None.N)r-   r@   r   r/   )rG   r-   rI   r"   r#   r/      s    zMemoryHandler.closeFc                    s   |rt t|   dS )zFlush the buffer if force=True.

        If force=False, this call is a noop.

        :param bool force: True if the buffer should be flushed.

        N)r@   r   r.   )rG   r&   rI   r"   r#   r.      s    
zMemoryHandler.flushc                 C   s   dS )zShould the buffer be automatically flushed?

        :param logging.LogRecord record: log record to be considered

        :returns: False because the buffer should never be auto-flushed
        :rtype: bool

        Fr"   rG   rL   r"   r"   r#   shouldFlush   s    	zMemoryHandler.shouldFlush)NrS   )F)	rN   rO   rP   rQ   rA   r/   r.   rU   rR   r"   r"   rI   r#   r      s
   r   c                       s8   e Zd ZdZ fddZ fddZ fddZ  ZS )r   a  Safely logs messages to a temporary file.

    The file is created with permissions 600. If no log records are sent
    to this handler, the temporary file is deleted when the handler is
    closed.

    :ivar str path: file system path to the temporary log file

    c                    sH   t  | _tj| jd| _tj| jddd}tt	| 
| d| _d S )Nlogwi  )modechmodT)tempfileZmkdtemp_workdirr   r   r;   r   Z	safe_openr@   r   rA   _deleterF   rI   r"   r#   rA      s
    
zTempHandler.__init__c                    s   d| _ tt| | dS )zlLog the specified logging record.

        :param logging.LogRecord record: Record to be formatted

        FN)r\   r@   r   emitrT   rI   r"   r#   r]      s    zTempHandler.emitc                    sL   |    z4| j  | jr&t| j d| _tt	|   W 5 |   X dS )zuClose the handler and the temporary log file.

        The temporary log file is deleted if it wasn't used.

        FN)
acquirereleaserH   r/   r\   shutilZrmtreer[   r@   r   )rG   rI   r"   r#   r/     s    
zTempHandler.close)rN   rO   rP   rQ   rA   r]   r/   rR   r"   r"   rI   r#   r      s   		r   c              	   O   s"   zt|| W 5 | j dd X dS )a  A simple wrapper around post_arg_parse_except_hook.

    The additional functionality provided by this wrapper is the memory
    handler will be flushed before Certbot exits. This allows us to
    write logging messages to a temporary file if we crashed before
    logging was fully configured.

    Since sys.excepthook isn't called on SystemExit exceptions, the
    memory handler will not be flushed in this case which prevents us
    from creating temporary log files when argparse exits because a
    command line argument was invalid or -h, --help, or --version was
    provided on the command line.

    :param MemoryHandler memory_handler: memory handler to flush
    :param tuple args: args for post_arg_parse_except_hook
    :param dict kwargs: kwargs for post_arg_parse_except_hook

    Tr%   N)r.   r3   )r    argskwargsr"   r"   r#   r     s    r   c                 C   s   | ||f}|st | ts8tjtjks(ttjd|d nftj	d|d t | t
jr\t| td t|rt|d\}}}t| nt| |d t| dS )a!  Logs fatal exceptions and reports them to the user.

    If debug is True, the full exception and traceback is shown to the
    user, otherwise, it is suppressed. sys.exit is always called with a
    nonzero status.

    :param type exc_type: type of the raised exception
    :param BaseException exc_value: raised exception
    :param traceback trace: traceback of where the exception was raised
    :param bool debug: True if the traceback should be shown to the user
    :param str log_path: path to file or directory containing the log

    zExiting abnormally:)exc_infozAn unexpected error occurred:z:: N)
issubclass	Exceptionr   r   r   ZERRORr,   r1   r?   r	   r   r=   r   exitr   Zis_acme_errorstr	partition	tracebackprint_exceptionexit_with_log_path)exc_type	exc_valueZtracer	   r
   rc   _Zexc_strr"   r"   r#   r3   /  s    



r3   c                 C   sD   d}t j| r |d| 7 }n|d| 7 }|d7 }t| dS )zPrint a message about the log location and exit.

    The message is printed to stderr and the program will exit with a
    nonzero status.

    :param str log_path: path to file or directory containing the log

    zPlease see the zlogfiles in {0} zlogfile '{0}' zfor more details.N)r   r   isdirr>   r   rf   )r
   r7   r"   r"   r#   rk   R  s    	rk   )"rQ   Z
__future__r   r   r   Zlogging.handlersr`   r   rZ   ri   Zacmer   Zcertbotr   r   r   Zcertbot.compatr   r   r   r   rN   r1   r$   r9   r(   ZStreamHandlerr   r*   r   r   r   r3   rk   r"   r"   r"   r#   <module>   s2   
&. ,-#