ϪfpZddlZddlZddlZddlZddlZddlZddlZddlmZddl m Z m Z m Z ddl mZmZddlmZmZddlmZddlmZddlmZdd lmZmZmZmZmZmZdd l m!Z!m"Z"m#Z#Gd d Z$Gd de$Z%Gdde$Z&GddZ'GddZ(dZ)d%dZ*dZ+dZ,GddZ-dZ.dZ/GddZ0Gdd ejbe0Z2d!Z3d"Z4d#Z5d$Z6y)&N) attrgetter) copyrightloggerplugin)reactorsservice) NoSuchReactorinstallReactor)defer)_ISupportsExitSignalCapturing)sob)failureloglogfileruntimeusageutil)namedAny namedModulequalceZdZdZdZdZy)_BasicProfilerz @ivar saveStats: if C{True}, save the stats information instead of the human readable format @type saveStats: C{bool} @ivar profileOutput: the name of the file use to print profile data. @type profileOutput: C{str} c ||_||_yN) profileOutput saveStats)selfrrs 9/usr/lib/python3/dist-packages/twisted/application/app.py__init__z_BasicProfiler.__init__%s*"c2d|d|}|dz }t|)z Helper method to report an import error with a profile module. This has to be explicit because some of these modules are removed by distributions due to them being non-free. zFailed to import module : z This is most likely caused by your operating system not including the module due to it being non-free. Either do not use the option --profile, or install the module; your operating system vendor may provide it in a separate package. ) SystemExit)rmoduleess r_reportImportErrorz!_BasicProfiler._reportImportError)s1 'vhb 4   mr N)__name__ __module__ __qualname____doc__rr'r rrrs# r rceZdZdZdZy) ProfileRunnerz1 Runner for the standard profile module. c@ ddl}j}|j |j |j r|j|jytjt|jdc}t_ |j|tjct_ }|jy#t$r}|jd|Yd}~d}~wwxYw#|tjct_ }|jwxYw)z: Run reactor under the standard profiler. rNprofilea)r0 ImportErrorr'Profileruncallrunr dump_statsrsysstdoutopen print_statsclose)rreactorr0r%ptmps rr5zProfileRunner.run>s 2  OO  '++ >> LL++ ,!jj$t/A/A3*GOC  "%szz C  2  # #Iq 1 1 2#&szz C s#C C/ C,C''C,/.DNr(r)r*r+r5r,r rr.r.9s r r.ceZdZdZdZy)CProfileRunnerz) Runner for the cProfile module. c ddl}ddl}j }|j |j |jr|j|jyt|jd5}j||}|j|jd|jdddy#t$r}|jd|Yd}~d}~wwxYw#1swYyxYw)z: Run reactor under the cProfile profiler. rNcProfilew)stream)rCpstatsr2r'r3r4r5rr6rr9Stats strip_dirs sort_statsr:)rr<rCrGr%r=rEr&s rr5zCProfileRunner.runYs 3       '++ >> LL++ ,d((#. &LL6L2  R      3  # #J 2 2 3  s$C3AC) C& C!!C&)C2Nr?r,r rrArATs  r rAc eZdZdZeedZdZy) AppProfilerz Class which selects a specific profile runner based on configuration options. @ivar profiler: the name of the selected profiler. @type profiler: C{str} )r0cprofilecX|jdd}|jdd}|jddj|_|j|jvr2|j|j||}|j|_yt d|j)N savestatsFr0profilerrMzUnsupported profiler name: )getlowerrP profilersr5r#)roptionsrrrPs rrzAppProfiler.__init__zsKK U3  It4  J ;AAC ==DNN *4t~~dmm4]INH||DH:4==/JK Kr N)r(r)r*r+r.rArSrr,r rrLrLos*~FILr rLc2eZdZdZdZdZdZdZdZdZ y) AppLoggera] An L{AppLogger} attaches the configured log observer specified on the commandline to a L{ServerOptions} object, a custom L{logger.ILogObserver}, or a legacy custom {log.ILogObserver}. @ivar _logfilename: The name of the file to which to log, if other than the default. @type _logfilename: C{str} @ivar _observerFactory: Callable object that will create a log observer, or None. @ivar _observer: log observer added at C{start} and removed at C{stop}. @type _observer: a callable that implements L{logger.ILogObserver} or L{log.ILogObserver}. Ncf|jdd|_|jdxsd|_y)zE Initialize an L{AppLogger} with a L{ServerOptions}. rrN)rQ _logfilename_observerFactoryrrTs rrzAppLogger.__init__s-$KK 26 ' H 5 =r c|j|j}nB|jtjd}| |jtjd}||j }||_tjj|j r|j g}ntjj|j r!tj|j g}n> %  % % 4 4T^^ D!DN &r ) r(r)r*r+rbrrnrjrarr,r rrVrVs("I>0d 3"r rVcd}d}d}|tj_|tj_|tj_y)Nc|j|jddlm}|j d|j y)Nrrp)clear_all_breaks set_continuertr< callLaterr)rargr<s rdo_stopzfixPdb..do_stops4  ,!W\\*r ctdy)NzEstop - Continue execution, then cleanly shutdown the twisted reactor.)printrs r help_stopzfixPdb..help_stops  V r c.tjdy)Nr)os_exitrs rset_quitzfixPdb..set_quits   r )pdbPdbrrr)rrrs rfixPdbrs6  CGGCGGO!CGGr c|ddlm} |dr||j|y|dr|t_|t_t jdk(rJtjtjdtjtjdttj|jy|jyy#t$rnd }|d r|}ntd d }d } t!j"||j%|r*|j'Yy#|r|j'wwxYwYywxYw)aN Start the reactor, using profiling if specified by the configuration, and log any error happening in the process. @param config: configuration of the twistd application. @type config: L{ServerOptions} @param oldstdout: initial value of C{sys.stdout}. @type oldstdout: C{file} @param oldstderr: initial value of C{sys.stderr}. @type oldstderr: C{file} @param profiler: object used to run the reactor with profiling. @type profiler: L{AppProfiler} @param reactor: The reactor to use. If L{None}, the global reactor will be used. Nrrpr0debugposixc*tjSrr set_traceargss rz'runReactorWithLogging..+s CMMOr c*tjSrrrs rrz'runReactorWithLogging..,s 3==?r FnodaemonzTWISTD-CRASH.logr1Tfile)rtr<r5r7r8stderrr platformTypesignalSIGUSR2SIGINTrrr4 BaseExceptionr9 traceback print_excflushr;)config oldstdout oldstderrrPr<r;rs rrunReactorWithLoggingr s (, ) # W% G_"CJ"CJ##w. fnn.KL fmm-JK H KK $ KKM$   * D*C0DE    T * JJL  u s5CB!CC!E9&D3E3EE Ec2|rtjdSy)Nz Passphrase: )getpassneededs r getPassphraser@s ~..r c2|rtjdSy)NzEncryption passphrase: )r getPasswordrs rgetSavePassphraserGs  9::r c<eZdZdZeZeZdZdZ dZ dZ dZ dZ y) ApplicationRunnera An object which helps running an application based on a config object. Subclass me and implement preApplication and postApplication methods. postApplication generally will want to run the reactor after starting the application. @ivar config: The config object, which provides a dict-like interface. @ivar application: Available in postApplication, but not preApplication. This is the application object. @ivar profilerFactory: Factory for creating a profiler object, able to profile the application if options are set accordingly. @ivar profiler: Instance provided by C{profilerFactory}. @ivar loggerFactory: Factory for creating object responsible for logging. @ivar logger: Instance provided by C{loggerFactory}. cj||_|j||_|j||_yr)rprofilerFactoryrP loggerFactoryr)rrs rrzApplicationRunner.__init__hs- ,,V4 ((0 r c|j|j|_|jj |j|j |jj y)z& Run the application. N)preApplicationcreateOrGetApplicationrkrrnpostApplicationrrs rr5zApplicationRunner.runmsU 668 $**+  r c|ddlm}t|j|||j|t j |r|j|_yd|_y)z Run the reactor with the given configuration. Subclasses should probably call this from C{postApplication}. @see: L{runReactorWithLogging} Nrrp)rtr<rrrPr rc _exitSignal)rr<rrs r startReactorzApplicationRunner.startReactorysI ? 0dkk9iPWX ( 3 3G <&22D #D r ct)z Override in subclass. This should set up any state necessary before loading and running the Application. NotImplementedErrorrs rrz ApplicationRunner.preApplications "##r ct)z Override in subclass. This will be called after the application has been loaded (so the C{application} attribute will be set). Generally this should start the application and run the reactor. rrs rrz!ApplicationRunner.postApplications "##r c|jjr|jj|jj}|j|jj}t j |j}|j||St|jd}t|j|}|S)a Create or load an Application based on the parameters found in the given L{ServerOptions} instance. If a subcommand was used, the L{service.IServiceMaker} that it represents will be used to construct a service to be added to a newly-created Application. Otherwise, an application will be loaded based on parameters in the config. encrypted) r subCommand loadedPlugins makeService subOptionsr ApplicationtapnamesetServiceParentrgetApplication)rplgserrk passphrases rrz(ApplicationRunner.createOrGetApplications ;; ! !++++DKK,B,BCC//$++"8"89C!--ckk:K   -'t{{;'?@J(jAKr N)r(r)r*r+rLrrVrrr5rrrrr,r rrrNs1,"OM1 $ $$r rcjdDcgc]}||s |||fc}d}|dddij|d|d}} tjd|ztj|||}tjd|Scc}w#t $r}d|z}t |tr|jdd k(r|d z }tjtj tj|tjtjd |zd zYd}~Sd}~wwxYw) N)pythonsourcerrrpicklerz Loading %s...zLoaded.zFailed to load application: %srkaN Could not find 'application' in the file. To use 'twistd -y', your .tac file must create a suitable object (e.g., by calling service.Application()) and store it in a variable named 'application'. twistd loads your .tac file and scans the global variables for one of this name. Please read the 'Using Application' HOWTO for details. r )rQrmsgrloadApplication Exception isinstanceKeyErrorrrrrdeferrr7exit)rrtr&filenamestylerkr%s rrrs!=KA&)QKANAdVX.221Q41>eH" (*+--hzJ    + L " ,q 0 a "qvvayM'A  A -    D!! "s# B BAB D2BD--D2ctjtjDcgc]}|jc}Scc}wr)r CompleteListrgetReactorTypes shortName)rs r_reactorActionrs.   H4L4L4NOqq{{O PPOsAceZdZdZej deiZejZ e e jZdZdZeZy)ReactorSelectionMixinz Provides options for selecting a reactor to install. If a reactor is installed, the short name which was used to locate it is saved as the value for the C{"reactor"} key. r<) optActionsc Lt|jtd}d}|D]O} t|j|j j d|jdd|jdQ|rQ|j j d|j j d |j j |td #t$rA}|dj|j|j|jd z }Yd }~d }~wwxYw) zE Display a list of possibly available reactor names. rkeyrXz z<4 rz !{:<4} {} ({}) rNz. reactors not available on this platform: ) sorted_getReactorTypesrr moduleName messageOutputwriter descriptionr2formatrr#)rrctsnotWorkingReactorsrr%s ropt_help_reactorsz'ReactorSelectionMixin.opt_help_reactorssd++-:k3JK A ALL)""((4 B/?r!--PR)ST      $ $T *    $ $E     $ $%7 8m "&=&D&DKKMMFF1I'" sA C D#"7DD#c t|||d<y#t$rd|d}tj|t$r }d|d}tj|d}~wwxYw)zX Which reactor to use (see --help-reactors for a list of possibilities) r<z'The specified reactor does not exist: 'z:'. See the list of available reactors with --help-reactorsz9The specified reactor cannot be used, failed with error: z9. See the list of available reactors with --help-reactorsN)r r r UsageErrorr)rrrr%s r opt_reactorz!ReactorSelectionMixin.opt_reactorsx ( 9 % (DO (&/1  ""3' ' (&')  ""3' '  (s ,AAAN)r(r)r*r+r CompletionsrcompDatar7r8r staticmethodrrrrropt_rr,r rrrsK!u  Y,GHHJJM#H$<$<=2(8 Er rc eZdZdZgdgdgdgZgdgdgddd d d d j ejzggd gdgdgdgZe jdge jde jde jde jdZ eej ZdZdZeZdZddZdZedZy ) ServerOptionszQtwistd reads a twisted.application.service.Application out of a file and runs it.)rONzBsave the Stats object rather than the text output of the profiler.)no_saveozdo not save state on shutdown)rr%z(The specified tap/aos file is encrypted.)rlNz%log to a specified file, - for stdout)rNNzA fully-qualified name to a log observer factory to use for the initial log observer. Takes precedence over --logfile and --syslog (when available).)r0r=Nz7Run in profile mode, dumping results to specified file.rPNrMz!Name of the profiler to use (%s).z, )rfz twistd.tapzread the given .tap file)ryNz:read an application from within a Python file (implies -o))rr&Nz2Read an application from a .tas file (AOT format).)rundird.z-Change to a supplied directory before running)rrrz*.tapz *.(tac|py)z*.tas)rrrr )mutuallyExclusivercd|d<d|vr |d|_ntj|_tjj |y)NFrr8)r8r7rOptionsr)rr1kws rrzServerOptions.__init__Xs:W r>X,DK**DK t$r c`tjdtjd|d<y)z Run the application in the Python Debugger (implies nodaemon), sending SIGUSR2 will drop into debugger TrN)r setDebuggingrstartDebugModers r opt_debugzServerOptions.opt_debug`s' 4  W r ctjtj ddl}|jtjy#t $rYywxYw)z Print an insanely verbose log of everything that happens. Useful when debugging freezes or locks in complex code. rN)r7settracerspewer threadingr2)rrs ropt_spewzServerOptions.opt_spewksD T[[!   4;;'   sA AAcx|tjddxsdg}tjj ||y)Nrz--help)r7argvrr parseOptionsr[s rrzServerOptions.parseOptionsws1 ?hhqrl0xjG ""41r c|js|drd|d<|d t|d|d<yy#t$r-}tjdj |d|d}~wwxYw)NrTrrz%Logger '{}' could not be imported: {})rrrrrr)rr%s r postOptionszServerOptions.postOptions|sx ??d8n"DO > % !)$x.!9X & &&;BB4>STU s0 A&(A!!A&c#K|jtj}i|_t |t dD]:}||j|j <|j d|fd|jf<yw)Nrrc"|jSr)rT)plugs rrz+ServerOptions.subCommands..s $,,.r ) _getPluginsr IServiceMakerrrrrr)rpluginsr!s r subCommandszServerOptions.subCommandssx""7#8#897 9(=> D/3D  t|| , !0    sA;A=r)r(r)r*longdescoptFlagsjoinrLrS optParametersrr CompleteFiles CompleteDirsrrr getPluginsr"rropt_brrrpropertyr%r,r rrrs !  :FH H      /$))Ks_))&&*EK[!**73"7+J[!&&J&Or c ddlm}tj|j |r3t j |}|jdd|jd|jddtj|jy)Nrrpaftershutdownbefore) rtr<rIService startServicer r6addSystemEventTriggerr8 stopService)rkr8r<r=s rstartApplicationrGsm( [!..0   [ )%%gz166:N !!*g..{;GGr ctj|tjtjtj|y)a Force the application to terminate with the specified signal by replacing the signal handler with the default and sending the signal to ourselves. @param sig: Signal to use to terminate the process with C{os.kill}. @type sig: C{int} N)rSIG_DFLrkillgetpid)sigs r_exitWithSignalrMs* MM#v~~&GGBIIKr )NN)7rrrrr7rreoperatorrtwistedrrrtwisted.applicationrrtwisted.application.reactorsr r rtr twisted.internet.interfacesr twisted.persistedr twisted.pythonrrrrrrtwisted.python.reflectrrrrr.rArLrVrrrrrrrrrrr5r>rGrMr,r rrVs  --1G"E!FF>><N6 ^ 6LL,o"o"d",0fhhV2QBBJzEMM#8zz P  r