a }|g<@sdZddlZddlZddlZddlZddlZddlZddlZddlm Z ddl m Z ddl m Z ddl m Z ddl mZddl mZdd l mZdd lmZdd lmZdd lmZdd lmZddlmZdd lmZddlmZdZdZee Z!ddddZ"ej#ddddZ$ej#e%e%eej&e%fdddZ'Gdddej(Z)Gdddej*j+Z+Gdd d ej(Z,e+e e dd!d"d#Z-ee.e.e e/e/e%dd$d%d&Z0e%dd'd(d)Z1dS)*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)cast)IO)Optional)Tuple)Type)messages) configuration)errors)util) constants)osz %(message)sz.%(asctime)s:%(levelname)s:%(name)s:%(message)sreturncCst}|tt|tjt|}t}|tt |tj t }|tj| || |t tjtjt|dtjvdtjvpdtjv|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-qdebugquietlog_pathN) TempHandler setFormatterlogging FormatterFILE_FMTsetLevelDEBUG MemoryHandlerColoredStreamHandlerCLI_FMTWARNING getLogger addHandlerr Zatexit_registerZshutdown functoolspartialpre_arg_parse_except_hooksysargvpath excepthook) temp_handlermemory_handlerZstream_handler root_loggerr,9/usr/lib/python3.9/site-packages/certbot/_internal/log.pypre_arg_parse_setup7s$      r.)configrc Cs<t|dt\}}t}d}}|jD]"}t|tr:|}q&t|tr&|}q&d}|dur^|dusfJ|||| |t |dd}| ||j dd| |r| |jrtj} n0|jdurtjt|jd} ntj|jd} || td| |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!targetTforce zRoot logging level set at %dzSaving debug log to )filer)setup_log_file_handlerrrr handlers isinstancerrr!Z removeHandlergetattrZ setTargetflushcloserr QUIET_LOGGING_LEVELZ verbose_levelZDEFAULT_LOGGING_LEVELintZ verbose_countrloggerrprintr%stderrr"r#post_arg_parse_except_hookr() r/Z file_handlerZ file_pathr+r*Zstderr_handlerhandlermsgr)levelr,r,r-post_arg_parse_setupbsB             rD)r/logfilefmtrc Cst|jd|jtj|j|}ztjj |d|j d}Wn6t yp}zt tj|WYd}~n d}~00||tjtj|d}||||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 ii)ZmaxBytesZ backupCountN)rF)r Zset_up_core_dirZlogs_dirZstrict_permissionsrr'joinrr6ZRotatingFileHandlerZmax_log_backupsOSErrorr ErrorZ PERM_ERR_FMTformatZ doRolloverrrrr)r/rErFZ log_file_pathrAerrorZhandler_formatterr,r,r-r5s (   r5csDeZdZdZd 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)streamrcs4t||durtjn||_tj|_dS)N) super__init__r%r?isattycoloredrr red_levelselfrL __class__r,r-rNs  zColoredStreamHandler.__init__recordrcs6t|}|jr2|j|jkr2dtj|tjfS|S)zFormats the string representation of record. :param logging.LogRecord record: Record to be formatted :returns: Formatted, string representation of record :rtype: str ) rMrJrPZlevelnorQrGr Z ANSI_SGR_REDZANSI_SGR_RESET)rSrWoutrTr,r-rJs zColoredStreamHandler.format)N) __name__ __module__ __qualname____doc__rrrNr LogRecordstrrJ __classcell__r,r,rTr-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')r0capacityrcstj||ddS)N)r0)rMrN)rSr0rbrTr,r-rNszMemoryHandler.__init__rcst|d}t||_dS)z;Close the memory handler, but don't set the target to None.r0N)r8rMr:r0)rSr0rTr,r-r:s  zMemoryHandler.closeF)r2rcs|rtdS)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)rMr9)rSr2rTr,r-r9s zMemoryHandler.flushrVcCsdS)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,rSrWr,r,r- shouldFlushs zMemoryHandler.shouldFlush)Nra)F)rZr[r\r]rrHandlerr<rNr:boolr9r^rdr`r,r,rTr-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 NrcsLtjdd|_tj|jd|_tj|jddd}t ||d|_ dS)Nz certbot-log-)prefixlogwi)modechmodT) tempfileZmkdtemp_workdirrr'rGr Z safe_openrMrN_deleterRrTr,r-rN s  zTempHandler.__init__rVcsd|_t|dS)zlLog the specified logging record. :param logging.LogRecord record: Record to be formatted FN)rnrMemitrcrTr,r-roszTempHandler.emitcsP|z8|j|jr&t|jd|_tW|n |0dS)zuClose the handler and the temporary log file. The temporary log file is deleted if it wasn't used. FN) acquirerLr:rnshutilrmtreermrMrelease)rSrTr,r-r: s   zTempHandler.close) rZr[r\r]rNrr^ror:r`r,r,rTr-rs   r)r*argskwargsrc Os2zt|i|W|jddn|jdd0dS)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 Tr1N)r@r9)r*rtrur,r,r-r$3sr$)exc_type exc_valuetracerrrrc s|||f}ddfdd }|s,t|tshtjtjks.exit_funczExiting due to user request.ryzExiting abnormally:)exc_infozAn unexpected error occurred:rX) issubclass Exceptionr r;rZERRORKeyboardInterruptr=rKr%rzrr rIr_r Z is_acme_error display_utilZdescribe_acme_errorr tracebackformat_exception_onlyrGrstrip) rvrwrxrrrr~r}outputr,r|r-r@Os$       r@)rrcCsHd}tj|r"|d|d7}n|d|d7}|d7}t|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)rr'isdirr%rz)rrBr,r,r-r{s  r{)2r]r"rZlogging.handlersrqr%rlrtypesrtypingrrrrrrZacmer Zcertbotr r r Zcertbot._internalr Zcertbot._internal.displayrZcertbot.compatrrrr rZr=r.ZNamespaceConfigrDr_rer5Z StreamHandlerrr6rrr$ BaseExceptionrfr@r{r,r,r,r-sP               +4  -0  5