3 گa:@sdZddlZddlZddlZddlZddlZddlZddlZddlm Z ddl m Z ddl m Z ddl m Z ddl mZddl mZdd lmZdd lmZdd lmZdd lmZdd lmZddlmZdZdZejeZddddZej ddddZ!ej e"e"eej#e"fdddZ$Gdddej%Z&Gdddej'j(Z(Gdddej%Z)e(e e dd d!d"Z*ee+e+e e,e,e"dd#d$d%Z-e"dd&d'd(Z.dS))aLogging 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. The `logging` module is useful for recording messages about about what Certbot is doing under the hood, but do not necessarily need to be shown to the user on the terminal. The default verbosity is WARNING. The preferred method to display important information to the user is to use `certbot.display.util` and `certbot.display.ops`. N) TracebackType)Any)IO)Optional)Tuple)Type)messages) configuration)errors)util) constants)osz %(message)sz.%(asctime)s:%(levelname)s:%(name)s:%(message)s)returncCst}|jtjt|jtjt|}t}|jtjt |jt j tj }|jtj|j ||j |tjtjtjt|dtjkdtjkpdtjk|jdt_dS)aSetup logging before command line arguments are parsed. Terminal logging is setup using `certbot._internal.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--debugz--quietz-q)debugquietlog_pathN) TempHandler setFormatterlogging FormatterFILE_FMTsetLevelDEBUG MemoryHandlerColoredStreamHandlerCLI_FMTr QUIET_LOGGING_LEVEL getLogger addHandlerr Zatexit_registerZshutdown functoolspartialpre_arg_parse_except_hooksysargvpath excepthook) temp_handlermemory_handlerZstream_handler root_loggerr)/usr/lib/python3.6/log.pypre_arg_parse_setup5s"      r+)configrc Cs(t|dt\}}tj}d}}x,|jD]"}t|tr<|}q(t|tr(|}q(Wd}|j||j |t |dd}|j ||j dd|j |r|j |jrtj} n0|jdk rtjt|jd} ntj|jd} |j| tjd| |js td |tjd tjt|j|j|d t_dS) aSetup 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.configuration.NamespaceConfig config: Configuration object zletsencrypt.logNz9Previously configured logging handlers have been removed!targetT)force zRoot logging level set at %dzSaving debug log to )file)rrr)setup_log_file_handlerrrrhandlers isinstancerrrZ removeHandlergetattrZ setTargetflushcloserr rZ verbose_levelZDEFAULT_LOGGING_LEVELintZ verbose_countrloggerrprintr"stderrrr post_arg_parse_except_hookr%) r,Z file_handlerZ file_pathr(r'Zstderr_handlerhandlermsgr&levelr)r)r*post_arg_parse_setup]s<            r?)r,logfilefmtrcCstj|jd|jtjj|j|}ytjj |d|j d}Wn4t k rn}zt j tjj|WYdd}~XnX|j|jtjtj|d}|j|||fS)aSetup file debug logging. :param certbot.configuration.NamespaceConfig 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)ZmaxBytesZ backupCountN)rAi)r Zset_up_core_dirZlogs_dirZstrict_permissionsr r$joinrr2ZRotatingFileHandlerZmax_log_backupsIOErrorr ErrorZ PERM_ERR_FMTformatZ doRolloverrrrr)r,r@rAZ log_file_pathr<errorZhandler_formatterr)r)r*r1s$   r1csDeZdZdZd eeddfdd Zeje dfdd Z Z S) ra6Sends 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 N)streamrcs4tj||dkrtjjn|j|_tj|_dS)N) super__init__r"r:isattycoloredrZWARNING red_level)selfrI) __class__r)r*rKs  zColoredStreamHandler.__init__)recordrcs6tj|}|jr2|j|jkr2djtj|tjfS|S)zFormats the string representation of record. :param logging.LogRecord record: Record to be formatted :returns: Formatted, string representation of record :rtype: str ) rJrGrMZlevelnorNrDr Z ANSI_SGR_REDZANSI_SGR_RESET)rOrQout)rPr)r*rGs zColoredStreamHandler.format)N) __name__ __module__ __qualname____doc__rrrKr LogRecordstrrG __classcell__r)r))rPr*rs rcsleZdZdZdeejeddfdd Zddfdd Z de dd fd d Z ej e dddZ ZS)rzBuffers 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')r-capacityrcstj||ddS)N)r-)rJrK)rOr-r\)rPr)r*rKszMemoryHandler.__init__)rcst|d}tj||_dS)z;Close the memory handler, but don't set the target to None.r-N)r4rJr6r-)rOr-)rPr)r*r6s  zMemoryHandler.closeF)r.rcs|rtjdS)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)rJr5)rOr.)rPr)r*r5s zMemoryHandler.flush)rQrcCsdS)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))rOrQr)r)r* shouldFlushs zMemoryHandler.shouldFlush)Nr[)F)rTrUrVrWrrHandlerr7rKr6boolr5rXr]rZr)r))rPr*rs  rcsNeZdZdZddfdd Zejddfdd Zddfd d ZZ S) ra 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 N)rcsHtj|_tjj|jd|_tj|jddd}tj ||d|_ dS)Nlogwi)modechmodT) tempfileZmkdtemp_workdirr r$rDr Z safe_openrJrK_delete)rOrI)rPr)r*rKs   zTempHandler.__init__)rQrcsd|_tj|dS)zlLog the specified logging record. :param logging.LogRecord record: Record to be formatted FN)rfrJemit)rOrQ)rPr)r*rgszTempHandler.emitc sH|jz0|jj|jr&tj|jd|_tjWd|jXdS)zuClose the handler and the temporary log file. The temporary log file is deleted if it wasn't used. FN) acquirerIr6rfshutilZrmtreererJrelease)rO)rPr)r*r6s  zTempHandler.close) rTrUrVrWrKrrXrgr6rZr)r))rPr*rs   r)r'argskwargsrc Os"zt||Wd|jddXdS)aA 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 NT)r.)r;r5)r'rkrlr)r)r*r!.sr!)exc_type exc_valuetracerrrrc s|||f}fdd}|s(t|t rT|tkrDtjdtjdtjd|dntjd|dt|tj rtjt ||tjdt j |rt |j d\}}} tj| n tj||} tjd j| j|d S) aaLogs 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 bool quiet: True if Certbot is running in quiet mode :param str log_path: path to file or directory containing the log csrtjdStS)N)r"exitexit_with_advicer))rrr)r*]sz,post_arg_parse_except_hook..zExiting due to user request.rpzExiting abnormally:)exc_infozAn unexpected error occurred:z:: rRN) issubclass ExceptionKeyboardInterruptr8rHr"rqrr rFrYrZ is_acme_error partition tracebackformat_exception_onlyrDrstrip) rmrnrorrrrtZ exit_func_Zexc_stroutputr))rrr*r;Js$        r;)rrcCsHd}tjj|r"|d|d7}n|d|d7}|d7}tj|dS)zPrint a link to the community forums, the debug log path, 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 zSAsk for help or search for solutions at https://community.letsencrypt.org. See the z logfiles in  zlogfile z+or re-run Certbot with -v for more details.N)r r$isdirr"rq)rr=r)r)r*rr}s  rr)/rWrrZlogging.handlersrir"rdrytypesrZtypingrrrrrZacmerZcertbotr r r Zcertbot._internalr Zcertbot.compatr rrrrTr8r+ZNamespaceConfigr?rYr^r1Z StreamHandlerrr2rrr! BaseExceptionr_r;rrr)r)r)r*sF             (4 -01