M/e<ndZddlZddlZddlZddlZddlZddlZddlZddlm Z ddl m Z ddl m Z ddl m Z ddl mZddl mZdd l mZdd lmZdd lmZdd lmZdd lmZddlmZdd lmZddlmZdZdZej>e Z!d+dZ"dejFddfdZ$dejFde%de%deejLe%ffdZ'GddejPZ)GddejTjVZ+GddejPZ,de+d e d!e ddfd"Z-d#ee.d$e.d%e d&e/d'e/d(e%ddfd)Z0d(e%ddfd*Z1y),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)sreturnct}|jtjt|j tj t|}t}|jtjt|j tjtj}|j tj |j||j|tjtjt!j"t$|dt&j(vdt&j(vxsdt&j(v|j*t&_y)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 atexit_registershutdown functoolspartialpre_arg_parse_except_hooksysargvpath excepthook) temp_handlermemory_handlerstream_handler root_loggers 7/usr/lib/python3/dist-packages/certbot/_internal/log.pypre_arg_parse_setupr17s  =Lg//9:'--("<0N)+N 1 1' :;GOO,##%K'>*>* ))*&&!>388#388#7tsxx'7"" $CNconfigct|dt\}}tj}dx}}|jD](}t |t r|}t |ts'|}*d}||J||j||j|t|dd}|j||jd|j|r|j|jrtj } nV|j"*tj$t'|j"dzz } n tj$|j(dzz } |j+| t,j/d| |jst1d |t2j4 t7j8t:|j.|j| t2_y) 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" removeHandlergetattr setTargetflushcloserrQUIET_LOGGING_LEVEL verbose_levelDEFAULT_LOGGING_LEVELint verbose_countrloggerrprintr(stderrr%r&post_arg_parse_except_hookr+) r3 file_handler file_pathr/r-stderr_handlerhandlermsgr,levels r0post_arg_parse_setuprQbs5!8-L)##%K&**N^''% g3 4$N  /$N % FC  %.*DIcI D<(n->8T:L\*t$ ||--    )//#f6J6J2Kb2PP//&2F2F2KKE" LL/7 << $YK0szzB&&"ll&,,DCNr2logfilefmtc@tj|jd|jtj j |j|} tjj|d|j}|j!|j#tj$tj&|}|j)|||fS#t$r7}tjtjj|d}~wwxYw)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)maxBytes backupCountN)rS)r set_up_core_dirlogs_dirstrict_permissionsrr*joinrr;RotatingFileHandlermax_log_backupsIOErrorr Error PERM_ERR_FMTformat doRolloverrrrr)r3rRrS log_file_pathrNerrorhandler_formatters r0r:r:s %1J1JKGGLL':M<""66 G..70  W]]#))c2 *+ M !! <ll4,,33E:;;rirAr5)ror5rps r0rAzMemoryHandler.closes!x(   r2r7c(|rt|yy)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)rir@)ror7rps r0r@zMemoryHandler.flushs  GMO r2rqcy)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 F)rorqs r0 shouldFlushzMemoryHandler.shouldFlushsr2)Ni'rN)F)rxryrzr{rrHandlerrErjrAboolr@r|rr~rs@r0rrsg <@!&2x822+/2  4 D  '"3"3  r2rcXeZdZdZdfd Zdej ddffd Zdfd ZxZ 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 rNctjd|_tjj |jd|_t j|jdd}t|%||d|_ y)Nz certbot-log-)prefixlogwi)modechmodT) tempfilemkdtemp_workdirrr*rZr safe_openrirj_deleterns r0rjzTempHandler.__init__ s^ ((? GGLL6  5A    r2rqc2d|_t| |y)zlLog the specified logging record. :param logging.LogRecord record: Record to be formatted FN)rriemit)rorqrps r0rzTempHandler.emits    Vr2c&|j |jj|jrt j |j d|_t| |jy#|jwxYw)zuClose the handler and the temporary log file. The temporary log file is deleted if it wasn't used. FN) acquirerfrArshutilrmtreerrirelease)rorps r0rAzTempHandler.close s_   KK   || dmm, DL GMO LLNDLLNs AA>>Br) rxryrzr{rjrr|rrAr~rs@r0rrs07,,r2rr-argskwargscn t|i||jdy#|jdwxYw)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 Tr6N)rJr@)r-rrs r0r'r'3s9()"D3F3 4(4(s 4exc_type exc_valuetracerrrc@|||f}d fd }|st|tsntjtj ksJ|t ur*tjdtjdtjd|n tjd|t|tjr%tjt||tjdtj |rAtjt#j$t'tj|nHt)j*||}tjdj-|j/|y) 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 NcLrtjdyty)N)r(exitexit_with_advice)rrsr0 exit_funcz-post_arg_parse_except_hook..exit_funcbs  HHQK X &r2zExiting due to user request.rzExiting abnormally:)exc_infozAn unexpected error occurred:rsr) issubclass ExceptionrrBrERRORKeyboardInterruptrGrcr(rrr r^r}r is_acme_error display_utildescribe_acme_errorr tracebackformat_exception_onlyrZrstrip) rrrrrrrroutputs `` r0rJrJOs")U+H' Jx3,, === ( ( LL7 8 HHQK *X > *X > h - LLY ( K 45  ! !) , LL99$x~~y:YZ [44XyIF LL//1 2 Kr2cd}tjj|r |d|dz }n |d|dz }|dz }tj|y)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(r)rrOs r0rrsU C ww}}X hZq)) (1%% 88CHHSMr2r)2r{r%rlogging.handlersrr(rrtypesrtypingrrrrrr acmer certbotr r r certbot._internalrcertbot._internal.displayrcertbot.compatrrrr!rxrGr1NamespaceConfigrQr}rr: StreamHandlerrr;rrr' BaseExceptionrrJrrr2r0rs}. !':  ;   8 $($V1D!>!>1D41Dh"=#@#@"3" #"(-goos.B(C"@700@*G$$22*Z-'''-`)m)%()47)<@)82m)<22&32<@2IM2),2152jstr2