a >h1@sdZddlZddlZddlZddlZddlZddlZddlmZmZddl Z ddl Z ddl Z ddl Z ddl m Z ddlmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZddlm Z m!Z!ddZ"d d Z#d d Z$e%d ej&Z'dZ(GdddZ)GdddZ*GdddZ+GdddZ,GdddZ-Gddde-Z.Gddde-Z/Gddde-Z0Gdd d e-Z1Gd!d"d"e-Z2Gd#d$d$e-Z3Gd%d&d&e-Z4Gd'd(d(e-Z5Gd)d*d*e-Z6d-d+d,Z7dS).z; This exports methods available for use by plugins for sos N)timesleep)datetime)sos_get_command_output import_modulegrepfileobjtail is_executableTIMEOUT_DEFAULT path_exists path_isdir path_isfile path_islinklistdir path_joinboldfile_is_binaryrecursive_dict_values_by_key)P_FILEP_LINKcCs^zBt|&}t||tjWdWS1s60YWntyXgYS0dS)z=Return a list of all non overlapping matches in the string(s)N)rrefindallread MULTILINEAttributeError)regexfnamefr?/usr/lib/python3.9/site-packages/sos/report/plugins/__init__.py regex_findall&s  8 r!cCs@tdd|}tdd|}tdd|d}|d|}|S) Nz^/(usr/|)(bin|sbin)/z [^\w\-\.\/]+_/.z ._-r)rsubstrip)commandname_maxZ manglednamerrr _mangle_command/s  r*cCsLtjdftjdftjdftjdfg}|D]}|d|jr(|dSq(dS)z return a string indicating the type of special node represented by the stat buffer st (block, character, fifo, socket). z block devicezcharacter devicez named pipeZsocketrr")statS_ISBLKS_ISCHRS_ISFIFOS_ISSOCKst_mode)stZ_typestrrr _node_type7sr4z!----(?:-| )BEGIN.*?----(?:-| )ENDz -----SCRUBBEDc@seZdZdZdZdZgZgZgZgZ gZ d%ddZ ddZ d d Z d d Zd dZddZddZddZddZddZddZddZddZdd Zd!d"Zdgggggifd#d$ZdS)& SoSPredicateaA class to implement collection predicates. A predicate gates the collection of data by an sos plugin. For any `add_cmd_output()`, `add_copy_spec()` or `add_journal()` call, the passed predicate will be evaulated and collection will proceed if the result is `True`, and not otherwise. Predicates may be used to control conditional data collection without the need for explicit conditional blocks in plugins. :param owner: The ``Plugin`` object creating the predicate :type owner: ``Plugin`` :param dry_run: Is sos running in dry_run mode? :type dry_run: ``bool`` :param kmods: Kernel module name(s) to check presence of :type kmods: ``list``, or ``str`` of single name :param services: Service name(s) to check if running :type services: ``list``, or ``str`` of single name :param packages: Package name(s) to check presence of :type packages: ``list``, or ``str`` of single name :param cmd_outputs: Command to run, with output string to check :type cmd_outputs: ``list`` of ``dict``s, or single ``dict`` taking form {'cmd': , 'output': } :param arch: Architecture(s) that the local system is matched against :type arch: ``list``, or ``str`` of single architecture :param required: For each parameter provided, should the checks require all items, no items, or any items provided :type required: ``dict``, with keys matching parameter names and values being either 'any', 'all', or 'none. Default 'any'. NFr"c s dd|jd}|j}|r.fdd|Dn|}|dd|d7}|j}|rdfd d|Dn|}|d d|d7}|j}|rfd d|Dn|}|d d|d7}fd d|jD}|dd|d7}|j} |rfdd| Dn| } |dd| d7}|||S)zxReturn a string representation of this SoSPredicate with optional prefix, suffix and value quoting. z"%s"zdry_run=, csg|] }|qSrr).0kZquotesrr z&SoSPredicate.__str..zkmods=[,z], csg|] }|qSrr)r7sr9rr r:r;z services=[csg|] }|qSrrr7pr9rr r:r;z packages=[c sBg|]:}ddd|dddd|dd qS)z{ cmd: r6outputz }r)r7Z cmdoutputr9rr r:s  z cmdoutputs=[csg|] }|qSrr)r7ar9rr r:r;zarches=[])dry_runkmodsjoinservicespackages cmd_outputsarch) selfquoteprefixsuffixZpstrrFrHZpkgsZ cmdoutputsZarchesrr9r Z__strs& zSoSPredicate.__strcCs|S)zReturn a string representation of this SoSPredicate. "dry_run=False, kmods=[], services=[], cmdoutputs=[]" _SoSPredicate__strrLrrr __str__szSoSPredicate.__str__cCs|jddddS)zReturn a machine readable string representation of this SoSPredicate. "SoSPredicate(dry_run=False, kmods=[], services=[], cmdoutputs=[])" Tz SoSPredicate())rMrNrOrPrRrrr __repr__szSoSPredicate.__repr__cCsD|dkrt|S|dkr t|S|dkr2t| Std|dS)zHelper to simplify checking the state of the predicate's evaluations against the setting of the required state of that evaluation anyallnonez7predicate requires must be 'any', 'all', or 'none' not N)rVrW ValueError)rLitemsrequiredrrr _check_required_states z"SoSPredicate._check_required_statecCs8|j|}|dkr$|j||n|j||dS)zHelper to direct failed predicates to provide the proper messaging based on the required check type :param test: The type of check we're doing, e.g. kmods, arch :param item: The string of what failed rXN)r[_failedappend _forbidden)rLtestitemZ_reqrrr _failed_or_forbiddens z!SoSPredicate._failed_or_forbiddencCs^|jr|jdrdSg}|jD]*}|j|}|||s |d|q |||jdS)Nallow_system_changesTrF)rF_owner get_optionis_module_loadedr^rbr\r[)rLZ_kmodskmodresrrr _eval_kmodss   zSoSPredicate._eval_kmodscCsR|js dSg}|jD]*}|j|}|||s|d|q|||jdS)NTrH)rHrdis_service_runningr^rbr\r[)rLZ_svcssvcrhrrr _eval_servicess   zSoSPredicate._eval_servicescCsR|js dSg}|jD]*}|j|}|||s|d|q|||jdS)NTrI)rIrd is_installedr^rbr\r[)rLZ_pkgspkgrhrrr _eval_packagess   zSoSPredicate._eval_packagescCsXd|vsd|vrdSt|d}|ddkr0dS|dD]}|d|vr<dSq3r;z.SoSPredicate._report_failed..)r]rZsetrGrLmsgZ_substrkeyvalrrr _report_failed)s"zSoSPredicate._report_failedcCsNd}d}|jD]6\}}|s qt|}|||ddd|Df7}q|S)zxReturn a string informing the user that a forbidden condition exists which caused the predicate to fail r"zforbidden %s '%s' found.r6css|] }|VqdSr}rr~rrr r@r;z1SoSPredicate._report_forbidden..)r_rZrrGrrrr _report_forbidden6s"zSoSPredicate._report_forbiddencCs*|||jrdndg}d|S)z}Used by `Plugin()` to obtain the error string based on if the reason was a failed check or a forbidden check z (dry run)r" )rrrErGlstriprLrrrr report_failureCs  zSoSPredicate.report_failurecCsTt|j|j|j|j|j|jgs$dS|oR|oR| oR| oR| oR|j S)z#Predicate evaluation hook. T) rVrFrHrIrJrKrErirlrorur|rRrrr __bool__NszSoSPredicate.__bool__c s|_t|_t|_t|_t|_t|ts>|g}|_|jjdj B_ dddddd_ j fdd Dgggggd_ gggggd_dS)z-Initialise a new SoSPredicate object cmdlineoptsrV)rFrHrIrJrKcs(i|] \}}|j|kr||qSr)r[)r7r8rr[rLrr ksz)SoSPredicate.__init__..)rFrHrIrJrxN)rdlistrFrHrIrK isinstancerJcommonsrEr[updaterZr]r_) rLownerrErFrHrIrJrKr[rrr __init__\s*     zSoSPredicate.__init__)Fr"r")__name__ __module__ __qualname____doc__rdrErFrHrIrJrKrQrSrUr\rbrirlrortrur|rrrrrrrrr r5Ks4(        r5c@s eZdZdZddZddZdS) SoSCommandaA class to represent a command to be collected. A SoSCommand() object is instantiated for each command handed to an _add_cmd_output() call, so that we no longer need to pass around a very long tuple to handle the parameters. Any option supported by _add_cmd_output() is passed to the SoSCommand object and converted to an attribute. SoSCommand.__dict__ is then passed to _get_command_output_now() for each command to be collected. cKs|j|dSr})__dict__r)rLkwargsrrr rszSoSCommand.__init__cCsdddt|jDS)zIReturn a human readable string representation of this SoSCommand r6css |]\}}|d|VqdS)=Nr)r7Zparamrrrr rr;z%SoSCommand.__str__..)rGsortedrrZrRrrr rSs  zSoSCommand.__str__N)rrrrrrSrrrr rzs rc@sTeZdZdZdZdZdZdZdZdZ dgZ dZ dddZ dd Z d d Zd d ZdS) PluginOptaVThis is used to define options available to plugins. Plugins will need to define options alongside their distro-specific classes in order to add support for user-controlled changes in Plugin behavior. :param name: The name of the plugin option :type name: ``str`` :param default: The default value of the option :type default: Any :param desc: A short description of the effect of the option :type desc: ``str`` :param long_desc: A detailed description of the option. Will be used by `sos info` :type long_desc: ``str`` :param val_type: The type of object the option accepts for values. If not provided, auto-detect from the type of ``default`` :type val_type: A single type or a ``list`` of types r"NF undefinedcCsL||_||_||_||_|j|_|dur:t|tsB|g}n|jg}||_dSr}) namedefaultdesc long_descvaluerr __class__val_type)rLrrrrrrrr rs zPluginOpt.__init__cCs@d|jd|jdd|jd|jg}dd|dS) Nzname=zdesc=''zvalue=zdefault=(r6rT)rrrrrG)rLrZrrr rSs     zPluginOpt.__str__cCs|Sr})rSrRrrr rUszPluginOpt.__repr__c std|jvrt|_dStfdd|jDsg}|jD]N}|durLq>|jdkrb|dq>|jdkrx|dq>|jdkr>|d q>td |jd |j d d |dtj|_dS)Nr"c3s|]}t|VqdSr})r)r7Z_trrr rr;z&PluginOpt.set_value..boolz boolean true/false (on/off, etc)strzstring (no spaces)intzinteger valueszPlugin option 'r%z' takes r6z, not ) typerrrrVrr^ ExceptionpluginrrG)rLrZvalidr3rrr set_values,        zPluginOpt.set_value)rNr"r"N)rrrrrrZenabledrrrrrrrSrUrrrrr rs  rc@seZdZdZdZdZdZdZdZdZ dZ dZ dZ dZ dZdZeZeZdZiZiZgZdZdZdZdZddZd d Zd d Zd dZddZdddZ ddZ!e"ddZ#e"ddZ$ddZ%ddZ&e'ddZ(e'dd Z)e'd!d"Z*e'd#d$Z+d%d&Z,d'd(Z-d)d*Z.d+d,Z/d-d.Z0d/d0Z1d1d2Z2d3d4Z3d5d6Z4d7d8Z5d9d:Z6d;d<Z7d=d>Z8d?d@Z9dAdBZ:dCdDZ;dEdFZddKdLZ?ddMdNZ@ddPdQZAdRdSZBddTdUZCdVdWZDdXdYZEdZd[ZFd\d]ZGd^d_ZHd`daZIdbdcZJdddeZKdfdgZLdhdiZMdjdkZNddldmZOdndoZPdpdqZQddsdtZRdudvZSdwdxZTdydzZUd{d|ZVddd}dgddfd~dZWddd}ddddgggddf ddZXddd}ddddgddf ddZYddZZddd}ddddgddddf ddZ[dddd}d}ddddddddgdddddddfddZ\ddZ]ddZ^dddZ_ddZ`ddZadddZbddZcddgfddZddddd}d}dddddddgddddddfddZedddd}d}ddddddddgdfddZfd ddZgddZhddZid ddZjd ddZkd ddZld ddZmdddZndddZodddZpdddZqdddZrddZsddZtddZuddZvdddZwdd„ZxddĄZyddƄZzddȄZ{ddʄZ|dd̄Z}dd΄Z~ddЄZejdgfdd҄ZddԄZddքZdd؄ZddڄZdd܄ZddބZddZddZddZdddZddZddZddZddZddZddZddZddZddZddZdddZdddZdS(Plugina]This is the base class for sos report plugins. Plugins should subclass this and set the class variables where applicable. :param commons: A set of information that is shared internally so that plugins may access the same dataset. This is provided automatically by sos :type commons: ``dict`` Each `Plugin()` subclass should also subclass at least one tagging class, e.g. ``RedHatPlugin``, to support that distribution. If different distributions require different collections, each distribution should have its own subclass of the Plugin that also subclasses the tagging class for their respective distributions. :cvar plugin_name: The name of the plugin, will be returned by `name()` :vartype plugin_name: ``str`` :cvar packages: Package name(s) that, if installed, enable this plugin :vartype packages: ``tuple`` :cvar files: File path(s) that, if present, enable this plugin :vartype files: ``tuple`` :cvar commands: Executables that, if present, enable this plugin :vartype commands: ``tuple`` :cvar kernel_mods: Kernel module(s) that, if loaded, enable this plugin :vartype kernel_mods: ``tuple`` :cvar services: Service name(s) that, if running, enable this plugin :vartype services: ``tuple`` :cvar architectures: Architecture(s) this plugin is enabled for. Defaults to 'none' to enable on all arches. :vartype architectures: ``tuple``, or ``None`` :cvar profiles: Name(s) of profile(s) this plugin belongs to :vartype profiles: ``tuple`` :cvar plugin_timeout: Timeout in seconds for this plugin as a whole :vartype plugin_timeout: ``int`` :cvar cmd_timeout: Timeout in seconds for individual commands :vartype cmd_timeout: ``int`` Nrr$Fcs2g_g_t_g_d_|_g_t_g_ g_ g_ i_ |d_ |d_|d_d_|dj_|dj_i_g_djvrjdntd_j j D]}j |_qʈjD]}|_|j |j<qtfdd tjD_ !t"dS) Nr"sysrootrydevicesrsoslogZsosc3s|]}|VqdSr})is_snap_installedr7rnrRrr rLsz"Plugin.__init__..)# copied_filesexecuted_commandsr _env_varsalerts custom_textrforbidden_paths copy_pathscontainer_copy_paths copy_strings collect_cmdsoptionsrryrmanifest skip_files skip_commandsdefault_environment_tail_files_listloggingZ getLoggerrrget_default_plugin_optsrr option_listrVrrIis_snap set_predicater5)rLrZpoptoptrrRr r)sB          zPlugin.__init__cCs0tddtddtddtddtddtd dd S) Ntimeoutz7Timeout in seconds for plugin to finish all collections)rrr cmd-timeoutz4Timeout in seconds for individual commands to finishpostprocTz(Enable post-processing of collected data)rrr)rrrrRrrr rSszPlugin.get_default_plugin_optscCs||_|jdd|jdd|jdd|jdd|jdd|jdd|jdd|jd d|jd d|jd |j|jd d |jd|j|jdg|jdg|jdi|jdi|jdgdS)zPass in a manifest object to the plugin to write to :param manifest: The manifest that the plugin will add metadata to :type manifest: ``SoSManifest`` start_timer"end_timerun_timeZ setup_startZ setup_endZ setup_timeZpostproc_startZ postproc_endZ postproc_timer timeout_hitFZcommand_timeoutcommandsfilesstrings containers collectionsN)r add_fieldr cmdtimeoutZadd_list)rLrrrr set_plugin_manifestcs$zPlugin.set_plugin_manifestcCs.t|tstd||_|d|jdS)a  Specify a collection of environment variables that should always be passed to commands being executed by this plugin. :param env_vars: The environment variables and their values to set :type env_vars: ``dict{ENV_VAR_NAME: ENV_VAR_VALUE}`` z:Environment variables for Plugin must be specified by dictz0Default environment for all commands now set to N)rdict TypeErrorr _log_debugrLZenv_varsrrr set_default_cmd_environment}s z"Plugin.set_default_cmd_environmentcCs4t|tstd|d|d|j|dS)a- Add or modify a specific environment variable in the set of default environment variables used by this Plugin. :param env_vars: The environment variables to add to the current set of env vars in use :type env_vars: ``dict`` z,Environment variables must be added via dictzAdding z to default environmentN)rrrrrrrrrr add_default_cmd_environments z"Plugin.add_default_cmd_environmentcCs8|dur|jSt|ts td|j}|||S)z Get the merged set of environment variables for a command about to be executed by this plugin. :returns: The set of env vars to use for a command :rtype: ``dict`` Nz'Command env vars must be passed as dict)rrrrcopyr)rLenv_envrrr _get_cmd_environments   zPlugin._get_cmd_environmentcCsd}zn||}t||}|dur,|}nD|durT|dkrT|tkrJ|}qpt|}n|durj|dkrj|}nWdSWnty|YS0|dur|dkr|S|S)a Get the timeout value for either the plugin or a command, as determined by either the value provided via the plugin.timeout or plugin.cmd-timeout option, the global timeout or cmd-timeout options, or the default value set by the plugin or the collection, in that order of precendence. :param optname: The name of the cmdline option being checked, either 'plugin_timeout' or 'timeout' :type optname: ``str`` :param plugoptname: The name of the plugin option name being checked, either 'timeout' or 'cmd-timeout' :type plugoptname: ``str`` :param default_timeout: The timeout to default to if determination is inconclusive or hits an error :type default_timeout: ``int`` :returns: The timeout value in seconds :rtype: ``int`` Nr)rerr rY)rLZoptnameZ plugoptnameZdefault_timeout_timeoutZ opt_timeoutZ own_timeoutrrr timeout_from_optionss$     zPlugin.timeout_from_optionscCs|dd|j}|S)zReturns either the default plugin timeout value, the value as provided on the commandline via -k plugin.timeout=value, or the value of the global --plugin-timeout option. plugin_timeoutr)rr)rLrrrr rszPlugin.timeoutcCs|dd|j}|S)zReturns either the default command timeout value, the value as provided on the commandline via -k plugin.cmd-timeout=value, or the value of the global --cmd-timeout option. cmd_timeoutr)rr)rLZ _cmdtimeoutrrr rszPlugin.cmdtimeoutcCs*d|_|jdt|jdddS)NTrr) _timeout_hitrrrZnowrRrrr set_timeout_hitszPlugin.set_timeout_hitcCs|jS)ax Checks to see if the plugin has hit its timeout. This is set when the sos.collect_plugin() method hits a timeout and terminates the thread. From there, a Popen() call can still continue to run, and we need to manually terminate it. Thus, check_timeout() should only be called in sos_get_command_output(). Since sos_get_command_output() is not plugin aware, this method is handed to that call to use as a polling method, to avoid passing the entire plugin object. :returns: ``True`` if timeout has been hit, else ``False`` :rtype: ``bool`` )rrRrrr check_timeoutszPlugin.check_timeoutcCs|jr |jS|jS)zsGet the name of the plugin :returns: The name of the plugin, in lowercase :rtype: ``str`` ) plugin_namerlower)clsrrr rsz Plugin.namecCs$|jdur||n ||dSr})rdisplay_self_helpdisplay_plugin_help)rsectionrrr display_helps  zPlugin.display_helpc Csddlm}||jd|jd}z6d}|jd}|tkrP|jrP|j}|jr`||j7}Wnt yxd}Yn0| d|r|n|t |j |j |j|j|j|jgs| dnnd D]6}t||dr|j d |d d t||d dqt|dr,|j dd dd|jDd d|jrZ|j dd dd|jDd dt|dr|j dd dd|jDd d|jtjur| d|jsdS|d}| dtd|jdd|j tddd d!d"d#d$d%d"d dd&}|jD]} | j} | dus.| dkr2d'} t| jtrR| jrNd(} nd)} dd | jd"| d$| jd"} |j t j!| ||d*d d| j"r|d+} d,} |j t j!| j"| | | d-d dqdS).Nr)TERMSIZEz Plugin Information - z8 Detailed information is not available for this plugin. r"r+z z)This plugin is always enabled by default.)rIrr kernel_modsrHz Enabled by rAr6Fnewlinerz+Enabled by containers with names matching: css|] }|VqdSr}rr7crrr r8r;z-Plugin.display_plugin_help..z%Enabled with the following profiles: css|] }|VqdSr}rr>rrr r?r;verify_packagesz) Verfies packages (when using --verify): css|] }|VqdSr}rrrrr rGr;zThis plugin performs post-processing on potentially sensitive collections. Disabling post-processing may leave sensitive data in plaintext.zPlugin Optionsz/These options may be toggled or changed using 'z-k z.option_name=$valuer rz<4z Option Namez<20ZDefault<30Z Descriptionz6 z None/UnsetzTrue/Onz False/Off)widthsubsequent_indent z )rinitial_indentr)#Zsos.helpr set_titlertitle short_desc__mro__rrradd_textrVrIrrrrHrgetattrrGprofileshasattrrrr add_sectionrrrrrrtextwrapfillr)rrrmissingZ_docZ_scZtrigoptsecZ opt_indentrZ_defZ_ln_sizespacerrr rs            zPlugin.display_plugin_helpcCs|d|dtdd|d}|d|dtdd td d |d td d|d}|dtddtdd|d}ddd}|jdddd|DdddS)NzSoS Plugin Detailed Helpz;Plugins are what define what collections occur for a given z sos reporta execution. Plugins are generally representative of a single system component (e.g. kernel), package (e.g. podman), or similar construct. Plugins will typically specify multiple files or directories to copy, as well as commands to execute and collect the output of for further analysis.zPlugin EnablementzPlugins will be automatically enabled based on one of several triggers - a certain package being installed, a command or file existing, a kernel module being loaded, etc...z:Plugins may also be enabled or disabled by name using the z-e $namez or z-n $namez options respectively.zCertain plugins may only be available for specific distributions or may behave differently on different distributions based on how the component for that plugin is installed or how it operates. When using zsos help report.plugins.$pluginzY, help will be displayed for the version of the plugin appropriate for your distribution.zUsing Plugin OptionszMany plugins support additional options to enable/disable or in some other way modify the collections it makes. Plugin options are set using the z#-k $plugin_name.$option_name=$valuez syntax. Options that are on/off toggles may exclude setting a value, which will be interpreted as enabling that option. See specific plugin help sections or z sos report -lz& for more information on these optionszSee AlsozHelp for a specific $pluginz$Information on distribution policies)zreport.plugins.$pluginZpolicieszLAdditional relevant information may be available in these help sections: %srcss(|] \}}dd|d|dVqdS)rz>8rNr)r7Zsecrrrr rsz+Plugin.display_self_help..Fr)rrrr rGrZ)rrZsubsecrZseealsoZ_alsorrr r{sT     zPlugin.display_self_helpcCs d|d|ddS)Nz[plugin:z] utf-8replace)rencodedecoderrrr _format_msgs zPlugin._format_msgcCs|j||dSr})rerrorrrrrr _log_errorszPlugin._log_errorcCs|j||dSr})rZwarningrrrrr _log_warnszPlugin._log_warncCs|j||dSr})rinforrrrr _log_infoszPlugin._log_infocCs|j||dSr})rdebugrrrrr rszPlugin._log_debugcCs4|s |S|jr0||jr0|t|jdS|S)zRemove the configured sysroot from a filesystem path :param path: The filesystem path to strip sysroot from :type path: ``str`` :returns: The stripped filesystem path :rtype: ``str`` N) use_sysrootr startswithlenrLpathrrr strip_sysroots zPlugin.strip_sysrootcCs|jtjtjkS)zDetermine if the configured sysroot needs to be used :returns: ``True`` if sysroot is not `/`, else ``False`` :rtype: ``bool`` )rosr"abspathseprRrrr rszPlugin.use_sysrootcCs(|jpd}||jg}tj||kS)zCheck if sysroot is within the archive's temp directory :returns: ``True`` if sysroot is in the archive's temp directory, else ``False`` :rtype: ``bool`` r$)rarchive get_tmp_dirr$r" commonprefix)rLZ_sysrootpathsrrr tmp_in_sysroots zPlugin.tmp_in_sysrootcCst|jj|dkS)zIs the package $package_name installed? :param package_name: The name of the package to check :type package_name: ``str`` :returns: ``True`` id the package is installed, else ``False`` :rtype: ``bool`` r)r rypackage_managerZall_pkgs_by_name)rL package_namerrr rms zPlugin.is_installedcCs"|jj|}|duo |ddkS)aIs the snap package $package_name installed? :param package_name: The name of the package to check :type package_name: ``str`` :returns: ``True`` if the snap package is installed, else ``False`` :rtype: ``bool`` NZ pkg_managerZsnap)ryr,Z pkg_by_name)rLr-rnrrr rs zPlugin.is_snap_installedcCs|jj|S)zDoes the service $name exist on the system? :param name: The name of the service to check :type name: ``str`` :returns: ``True`` if service is present on the system, else ``False`` :rtype: ``bool`` )ry init_system is_servicerLrrrr r/s zPlugin.is_servicecCs|jj|S)zIs the service $name enabled? :param name: The name of the service to check :type name: ``str`` :returns: ``True if service is enabled on the system, else ``False`` :rtype: ``bool`` )ryr.Z is_enabledr0rrr is_service_enabled s zPlugin.is_service_enabledcCs|jj|S)zIs the service $name disabled? :param name: The name of the service to check :type name: ``str`` :returns: ``True`` if service is disabled on the system, else ``False`` :rtype: ``bool`` )ryr.Z is_disabledr0rrr is_service_disableds zPlugin.is_service_disabledcCs|jj|S)a Is the service $name currently running? :param name: The name of the service to check :type name: ``str`` :returns: ``True`` if the service is running on the system, else ``False`` :rtype: ``bool`` )ryr.Z is_runningr0rrr rj"s zPlugin.is_service_runningcCs|jj|dS)zReturn the reported status for service $name :param name: The name of the service to check :type name: ``str`` :returns: The state of the service according to the init system :rtype: ``str`` rp)ryr.get_service_statusr0rrr r3.s zPlugin.get_service_statuscCs|jj|S)zGet all service names matching regex :param regex: A regex to match service names against :type regex: ``str`` :returns: All service name(s) matching the given `regex` :rtype: ``list`` )ryr.get_service_namesrLrrrr r49s zPlugin.get_service_namescCs ||_dS)zSet or clear the default predicate for this plugin. :param pred: The predicate to use as the default for this plugin :type pred: ``SoSPredicate`` N) predicaterLpredrrr rDszPlugin.set_predicatecCs ||_dS)aPSet or clear the default predicate for command collection for this plugin. If set, this predecate takes precedence over the `Plugin` default predicate for command and journal data collection. :param pred: The predicate to use as the default command predicate :type pred: ``SoSPredicate`` N) cmd_predicater7rrr set_cmd_predicateLszPlugin.set_cmd_predicatecCs&|dur |S|r |jdur |jS|jS)aGet the current default `Plugin` or command predicate. :param cmd: If a command predicate is set, should it be used. :type cmd: ``bool`` :param pred: An optional predicate to pass if no command or plugin predicate is set :type pred: ``SoSPredicate`` :returns: `pred` if neither a command predicate or plugin predicate is set. The command predicate if one is set and `cmd` is ``True``, else the plugin default predicate (which may be ``None``). :rtype: ``SoSPredicate`` or ``None`` N)r9r6rLr@r8rrr get_predicateVs zPlugin.get_predicatecCs"|j||d}|durt|SdS)aTest the current predicate and return its value. :param cmd: ``True`` if the predicate is gating a command or ``False`` otherwise. :param pred: An optional predicate to override the current ``Plugin`` or command predicate. :returns: ``True`` or ``False`` based on predicate evaluation, or ``False`` if no predicate :rtype: ``bool`` r@r8NF)r<rr;rrr test_predicatels zPlugin.test_predicatecCs>|durt|}d|d|}|r0|d7}||dS)a*Log that a command was skipped due to predicate evaluation. Emit a warning message indicating that a command was skipped due to predicate evaluation. If ``kmods`` or ``services`` are ``True`` then the list of expected kernel modules or services will be included in the log message. If ``allow_changes`` is ``True`` a message indicating that the missing data can be collected by using the "--allow-system-changes" command line option will be included. :param cmd: The command that was skipped :type cmd: ``str`` :param pred: The predicate that caused the command to be skipped :type pred: ``SoSPredicate`` :param changes: Is the `--allow-system-changes` enabled :type changes: ``bool`` Nzskipped command '': z3 Use '--allow-system-changes' to enable collection.)r5rr)rLr@r8changesrrrr log_skipped_cmd}s zPlugin.log_skipped_cmdr"cCs>|js dS|d||r,td|nt}||t|S)aRemove certificate and key output archived by sos report. Any matching instances are replaced with: '-----SCRUBBED' and this function does not take a regexp or substituting string. :param cmd: The name of the binary to scrub certificate output from :type cmd: ``str`` :param desc: An identifier to add to the `SCRUBBED` header line :type desc: ``str`` :returns: Number of replacements made :rtype: ``int`` rz/Scrubbing certs and keys for commands matching r)rr _cert_replacedo_cmd_output_sub _certmatch)rLr@rrrrr do_cmd_private_subszPlugin.do_cmd_private_subc CsFd|d}t|dr|jn|}|d|d|d|d|jsHdSd}z|jD]}|d durfqT|d d kr|d |d dqTt|d|rTtj|j d|d }|d|d|j |} t ||| \} }|rT|j | |qTWnDty@} z*d} || |d | fd}WYd} ~ n d} ~ 00|S)aApply a regexp substitution to command output archived by sos This is used to obfuscate sensitive information captured by command output collection via plugins. :param cmd: The command name/binary name for collected output that needs to be obfuscated. Internally globbed with a leading and trailing `*` :type cmd: ``str`` :param regexp: A regex to match the contents of the command output against :type regexp: ``str`` or compile ``re`` object :param subst: The substitution string used to replace matches from `regexp` :type subst: ``str`` :returns: Number of replacements made :rtype: ``int`` *patternsubstituting 'z' for 'z' in commands matching 'rrNfilebinaryyesz3Cannot apply regex substitution to binary output: 'exer@cmddirzapplying substitution to '-regex substitution failed for '%s' with: '%s')r rGrrrfnmatchr$r"rGrr'Z open_filersubnr add_stringrr) rLr@regexpsubstZglobstrrG replacementsZcalledr"readablerrerrrr rCsB       zPlugin.do_cmd_output_subcsp|d|t|j|r.td|nt}fdd|jD}|D] }|d}|s\qJ||t|qJdS)aScrub certificate/key/etc information from files collected by sos. Files matching the provided pathregex are searched for content that resembles certificate, ssh keys, or similar information. Any matches are replaced with "-----SCRUBBED $desc" where `desc` is a description of the specific type of content being replaced, e.g. "-----SCRUBBED RSA PRIVATE KEY" so that support representatives can at least be informed of what type of content it was originally. :param pathregex: A string or regex of a filename to match against :type pathregex: ``str`` :param desc: A description of the replaced content :type desc: ``str`` z,Scrubbing certs and keys for paths matching rcsg|]}|dr|qSsrcpathrr7rr{rr r:r;z.Plugin.do_file_private_sub..dstpathN)rrcompiler{rBr do_file_subrD)rLZ pathregexrr file_listir"rrZr do_file_private_subs zPlugin.do_file_private_subc Cszf||}|d|d|t|drDd|d|d|jn||sTWdS|j|||}Wn^ty}zF|jtjkrd}|||nd}| |||fd}WYd }~n d }~00|S) aApply a regexp substitution to a file archived by sos report. :param srcpath: Path in the archive where the file can be found :type srcpath: ``str`` :param regexp: A regex to match the contents of the file :type regexp: ``str`` or compiled ``re`` object :param subst: The substitution string to be used to replace matches within the file :type subst: ``str`` :returns: Number of replacements made :rtype: ``int`` zsubstituting scrpath 'rrGrHz' for '%s' in 'rz-file '%s' not collected, substitution skippedrNN) _get_dest_for_srcpathrr rGr'r]OSErrorerrnoENOENTr)rLrXrRrSr"rTrVrrrr r]s*  zPlugin.do_file_subcCs,t|tr|g}|D]}||ddqdS)ae Obfuscate Basic_AUTH URL credentials in all files in the given list. Proxy setting without protocol is ignored, since that is not recommended setting and obfuscating that one can hit false positives. :param pathspecs: A filepath to obfuscate credentials in :type pathspecs: ``str`` or a ``list`` of strings zhttp(s)?://\S+:\S+@zhttp\1://******:******@N)rrdo_path_regex_sub)rLZ pathspecsr"rrr do_paths_http_sub)s zPlugin.do_paths_http_subcsNt|dst|}|jfdd|jD}|D]}||d||q2dS)a,Apply a regexp substituation to a set of files archived by sos. The set of files to be substituted is generated by matching collected file pathnames against `pathexp`. :param pathexp: A regex to match filenames within the archive :type pathexp: ``str`` or compiled ``re`` object :param regexp: A regex to match against the contents of each file :type regexp: ``str`` or compiled ``re`` object :param subst: The substituion string to be used to replace matches :type subst: ``str`` r{csg|]}|dr|qSrWrrYrZrr r:Ir;z,Plugin.do_path_regex_sub..rXN)r rr\r{rr])rLZpathexprRrSr^rIrrZr re8s   zPlugin.do_path_regex_subcCs t||Sr})r!)rLrrrrr do_regex_find_allMszPlugin.do_regex_find_allc Cst|}tjtj||}tj|}||rP|d|d|dStj|rtj tj|}tjj ||d}| r|t tj tjd}|d|d|dn|}|d|d|d ||||}|j||||r|d |d dS|j||d |d zt|WnRty}z8|jdkr||d |dWYd}~dSWYd}~n d}~00|d|d|d||kr||jo|jj} |j|| dn|d |ddS)Nskipping excluded path 'z' as symlink destination from )startzmade link target 'z' relative as 'rzcopying link 'z' pointing to 'z ' with isdir=zlink 'z' is a directory, skipping...rK)rXr[symlinkZpointsto(z3' is part of a file system loop, skipping target...znormalized link target 'z' as 'forcez&' points to itself, skipping target...)r$readlinkr"rGdirnamenormpath_is_skipped_pathrisabsrealpathrelpathrr r&pardirr r#r'add_linkrr^r,rbrcrrryZ _in_container _do_copy_path) rLrXZlinkdestdestZabsdestZrealdirZreldestr[rVrmrrr _copy_symlinkPsV          $ zPlugin._copy_symlinkc CszD||D]4}|d|d|dtj||}||q Wnty}z~|jtjksftj rd}| d|d|WYd}~dS|jtj krd}| d|d |dWYd}~dSWYd}~n d}~00dS) Nzrecursively adding 'z' from 'rzPermission deniedz _copy_dir: 'z' z)Too many levels of symbolic links copyingz _copy_dir: z ') rrr$r"rGrwrbrcEPERMZEACCESrELOOPr)rLrXrr"rVrrrr _copy_dirs"   zPlugin._copy_dircCs:|r||}|jD]}||dkr|dSqdS)NrXr[)rrr)rLrXZcopiedrrr ras    zPlugin._get_dest_for_srcpathcstfdd|jDS)Nc3s|]}t|VqdSr}rr{)r7forbidr"rr rsz,Plugin._is_forbidden_path..)rVrr!rrr _is_forbidden_paths zPlugin._is_forbidden_pathcstfdd|jjDS)Nc3s|]}t|VqdSr})rO)r7fprrr rsz3Plugin._is_policy_forbidden_path..)rVryrr!rrr _is_policy_forbidden_paths z Plugin._is_policy_forbidden_pathcCs"|jD]}t||rdSqdS)aCheck if the given path matches a user-provided specification to ignore collection of via the ``--skip-files`` option :param path: The filepath being collected :type path: ``str`` :returns: ``True`` if file should be skipped, else ``False`` TF)rrO)rLr"Z _skip_pathrrr rqs  zPlugin._is_skipped_pathcCs:t|j}t|j}|j}|j||t||dSr})r$majorst_rdevminorr1r'Zadd_nodemakedev)rLr"r2Zdev_majZdev_minmoderrr _copy_nodes  zPlugin._copy_nodecCs|jr dS||r*|d|ddS|s2|}|rD||}zt|}Wn&tyx|d|dYdS0t |j r| |dSt |j rt|tjr||s|j|dS||dSt |j s"t |j s"t|}|d|d|d|||dS|d|d|d|j d @sV|jd |n|jj|||d |j||d d dS)zCopy file or directory to the destination tree. If a directory, then everything below it is recursively copied. A list of copied files are saved for use later in preparing a report. Nskipping forbidden path 'rfailed to stat 'z creating z node at archive:'zcopying path 'z' to archive:'i$r"rlnorXr[rj)rrrrr#r$lstatrbrr,S_ISLNKr1ryS_ISDIRaccessR_OKrr'Zadd_dirr|S_ISREGr4rrQZadd_filerr^)rLrXrxrmr2Zntyperrr rwsL          zPlugin._do_copy_pathcsht|tr|g}r*fdd|D}|D]4}d|dd|vrVt|}j|q.dS)zSpecify a path, or list of paths, to not copy, even if it's part of an ``add_copy_spec()`` call :param forbidden: A filepath to forbid collection from :type forbidden: ``str`` or a ``list`` of strings csg|]}|qSr)rrYrRrr r:r;z-Plugin.add_forbidden_path..zadding forbidden path 'rrFN)rrrrrO translaterr^)rLZ forbiddenr~rrRr add_forbidden_paths  zPlugin.add_forbidden_pathc CsV||jvrRz|j||WdStyP}z||WYd}~n d}~00dS)a`Set the named option to value. Ensure the original type of the option value is preserved :param optioname: The name of the option to set :type optioname: ``str`` :param value: The value to set the option to :returns: ``True`` if the option is successfully set, else ``False`` :rtype: ``bool`` TNF)rrrr)rL optionnamererrrrr set_options  zPlugin.set_optionrcCsLd}||vrt|jd|S||jvrH|j|}|r>|jdurD|jS|S|S)amRetrieve the value of the requested option, searching in order: parameters passed from the command line, set via `set_option()`, or the global_plugin_options dict. `optionname` may be iterable, in which case this function will return the first match. :param optionname: The name of the option to retrieve the value of :type optionname: ``str`` :param default: Optionally provide a default value to return if no option matching `optionname` is found. Default 0 :returns: The value of `optionname` if found, else `default` )all_logsrcr journal_sizelog_sizersinceZverifyrN)r rrr)rLrrZglobal_optionsrrrr re2s  zPlugin.get_optioncCs|j|dSr})rr)rLrrrr _add_copy_pathsRszPlugin._add_copy_pathscCs6|D] }t||tr||g||<q|j|dS)aApply a tag to a file matching a given regex, for use when a file is copied by a more generic copyspec. :param tagdict: A dict containing the filepatterns to match and the tag(s) to apply to those files :type tagdict: ``dict`` `tagdict` takes the form `{file_pattern: tag}`, E.G. to match all bond devices from /proc/net/bonding with the tag `bond`, use `{'/proc/net/bonding/bond.*': ['bond']}` N)rrfiletagsr)rLtagdictrrrr add_file_tagsUs zPlugin.add_file_tagscCs2g}|jD]\}}t||r||q|S)aGet the tags that should be associated with a file matching a given regex :param fname: A regex for filenames to be matched against :type fname: ``str`` :returns: The tag(s) associated with `fname` :rtype: ``list`` of strings )rrZrr{extend)rLrtagsrrrrr get_tags_for_filefs   zPlugin.get_tags_for_filecCsr|jD]b\}}|g|d}g}|jD](}t||dr(||ddq(|r ||d<|jj|q dS)zAfter file collections have completed, retroactively generate manifest entries to apply tags to files copied by generic copyspecs Z specification files_copiedrrXr[r$rN) rrZrrr{r^rrr)rLZ file_regextagZ manifest_dataZ matched_filescfilerrr generate_copyspec_tagsvs zPlugin.generate_copyspec_tagsTc  sd|dr|dtdtd|dd|j|dsj|d|d |j|dd dS|dur||d }|d rd}|r|d 9}|sdSt|tr|g}t|tr|g}dd} ddfdd} |D]} | rt | sdS|s4| r|| } | | } t | dkr:qn| g} g} t | dkr|| | d}|rh| || || d| |tt| } |rt|tr|g}|D]}||s|dur̐qd}|rvd| }|j|||d}|ddkrRzt|d}||krd}Wn2tyN|d| d|dYqYn0n$|d| d|d |dq|j || ||| |f|d!| d"|d#qqsrtt| | } | jdd$d}d}g}| D]}||jvr |d%|d#q||r.|d&|d#q||rP|d'|d#q||rr|d(|d#q|r|d)|d*qzt|tj}Wn>t y|!|rd}n|d+|d,YqYn0||7}|rd||krdd}|rt"|r$|d-|d.q|d-|d/|||}|j# ||f| |$d0n*| |$d0|%|g|o||k}q|s|j&r|j&j' | || d1qdS)2aAdd a file, directory, or globs matching filepaths to the archive :param copyspecs: Files, directories, or globs matching filepaths :type copyspecs: ``str`` or a ``list`` of strings :param sizelimit: Limit the total size of collections from `copyspecs` to this size in MB :type sizelimit: ``int`` :param maxage: Collect files with `mtime` not older than this many hours :type maxage: ``int`` :param tailit: Should a file that exceeds `sizelimit` be tail'ed to fit the remaining space to meet `sizelimit` :type tailit: ``bool`` :param pred: A predicate to gate if `copyspecs` should be collected :type pred: ``SoSPredicate`` :param tags: A tag or set of tags to add to the metadata information for this collection :type tags: ``str`` or a ``list`` of strings :param container: Container(s) from which this file should be copied :type container: ``str`` or a ``list`` of strings :param runas: When collecting data from a container, run it under this user. :type runas: ``str`` `copyspecs` will be expanded and/or globbed as appropriate. Specifying a directory here will cause the plugin to attempt to collect the entire directory, recursively. If `container` is specified, `copyspecs` may only be explicit paths, not globs as currently container runtimes do not support glob expansion as part of the copy operation. Note that `sizelimit` is applied to each `copyspec`, not each file individually. For example, a copyspec of ``['/etc/foo', '/etc/bar.conf']`` and a `sizelimit` of 25 means that sos will collect up to 25MB worth of files within `/etc/foo`, and will collect the last 25MB of `/etc/bar.conf`. Nrz".*((\.(zip|gz|bz2|xz))|[-.][\d]+)$^etcz/*r8zskipped copy spec 'z' due to predicate (rTrriFcSsB|drdS|dd}|dd}|dr>|ddSdS) zGenerate a tag to add for a single file copyspec This tag will be set to the filename, minus any extensions except for special extensions like .conf or .log, which will be mangled to _conf or similar. )z/procz/sysNr$r-r#)z.confz.logz.txtr%)rsplitrendswith)rZ_fnamerrr get_filename_tags    z.Plugin.add_copy_spec..get_filename_tagcSs(ztj|WSty"YdS0dS)z Files should be sorted in most-recently-modified order, so that we collect the newest data first before reaching the limit.rN)r$r"getmtimerbrrrr rs z&Plugin.add_copy_spec..getmtimecs\|dus|dur dS|}t|}r>|ksTrXt|dkrXdSdS)zl When --since is passed, or maxage is coming from the plugin, we need to filter out older files NTiF)searchrZ fromtimestampr)r"ZfiletimeZ filedatetimeZconfigfile_patternrZlogarchive_patternmaxagerrr time_filters   z)Plugin.add_copy_spec..time_filterrr+z stat -c %s  containerrunasrprBTzunable to determine size of 'z' in container 'z'. Skipping collection.z stat of 'z' failed, skipping collection: zadded collection of '' from container 'r)rreversezskipping redundant file 'rz skipping policy forbidden path 'rhz skipping 'z' over size limitrz ', skippingzFile 'z8' is over size limit and is binary. Skipping collection.zI' is over size limit, will instead tail the file during collection phase.r$r)(rerr\rr>rr<rrr r_expand_copy_specr^rrrrcontainer_existsexec_cmdrrYrrfiltersortrrrrqr$r,ST_SIZErbrrrrrrr)rLZ copyspecs sizelimitrtailitr8rrrrrcopyspecrZ _spec_tagsZ_specconZ_tailr@retZconsizeZ current_sizeZ limit_reachedZ_manifest_files_file file_sizeZadd_sizerrr add_copy_specs0                                      zPlugin.add_copy_specrcsg}t| tr| g} t|tr$|g}t|j|}rVttrDgfdd|D}r|ttrjgfdd|D}|| |j||||||||| || |d dS)aRun a command or list of commands against devices discovered during sos initialization. Any commands specified by cmd will be iterated over the list of the specified devices. Commands passed to this should include a '%(dev)s' variable for substitution. :param cmds: The command(s) to run against the list of devices :type cmds: ``str`` or a ``list`` of strings :param devices: The device paths to run `cmd` against. This should be either a list of devices/device paths or a key in the devices dict discovered by sos during initialization. :type devices: ``str`` or a ``list`` of devices or device paths. :param timeout: Timeout in seconds to allow each `cmd` to run :type timeout: ``int`` :param sizelimit: Maximum amount of output to collect, in MB :type sizelimit: ``int`` :param chroot: Should sos chroot the command(s) being run :type chroot: ``bool`` :param runat: Set the filesystem location to execute the command from :type runat: ``str`` :param env: Set environment variables for the command(s) being run :type env: ``dict`` :param binary: Is the output collected going to be binary data :type binary: ``bool`` :param prepend_path: The leading path for block device names :type prepend_path: ``str`` or ``None`` :param whitelist: Limit the devices the `cmds` will be run against to devices matching these item(s) :type whitelist: ``list`` of ``str`` :param blacklist: Do not run `cmds` against devices matching these item(s) :type blacklist: ``list`` of ``str`` :param subdir: Write the command output to this subdir within the Plugin directory :type subdir: ``str`` cs&g|]tfddDrqS)c3s |]}td|VqdSz(.*)?Nr})r7Zwldrr rr;3Plugin.add_device_cmd...rVr7) whitelistrr r:sz)Plugin.add_device_cmd..cs&g|]tfddDsqS)c3s |]}td|VqdSrr})r7Zblrrr rr;rrr) blacklistrr r:s) rrchrootrunatrrJ prepend_pathrprioritysubdirN)rrrrr_add_device_cmd)rLcmdsrrrrrrrJrrrrrr _dev_tagsZ_devsr)rrr add_device_cmds(5       zPlugin.add_device_cmdc Cst|tr|g}t|tr |g}|p,|d}|D]X} |D]N}|g}|| | r^|| |}| d|i}|j||||||||| | d q:q2dS)zCRun a command against all specified devices on the system. rdev) r@rrrrrrJrrrN)rrrerr_add_cmd_output)rLrrrrrrrrJrrrrr@ZdevicerZ_cmdrrr rs$     zPlugin._add_device_cmdcKsPd|vr|dnt|}d|vr*d|d<d|vr:d|d<ttfi|ddsv|dsf|dd krvd |d<d |d <d|vr|dtfi|}|d t||jD],}t|j |r|d |j ddSq|j d |dr8|j |d}t|dddurd|j d}|d|j d|n|j|j ||jddS)z?Internal helper to add a single command to the collection list.r8rrr@Fsnap_cmdrrrTto_filezpacked command: zskipping excluded command 'rNr=r"r , as the  userzadded cmd output 'r@)popr5r rrerrrrOr@r>rr^rrrAr@)rLrr8soscmdZ _skip_cmduserrrr rs6    zPlugin._add_cmd_outputc st|tr|g}r,fdd|D}nfdd|D}|sbd|rLdnd| rX| nd}nd}|D]:}j|rzdnd d |d ||||||| | d qjd S)a Used as a way to standardize our collections of directory listings, either as an output of `ls` or `tree` depending on if the `tree` parameter is set to `True`. This is ultimately a wrapper around `add_cmd_output()` and supports several, but not all, of the options for that method. :param paths: The path(s) to collect a listing for :type paths: ``str`` or a ``list`` of ``str``s :param tree: Collect output with `tree` instead of `ls` :type tree: ``bool`` (default: False) :param recursive: Recursively list directory contents with `ls` :type recursive: ``bool`` (default: False) cs g|]}j|dr|qS)r)container_path_existsr>rrrLrr r:*sz*Plugin.add_dir_listing..csg|]}|r|qSrr r>rRrr r:.r;ZalZRr"ZlptreeZlsz -r) rrrr8rrrrsuggest_filenameN)rradd_cmd_output)rLr*r recursiverrrr8rrrrrZ extra_optsrr"rrr add_dir_listings"  zPlugin.add_dir_listingcCst|tr|g}t|dkr.|s$|r.|d| dur@|d} | durT|jdd} |D]|}d}|r|}||f}|j||||d}|s|d|d |d qX|j||||||||| | | | || |||||||d qXdS) aK Run a program or a list of programs and collect the output Output will be limited to `sizelimit`, collecting the last X amount of command output matching `sizelimit`. Unless `suggest_filename` is set, the file that the output is saved to will match the command as it was executed, and will be saved under `sos_commands/$plugin` :param cmds: The command(s) to execute :type cmds: ``str`` or a ``list`` of strings :param suggest_filename: Override the name of the file output is saved to within the archive :type suggest_filename: ``str`` :param root_symlink: If set, create a symlink with this name in the archive root :type root_symlink: ``str`` :param timeout: Timeout in seconds to allow each `cmd` to run for :type timeout: ``int`` :param stderr: Should stderr output be collected :type stderr: ``bool`` :param chroot: Should sos chroot the `cmds` being run :type chroot: ``bool`` :param runat: Run the `cmds` from this location in the filesystem :type runat: ``str`` :param env: Set environment variables for the `cmds` being run :type env: ``dict`` :param binary: Is the command expected to produce binary output :type binary: ``bool`` :param sizelimit: Maximum amount of output in MB to save :type sizelimit: ``int`` :param pred: A predicate to gate if `cmds` should be collected or not :type pred: ``SoSPredicate`` :param subdir: Save output to this subdirectory, within the plugin's directory under sos_commands :type subdir: ``str`` :param changes: Do `cmds` have the potential to change system state :type changes: ``int`` :param foreground: Should the `cmds` be run in the foreground, with an attached TTY :type foreground: ``bool`` :param tags: A tag or set of tags to add to the metadata entries for the `cmds` being run :type tags: ``str`` or a ``list`` of strings :param priority: The priority with which this command should be run, lower values will run before higher values :type priority: ``int`` :param cmd_as_tag: Should the command string be automatically formatted to a tag? :type cmd_as_tag: ``bool`` :param container: Run the specified `cmds` inside a container with this ID or name :type container: ``str`` :param to_file: Should command output be written directly to a new file rather than stored in memory? :type to_file: ``bool`` :param runas: Run the `cmd` as the `runas` user :type runas: ``str`` :param snap_cmd: Are the commands being run from a snap? :type snap_cmd: ``bool`` :param runtime: Specific runtime to use to run container cmd :type runtime: ``str`` r+z.ambiguous filename or symlink for command listNrT)r@)runtimerzSkipping command 'z' as the requested container 'z' does not exist.)r@r root_symlinkrstderrrrrrJrr8rrr@ foregroundr cmd_as_tagr container_cmdrr) rrr rrer<fmt_container_cmdrr)rLrrrrrrrrrJrr8rr@rrrrrrrrrr@rZocmdrrr r>s>Z       zPlugin.add_cmd_outputcCs6|D] }t||tr||g||<q|j|dS)aRetroactively add tags to any commands that have been run by this plugin that match a given regex :param tagdict: A dict containing the command regex and associated tags :type tagdict: ``dict`` `tagdict` takes the form of {cmd_regex: tags}, for example to tag all commands starting with `foo` with the tag `bar`, use {'foo.*': ['bar']} N)rrcmdtagsr)rLrr@rrr add_cmd_tagss zPlugin.add_cmd_tagscCs,|jD]\}}t||r |Sq gS)zGet the tag(s) that should be associated with the given command :param cmd: The command that tags should be applied to :type cmd: ``str`` :returns: Any tags associated with the command :rtype: ``list`` )rrZrr{)rLr@rrrrr get_tags_for_cmds   zPlugin.get_tags_for_cmdcCsBtj|jd|}|r,tj||}|r>tj|dd|S)aGet the path where this plugin will save command output :param name: Optionally specify a filename to use as part of the command output path :type name: ``str`` or ``None`` :param make: Attempt to create the command output path :type make: ``bool`` :returns: The path where the plugin will write command output data within the archive :rtype: ``str`` sos_commandsT)exist_ok)r$r"rGr'r(rmakedirs)rLrZmakeZcmd_output_pathrrr get_cmd_output_pathszPlugin.get_cmd_output_pathcGst|g|RS)aMGrep through file(s) for a specific string or regex :param regexp: The string or regex to search for :type regexp: ``str`` :param fnames: Paths to grep through :type fnames: ``str``, ``list`` of string, or open file objects :returns: Lines matching `regexp` :rtype: ``str`` )r)rLrRfnamesrrr file_greps zPlugin.file_grepcCs|j}t||Sr})r'r)r*)rLrLr)rrr r*s zPlugin._mangle_commandc Cs|}|r|d|7}tj|jd|}||}tjtj|j||rd}|j }d|}|} |t | t |kr| d|t | t |} | |} tjtj|j|| s| }q|d7}qdtj||S)z@The internal function to build up a filename based on a command.r$rMr+r%N) rr$r"rGrr*existsr'r(r)r ) rLrLrZ plugin_dirZoutdiroutfnZincr)rOZnewfnrrr _make_command_filenames,    zPlugin._make_command_filenamecCs8t|ts|g}|D]}|j|||gqdS)aAdd an environment variable to the list of to-be-collected env vars. Collected environment variables will be saved to an `environment` file in the archive root, and any variable specified for collection will be collected in lowercase, uppercase, and the form provided :param name: The name of the environment variable to collect :type name: ``str`` N)rrrrupperr)rLrrrrr add_env_var s zPlugin.add_env_varcCs|jd|ds,|d|j|dddS|r4dnd}tj|||}t|tr\|g}|j |||f| d |d dS) aAdd a string to the archive as a file :param content: The string to write to the archive :type content: ``str`` :param filename: The name of the file to write `content` to :type filename: ``str`` :param pred: A predicate to gate if the string should be added to the archive or not :type pred: ``SoSPredicate`` :param plug_dir: Should the string be saved under the plugin's dir in sos_commands/? If false, save to sos_strings/ :type plug_dir: ``bool`` :param tags: A tag or set of tags to add to the manifest entry for this collection :type tags: ``str`` or a ``list`` of strings Fr=z!skipped string due to predicate (rrTNr sos_stringszadded string as 'r) r>rr<r$r"rGrrrrr^r)rLZcontentfilenamer8Zplug_dirrZsos_dirrrr add_string_as_file+ s   zPlugin.add_string_as_filec'Cs<|jr dS|dur|j}g}t|tr,|g}||||||r^|tdd|t t |}| |}|s|j dj dkr|j}nd}|r||| }n ||| }|t|j ddd}|r|d|d |j|ttj|j|}nd }t}t||||||| | |j| |||d }t}||}|d d krd|d|d}|||rd|} ||| |dd|ddd||r|nd|d|d |||||d }!|d dks|d dkr|r\|dkr\|j dj dkr\|d|dd|dt||d ||| | |j||d }t|}|d|d|d dvr|jr|jj |!|S|d|dd |d!| d"|dr|d|dd#|}"|!d$d%d&}|r|jj|td'd(}#t"||#|sJ| r8|j#|d)|n|j$|d)||drtj|j|}$tj|j|"}%tj%|$|%}&|&!d*d+d}&|j&|&|"|r|j&|||j'||| rd,nd-d.|rtj|j|nd+|d/<|jr8||!d0<||!d1<|jj |!|r8|(|!)|||S)2aJExecute a command and save the output to a file for inclusion in the report. Positional Arguments: :param cmd: The command to run Keyword Arguments: :param suggest_filename: Filename to use when writing to the archive :param root_symlink: Create a symlink in the archive root :param timeout: Time in seconds to allow a cmd to run :param stderr: Write stderr to stdout? :param chroot: Perform chroot before running cmd? :param runat: Run the command from this location, overriding chroot :param env: Dict of env vars to set for the cmd :param binary: Is the output in binary? :param sizelimit: Maximum size in MB of output to save :param subdir: Subdir in plugin directory to save to :param changes: Does this cmd potentially make a change on the system? :param foreground: Run the `cmd` in the foreground with a TTY :param tags: Add tags in the archive manifest :param cmd_as_tag: Format command string to tag :param to_file: Write output directly to file instead of saving in memory :param tac: Reverse log lines order :param runas: Run the `cmd` as the `runas` user :returns: dict containing status, output, and filename in the archive for the executed cmd Nz[^\w\.]+r#ralwaysrMr+ collecting 'z' output directly to diskF) rrrchdirrrJrpollerrrtacrrp|z command 'z' timed out after r=z3 - output up until the timeout may be available at rr truncated) r( parametersexecfilepathr Z return_coderrrrr~r$z' not found in z - re-trying in host root) rrrrrJrrrrzcould not run 'z': command not found)r rzcollected output of '' in z (changes=rTz' was truncatedrr.tailedTrlrBz../r"rKr)r@rIrJrr r)*rrrrrrr^rr&rrrrrrrr rr' check_pathrr$r"rGZget_archive_pathrrrrrrrrrrenameZ add_binaryrQrtrvr_add_container_cmd_to_manifestr)'rLr@rrrrrrrrJrrr@rrrrrrrrZ_tagsrrootrZ outfn_stripZout_filerirrendrwarnrZ manifest_cmdZlinkfnrxZ _outfn_pathZ _link_pathZrpathrrr _collect_cmd_outputP s)                 zPlugin._collect_cmd_outputcCsP|jd| ds*|j|| | dddddS|j||||||||| | | |||dS)aExecute a command and save the output to a file for inclusion in the report, then return the results for further use by the plugin :param cmd: The command to run :type cmd: ``str`` :param suggest_filename: Filename to use when writing to the archive :param suggest_filename: ``str`` :param root_symlink: Create a symlink in the archive root :type root_symlink: ``bool`` :param timeout: Time in seconds to allow a cmd to run :type timeout: ``int`` :param stderr: Write stderr to stdout? :type stderr: ``bool`` :param chroot: Perform chroot before running cmd? :type chroot: ``bool`` :param runat: Run the command from this location, overriding chroot :type runat: ``str`` :param env: Environment vars to set for the cmd :type env: ``dict`` :param binary: Is the output in binary? :type binary: ``bool`` :param sizelimit: Maximum size in MB of output to save :type sizelimit: ``int`` :param subdir: Subdir in plugin directory to save to :type subdir: ``str`` :param changes: Does this cmd potentially make a change on the system? :type changes: ``bool`` :param foreground: Run the `cmd` in the foreground with a TTY :type foreground: ``bool`` :param tags: Add tags in the archive manifest :type tags: ``str`` or a ``list`` of strings :param runas: Run the `cmd` as the `runas` user :type runas: ``str`` :returns: `cmd` exit status, output, and the filepath within the archive output was saved to :rtype: ``dict`` Tr=rNr")rprBr) rrrrrrrrJrrrrr)r>rAr)rLr@rrrrrrrrJrr8r@rrrrrrr collect_cmd_output s=zPlugin.collect_cmd_outputc Csddd}|jd|ds|S|dur*|j}|s>|jdjdkrF|j}nd}||}| r|dur|d|d | d |S|| | s| dur| | || | | }n|d|d | d t ||||||| || d S) aBExecute a command right now and return the output and status, but do not save the output within the archive. Use this method in a plugin's setup() if command output is needed to build subsequent commands added to a report via add_cmd_output(). :param cmd: The command to run :type cmd: ``str`` :param timeout: Time in seconds to allow a cmd to run :type timeout: ``int`` :param stderr: Write stderr to stdout? :type stderr: ``bool`` :param chroot: Perform chroot before running cmd? :type chroot: ``bool`` :param runat: Run the command from this location, overriding chroot :type runat: ``str`` :param env: Environment vars to set for the cmd :type env: ``dict`` :param binary: Is the output in binary? :type binary: ``bool`` :param pred: A predicate to gate execution of the `cmd` :type pred: ``SoSPredicate`` :param foreground: Run the `cmd` in the foreground with a TTY :type foreground: ``bool`` :param container: Execute this command in a container with this name :type container: ``str`` :param quotecmd: Whether the cmd should be quoted. :type quotecmd: ``bool`` :param runas: Run the `cmd` as the `runas` user :type runas: ``str`` :param runtime: Specific runtime to use to execute the container command :type runtime: ``str`` :returns: Command exit status and output :rtype: ``dict`` Nr")rprBTr=rrzCannot run cmd 'z' in container z: no runtime detected on host.z: no such container is running.)rrrrJrrrr) r>rrrrr_get_container_runtimerrrr)rLr@rrrrrrJr8rrquotecmdrrZ_defaultrrrrr rS s67        zPlugin.exec_cmdcCs@||jjvrggd|jj|<|jj|d|||ddS)aAdds a file collection to the manifest for a particular container and file path. :param container: The name of the container :type container: ``str`` :param path: The filename from the container filesystem :type path: ``str`` :param arcpath: Where in the archive the file is written to :type arcpath: ``str`` :param tags: Metadata tags for this collection :type tags: ``str`` or ``list`` of strings rrrrN)rrr^)rLrr"Zarcpathrrrr _add_container_file_to_manifest s z&Plugin._add_container_file_to_manifestc Cs|\}}||jjvr&ggd|jj|<||d<|dd|d<|ddd|d<d |d |}d |d }|r|n||}|d |} |j| trt ||j | | |d <|jj|d |dS)aAdds a command collection to the manifest for a particular container and creates a symlink to that collection from the relevant sos_containers/ location :param manifest: The manifest entry for the command :type manifest: ``dict`` :param contup: A tuple of (original_cmd, container_name) :type contup: ``tuple`` rr rrr(r+Nr sos_containers/z/sos_commands/z ../../../../r r$r) rrrrr*r'rrr$rj dest_pathr^) rLrcontupZ suggest_fnamer@rZ_cdirZ_outlocZcmdfnZconlnkrrr r s  z%Plugin._add_container_cmd_to_manifestcCsX|dur&d|jjvrT|jjdSn.t|jjD]}||kr6|jj|Sq6dS)zjBased on policy and request by the plugin, return a usable ContainerRuntime if one exists Nr)ryZruntimeskeysr)rLrZ pol_runtimerrr r szPlugin._get_container_runtimecCs4||p |j}|dur0||p.||duSdS)aIf a container runtime is present, check to see if a container with a given name is currently running :param name: The name or ID of the container to check presence of :type name: ``str`` :param runtime: The runtime to use :type runtime: ``str`` :returns: ``True`` if `name` exists, else ``False`` :rtype: ``bool`` NF)rrrget_container_by_namerLrr_runtimerrr r s   zPlugin.container_existscs2|}|dur.|j|d}fdd|DSgS)aGet a list of all container names and ID matching a regex :param regex: The regular expression to match :type regex: ``str`` :param get_all: Return all containers found, even terminated ones :type get_all: ``bool`` :returns: All container IDs and names matching ``regex`` :rtype: ``list`` of ``tuples`` as (id, name) Nget_allcs g|]}t|dr|qS)r+r}rrrr r: r;z6Plugin.get_all_containers_by_regex..)rget_containers)rLrr%r#Z _containersrr&r get_all_containers_by_regex s  z"Plugin.get_all_containers_by_regexcCs ||}|dur||SdS)a,Get the container ID for a specific container :param name: The name of the container :type name: ``str`` :param runtime: The runtime to use :type runtime: ``str`` :returns: The ID of the container if it exists :rtype: ``str`` or ``None`` N)rr!r"rrr r! s  zPlugin.get_container_by_namecCs.|j|d}|dur*|r$|jddS|jSgS)a\Return a list of all container IDs from the ``Policy`` ``ContainerRuntime`` If `runtime` is not provided, use the ``Policy`` default :param runtime: The container runtime to use, if not the default runtime detected and loaded by the ``Policy`` :type runtime: ``str`` :param get_all: Return all containers known to the `runtime`, even those that have terminated :type get_all: ``bool`` :returns: All container IDs found by the ``ContainerRuntime`` :rtype: ``list`` rNTr$)rr'r)rLrr%r#rrr r'% s   zPlugin.get_containerscCs|j|d}|dur|jSgS)aReturn a list of all image names from the Policy's ContainerRuntime If `runtime` is not provided, use the Policy default. If the specified `runtime` is not loaded, return empty. :param runtime: The container runtime to use, if not using the default runtime detected by the ``Policy`` :type runtime: ``str`` :returns: A list of container images known to the `runtime` :rtype: ``list`` r)N)rZimagesrLrr#rrr get_container_images= s zPlugin.get_container_imagescCs|j|d}|dur|jSgS)aReturn a list of all volume names from the Policy's ContainerRuntime If `runtime` is not provided, use the Policy default. If the specified `runtime` is not loaded, return empty. :param runtime: The container runtime to use, if not using the default runtime detected by the ``Policy`` :type runtime: ``str`` :returns: A list of container volumes known to the `runtime` :rtype: ``list`` r)N)rZvolumesr*rrr get_container_volumesP s zPlugin.get_container_volumesc Ksd|}|dur`t|tr |g}|D]:}|||}|D]$}||d}|j|fi|q8q$dS)aHelper to get the ``logs`` output for a given container or list of container names and/or regexes. Supports passthru of add_cmd_output() options :param containers: The name of the container to retrieve logs from, may be a single name or a regex :type containers: ``str`` or ``list`` of strs :param get_all: Should non-running containers also be queried? Default: False :type get_all: ``bool`` :param kwargs: Any kwargs supported by ``add_cmd_output()`` are supported here Nr+)rrrr(Zget_logs_commandr) rLrr%rr#rZ_consZ_conr@rrr add_container_logsc s  zPlugin.add_container_logscCs4|||s"||}r0|dur0||||SdS)aFormat a command to be executed by the loaded ``ContainerRuntime`` in a specified container :param container: The name of the container to execute the `cmd` in :type container: ``str`` :param cmd: The command to run within the container :type cmd: ``str`` :param quotecmd: Whether the cmd should be quoted. :type quotecmd: ``bool`` :param runtime: The specific runtime to use to run the command within the container :type runtime: ``str`` :param runas: What user runs the container. If set, we trust the container really runs (we dont keep them atm) :type runas: ``str`` :returns: The command to execute so that the specified `cmd` will run within the `container` and not on the host :rtype: ``str`` Nr")rrr)rLrr@rrrr#rrr r~ s  zPlugin.fmt_container_cmdcCs ||jjvS)aDetermine whether specified module is loaded or not :param module_name: Name of kernel module to check for presence :type module_name: ``str`` :returns: ``True`` if the module is loaded, else ``False`` :rtype: ``bool`` )ryr)rLZ module_namerrr rf s zPlugin.is_module_loadedcCs|j|dS)zAdd an alert to the collection of alerts for this plugin. These will be displayed in the report :param alertstring: The text to add as an alert :type alertstring: ``str`` N)rr^)rLZ alertstringrrr add_alert szPlugin.add_alertcCs|j|7_dS)zAppend text to the custom text that is included in the report. This is freeform and can include html. :param text: The text to include in the report :type text: ``str`` N)r)rLtextrrr add_custom_text szPlugin.add_custom_textcKsVt|tr|g}|jjj}|s,|ddS|D] }|j|d|fi|q0dS)aRCollect service status information based on the ``InitSystem`` used :param services: Service name(s) to collect statuses for :type services: ``str`` or a ``list`` of strings :param kwargs: Optional arguments to pass to add_cmd_output (timeout, predicate, suggest_filename,..) zFCannot add service output, policy does not define an InitSystem to useNr)rrryr.Z query_cmdrr)rLrHrqueryservicerrr add_service_status s   zPlugin.add_service_statusc Csd}d}d}d}d}d}d}d}d }| d ks6|d r.__expandrFT)r)r$rrr rrr9removerr"rGr:rr)rLrZexpandedZrecursed_files_pathrr;r rC s     zPlugin._expand_copy_speccCs<t|jddD] }|d|d||q|dS)NT)rzcollecting path 'r)rrrrwrr!rrr _collect_copy_specso s zPlugin._collect_copy_specsc Cs`|js dS|}|s$|ddS|s:|ddS|jD]}|\}}}}}}|d|d|dd|d|d} |j| t|j| } |dur|j ||| |r|ndd n| |d |d } |j | d |d } | ddkr:|s|dur|j | d| | ||| ||j|| ddq@|d|d|d| dq@dS)a?Copy any requested files from containers here. This is done separately from normal file collection as this requires the use of a container runtime. This method will iterate over self.container_copy_paths which is a set of 5-tuples as (container, path, sizelimit, stdout, tags). NzDCannot collect container based files - no runtime is present/active.zYLoaded runtime '%s' does not support copying files from containers. Skipping collections.rrrrr$)rzcat Fr)rrrprrBrrzerror copying 'r?)rrrZcheck_can_copyrr'rrrZget_copy_commandrrrQrrr^) rLZrtrrr"rrrrZarcdestrxZcpcmdZcpretrrr _collect_container_copy_specsu sL      z$Plugin._collect_container_copy_specscCs|jjddd|jD]d}|dt|d}t|dddurRd|jd}|d |jd ||jfi|j qdS) NcSs|jSr})r)xrrr  r;z&Plugin._collect_cmds..)rzunpacked command: r"rrrzcollecting output of 'r) rrrrr rrr@rr)rLrrrrr _collect_cmds s zPlugin._collect_cmdscCs|jD]\}}|d|d|}|dtjkr>|tj}|tjjdd}|t|||tj dtj |}tj |d| |}|j ||qdS)Nzcollecting tail of 'z' due to size limitrr%rr$r)rrr$r&rrr"rr rtrorGrr'rv)rLrr file_nameZstrfileZrel_pathZ link_pathrrr _collect_tailed_files s  zPlugin._collect_tailed_filesc Cs|jD]\}}}|jrdS|d|dz:|j|||dddd}||d|jj|<Wqt y}z"| d|d |WYd}~qd}~00qdS) Nzcollecting string as 'rr$rr%r#)r"rzcould not add string 'r?) rrrr'rQrrrrrr)rLstringrCr_namerVrrr _collect_strings szPlugin._collect_stringsc CsFz |Wn4ty@}z|d|WYd}~n d}~00dS)aKick off manual collections performed by the plugin. These manual collections are anything the plugin collects outside of existing files and/or command output. Anything the plugin manually compiles or constructs for data that is included in the final archive. Plugins will need to define these collections by overriding the ``collect()`` method, similar to how plugins define their own ``setup()`` methods. z!Error during plugin collections: N)collectrr)rLrrrr _collect_manual s  zPlugin._collect_manualcCsdS)aCIf a plugin needs to manually compile some data for a collection, that should be specified here by overriding this method. These collections are run last during a plugin's execution, and as such are more likely to be interrupted by timeouts than file or command output collections. NrrRrrr rH szPlugin.collectc cszt}|j||d}|j|t|j|}t|ddd&}|d||VWdn1sj0Yt}||} |d|d| t |t r|g}|j j |||d Wn:ty} z"|d |d | WYd} ~ n d} ~ 00dS) aHandles creating and managing files within a plugin's subdirectory within the archive, and is intended to be used to save manually compiled data generated during a plugin's ``_collect_manual()`` step of the collection phase. Plugins should call this method using a ``with`` context manager. :param fname: The name of the file within the plugin directory :type fname: ``str`` :param subdir: If needed, specify a subdir to write the file to :type subdir: ``str`` :param tags: Tags to be added to this file in the manifest :type tags: ``str`` or ``list`` of ``str`` )rwrencodingzmanual collection file opened: Nzmanual collection 'z' finished in )rr rzError with collection file 'r?)rrr'rrropenrrrrrrr^r) rLrrrriZ_pfnamerFrrrunrrrr collection_file s( $  zPlugin.collection_filecCsZt}|||||||d|dt|dS)zCollect the data for a plugin.zcollected plugin 'rN) rr>r?rDrGrBrIrr)rLrirrr collect_plugin szPlugin.collect_plugincCs"z|jWStyYdS0dS)z8This function will return the description for the pluginrN)rrrRrrr get_description s zPlugin.get_descriptioncCst|j|j|j|j|j|j|jgrt|jt r:|jg|_t|jt rP|jg|_t|jt rf|jg|_t|jt r||jg|_t|jt r|jg|_| |j|j|j|j|jSdS)aThis method will be used to verify that a plugin should execute given the condition of the underlying environment. The default implementation will return True if none of class.files, class.packages, nor class.commands is specified. If any of these is specified the plugin will check for the existence of any of the corresponding paths, packages or commands and return True if any are present. For plugins with more complex enablement checks this method may be overridden. :returns: ``True`` if the plugin should be run for this system, else ``False`` :rtype: ``bool`` T) rVrrIrrrHr architecturesrr_check_plugin_triggersrRrrr check_enabled s(           zPlugin.check_enabledcst|||||gsStfdd|Dstfdd|Dstfdd|DstfddjDstfdd|Dstfdd|DoS)Nc3s|]}|VqdSr}r)r7rrRrr rQ r;z0Plugin._check_plugin_triggers..c3s|]}|VqdSr})rmrrRrr rR r;c3s|]}t|jVqdSr})r r)r7r@rRrr rS r;c3s|]}|VqdSr})rf)r7modrRrr rT r;c3s|]}|VqdSr})r/)r7rkrRrr rU r;c3s|]}|VqdSr})r)r7ZcntrrRrr rV r;)rVcheck_is_architecturer)rLrrIrrHrrrRr rSJ szPlugin._check_plugin_triggerscCs4|jdurdSdd|jd}t||jS)a?Checks whether or not the system is running on an architecture that the plugin allows. If not architecture is set, assume plugin can run on all arches. :returns: ``True`` if the host's architecture allows the plugin to run, else ``False`` :rtype: ``bool`` NTrvrwrT)rRrGrr{ryrzr5rrr rVY s zPlugin.check_is_architecturecCsdS)zwThis decides whether a plugin should be automatically loaded or only if manually specified in the command line.TrrRrrr default_enabledg szPlugin.default_enabledcCsT|jD]"}||r||||q|jD]}||r0|d|q0dS)zBased on the class attrs defined for plugin enablement, add a standardized set of collections before we call the plugin's own setup() method. zmodinfo N)rHr/r3r8rrfr)rLr2rgrrr add_default_collectionsl s      zPlugin.add_default_collectionscCs|t|jdS)zCollect the list of files declared by the plugin. This method may be overridden to add further copy_specs, forbidden_paths, and external programs if required. N)rrrrRrrr setup{ sz Plugin.setupcCsXt|ds2t|dr.|jr.dd|jD|_ndS|jj}||j}|rT||dS)NrrIcSsg|] }|dqS)$rr>rrr r: r;z'Plugin.setup_verify..)r rIrryr,Zbuild_verify_commandr)rLZpmZ verify_cmdrrr setup_verify s  zPlugin.setup_verifycCs|jd|||dS)aCheck if a path exists inside a container before collecting a dir listing :param path: The canonical path for a specific file/directory in a container :type path: ``str`` :param container: The container where to check for the path :type container: ``str`` :returns: True if the path exists in the container, else False :rtype: ``bool`` ztest -e r)r)rLr"rrrrr r szPlugin.container_path_existscCs t||jS)a\Helper to call the sos.utilities wrapper that allows the corresponding `os` call to account for sysroot :param path: The canonical path for a specific file/directory :type path: ``str`` :returns: True if the path exists in sysroot, else False :rtype: ``bool`` )r rr!rrr r s zPlugin.path_existscCs t||jS)aSHelper to call the sos.utilities wrapper that allows the corresponding `os` call to account for sysroot :param path: The canonical path for a specific file/directory :type path: ``str`` :returns: True if the path is a dir, else False :rtype: ``bool`` )r rr!rrr r s zPlugin.path_isdircCs t||jS)aTHelper to call the sos.utilities wrapper that allows the corresponding `os` call to account for sysroot :param path: The canonical path for a specific file/directory :type path: ``str`` :returns: True if the path is a file, else False :rtype: ``bool`` )rrr!rrr r s zPlugin.path_isfilecCs t||jS)aTHelper to call the sos.utilities wrapper that allows the corresponding `os` call to account for sysroot :param path: The canonical path for a specific file/directory :type path: ``str`` :returns: True if the path is a link, else False :rtype: ``bool`` )rrr!rrr r s zPlugin.path_islinkcCs t||jS)aTHelper to call the sos.utilities wrapper that allows the corresponding `os` call to account for sysroot :param path: The canonical path for a specific file/directory :type path: ``str`` :returns: Contents of path, if it is a directory :rtype: ``list`` )rrr!rrr r s zPlugin.listdircGst|g|Rd|jiS)aHelper to call the sos.utilities wrapper that allows the corresponding `os` call to account for sysroot :param path: The leading path passed to os.path.join() :type path: ``str`` :param p: Following path section(s) to be joined with ``path``, an empty parameter will result in a path that ends with a separator :type p: ``str`` r)rr)rLr"r?rrr r s zPlugin.path_joincCsdS)zLPerform any postprocessing. To be replaced by a plugin if required. NrrRrrr r szPlugin.postprocc Csd}d}zdt|}|D]P}t||ddd(}|}||vrJd}Wdq1s^0YqWntyYdS0|S)zChecks if a named process is found in /proc/[0-9]*/cmdline. :param process: The name of the process :type process: ``str`` :returns: ``True`` if the process exists, else ``False`` :rtype: ``bool`` F/proc/[0-9]*/cmdlinerrrKTN)r9rMrrr'IOError)rLprocessrp cmd_line_globcmd_line_pathsr"Zpfilecmd_linerrr check_process_by_name s    ( zPlugin.check_process_by_namec Csg}d}t|}|D]|}z`t|ddd>}|d}t||rZ||ddWdn1sn0YWqtyYqYq0q|S) zGet a list of all PIDs that match a specified name :param process: The name or regex of the process the get PIDs for :type process: ``str`` :returns: A list of PIDs :rtype: ``list`` r\r]rrKr$N) r9rMrr'rr{r^rr^)rLr_pidsr`rar"rrbrrr get_process_pids s   6  zPlugin.get_process_pidsc Csg}||}|D]f}z tt|tj||Wqtyv}z(|d|d|d|WYd}~qd}~00qt t t |d|S)a Send a SIGUSR1 to the pid(s) associated with the specified process name. Callers should be aware that a 1-second delay per signalled pid, up to 5 seconds at most, is expected as to allow sufficient time for the signalled process(es) to react to the received signal. :param process: The name or regex pattern of the process(es) to signal :type process: ``str`` :returns: A list of pids that were successfully signalled :rtype: ``list`` zFailed to signal pid z for 'r?N) rgr$killrsignalSIGUSR1r^rrrminr )rLr_Z signalledrfpidrrrr signal_process_usr1 s  zPlugin.signal_process_usr1cCs8|dur |jdjr |jdj}||jdd||S)Nr namespacesnetwork)rrofilter_namespaces)rL ns_patternns_maxrrr get_network_namespaces<s  zPlugin.get_network_namespacescCs~g}d}|r*dd|ddd}|D]J}|rHtt||sHq.|||r.t||kr.|d|dqzq.|S) zFilter a list of namespaces by regex pattern or max number of namespaces (options originally present in the networking plugin.) Nrvz$|rFz.*z$)z&Limiting namespace iteration to first z namespaces found) rGrrrrr{r^r r)rLZns_listrrrsZout_nsrGnsrrr rqBs    zPlugin.filter_namespaces)N)FN)FN)F)r")r")NF)r)NT)N) NTTNNFNFFFNN)N)N)F)N)NF)N)N)F)FNN)NNNNNFNNNNNNNr)N)NN)NN)rrrrrrIrrrrHrrrRr'r rr rrrrrrrr6r9rrrrrrrrpropertyrrrr classmethodrrrrrrrrrr#rr+rmrr/r1r2rjr3r4rr:r<r>rArErCr`r]rfrergryr|rarrrqrrwrrrerrrrrrrrrrrrrrr*rrrrrrrrrrr(r!r'r+r,r-rrfr.r0r3r8rr>r?rBrDrGrIrH contextlibcontextmanagerrOrPrQrTrSrVrWrXrYr[rr r rrrrrrcrgrnrtrqrrrr rs.* ,     e 8             8 %C <   Q ! - x   % 8 L V!            p,0  & +       rc@seZdZdZdS)PluginDistroTagzThe base tagging class for distro-specific classes used to signify that a Plugin is written for that distro. Use IndependentPlugin for plugins that are distribution agnostic Nrrrrrrrr rz_srzc@seZdZdZdS) RedHatPluginz/Tagging class for Red Hat's Linux distributionsNr{rrrr r|gsr|c@seZdZdZdS) UbuntuPluginzTagging class for Ubuntu LinuxNr{rrrr r}ksr}c@seZdZdZdS) DebianPluginzTagging class for Debian LinuxNr{rrrr r~osr~c@seZdZdZdS) SuSEPluginz*Tagging class for SuSE Linux distributionsNr{rrrr rssrc@seZdZdZdS)OpenEulerPluginz/Tagging class for openEuler linux distributionsNr{rrrr rwsrc@seZdZdZdS) CosPluginz(Tagging class for Container-Optimized OSNr{rrrr r{src@seZdZdZdS)IndependentPluginz6Tagging class for plugins that can run on any platformNr{rrrr rsrc@seZdZdZdS)ExperimentalPluginz=Tagging class that indicates that this plugin is experimentalNr{rrrr rsrc@seZdZdZdS) AzurePluginzTagging class for Azure LinuxNr{rrrr rsrcCsd|}|stf}t||S)zImport name as a module and return a list of all classes defined in that module. superclasses should be a tuple of valid superclasses to import, this defaults to (Plugin,). zsos.report.plugins.)rr)rZ superclassesZ plugin_fqnamerrr import_plugins r)N)8rrxr$r9rrjr,rrrrOrcr rZ sos.utilitiesrrrrr r r r r rrrrrrrZ sos.archiverrr!r*r4r\DOTALLrDrBr5rrrrzr|r}r~rrrrrrrrrrr  sz H 1Q