3 ܓi7@sdZddlZddlZddlZddlZddlZddlZddlZddlmZm Z ddl Z ddl Z ddl Z ddl Z ddlmZddlmZddlmZmZmZmZmZmZmZmZmZmZmZmZmZmZm Z m!Z!ddl"m#Z#m$Z$m%Z%dd Z&d d Z'd d Z(ej)dej*Z+dZ,GdddZ-GdddZ.GdddZ/GdddZ0GdddZ1Gddde1Z2Gddde1Z3Gddde1Z4Gd d!d!e1Z5Gd"d#d#e1Z6Gd$d%d%e1Z7Gd&d'd'e1Z8Gd(d)d)e1Z9Gd*d+d+e1Z:d.d,d-Z;dS)/z; This exports methods available for use by plugins for sos N)timesleep)datetime)Path)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_LINK P_CONTFILEcCsBy(t|}tj||jtjSQRXWntk r<gSXdS)z=Return a list of all non overlapping matches in the string(s)N)r refindallread MULTILINEAttributeError)regexfnamefr!/usr/lib/python3.6/__init__.py regex_findall(s  r#cCs@tjdd|}tjdd|}tjdd|jd}|d|}|S) Nz^/(usr/|)(bin|sbin)/z [^\w\-\.\/]+_/.z ._-r)rsubstrip)commandname_maxZ manglednamer!r!r"_mangle_command1s  r,cCsLtjdftjdftjdftjdfg}x"|D]}|d|jr*|dSq*WdS)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_typestr!r!r" _node_type9s   r6z!----(?:-| )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|}|ddj|d7}|j}|rdfd d|Dn|}|d dj|d7}|j}|rfd d|Dn|}|d dj|d7}fd d|jD}|ddj|d7}|j} |rfdd| Dn| } |ddj| d7}|||S)zxReturn a string representation of this SoSPredicate with optional prefix, suffix and value quoting. z"%s"zdry_run=z, csg|] }|qSr!r!).0k)quotesr!r" sz&SoSPredicate.__str..zkmods=[,z], csg|] }|qSr!r!)r8s)r:r!r"r;sz services=[csg|] }|qSr!r!)r8p)r:r!r"r;sz packages=[c sBg|]:}ddd|dddd|dd qS)z{ cmdz: z, outputz }r!)r8Z cmdoutput)r:r!r"r;sz cmdoutputs=[csg|] }|qSr!r!)r8a)r:r!r"r;szarches=[])dry_runkmodsjoinservicespackages cmd_outputsarch) selfquoteprefixsuffixZpstrrDrFZpkgsZ cmdoutputsZarchesr!)r:r"Z__strs$  zSoSPredicate.__strcCs|jS)zReturn a string representation of this SoSPredicate. "dry_run=False, kmods=[], services=[], cmdoutputs=[]" )_SoSPredicate__str)rJr!r!r"__str__szSoSPredicate.__str__cCs|jddddS)zReturn a machine readable string representation of this SoSPredicate. "SoSPredicate(dry_run=False, kmods=[], services=[], cmdoutputs=[])" Tz SoSPredicate())rKrLrM)rN)rJr!r!r"__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)rRrS ValueError)rJitemsrequiredr!r!r"_check_required_states z"SoSPredicate._check_required_statecCs8|j|}|dkr$|j|j|n|j|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 rTN)rW_failedappend _forbidden)rJZtestitemZ_reqr!r!r"_failed_or_forbiddens z!SoSPredicate._failed_or_forbiddencCsd|j s|jjdrdSg}x4|jD]*}|jj|}|j||s$|jd|q$W|j||jdS)Nallow_system_changesTrD)rD_owner get_optionis_module_loadedrZr]rXrW)rJZ_kmodskmodresr!r!r" _eval_kmodss   zSoSPredicate._eval_kmodscCsV|js dSg}x4|jD]*}|jj|}|j||s|jd|qW|j||jdS)NTrF)rFr_is_service_runningrZr]rXrW)rJZ_svcssvcrcr!r!r"_eval_servicess   zSoSPredicate._eval_servicescCsV|js dSg}x4|jD]*}|jj|}|j||s|jd|qW|j||jdS)NTrG)rGr_ is_installedrZr]rXrW)rJZ_pkgspkgrcr!r!r"_eval_packagess   zSoSPredicate._eval_packagescCsZd|ksd|krdSt|d}|ddkr0dSx$|djD]}|d|kr>dSq>WdS)z*Does 'cmd' output contain string 'output'?r?r@FstatusrT)r splitlines)rJZ cmd_outputresultliner!r!r"_eval_cmd_outputs   zSoSPredicate._eval_cmd_outputcCsf|js dSg}xD|jD]:}|j|}|j||s|jd|dd|dqW|j||jdS)NTrHr?z: r@)rHrorZr]rXrW)rJZ_cmdsr?rcr!r!r"_eval_cmd_outputs s   zSoSPredicate._eval_cmd_outputscCs|js dS|jjj}ddj|jd}|jddkr\tj||rX|jdj |dSdStj||rldS|j dj |dS) NTz(?:|rPrIrT architectureF) rIr_policyget_archrErWrmatchr[rZrY)rJZ_archrr!r!r" _eval_archs   zSoSPredicate._eval_archcCsRd}d}xD|jjD]6\}}|s"qt|}|||djdd|Df7}qW|S)z\Return a string informing user what caused the predicate to fail evaluation r$zrequired %s missing: %s.z, css|] }|VqdS)Nr!)r8vr!r!r" 5sz.SoSPredicate._report_failed..)rYrVsetrE)rJmsg_substrkeyvalr!r!r"_report_failed+s$zSoSPredicate._report_failedcCsRd}d}xD|jjD]6\}}|s"qt|}|||djdd|Df7}qW|S)zxReturn a string informing the user that a forbidden condition exists which caused the predicate to fail r$zforbidden %s '%s' found.z, css|] }|VqdS)Nr!)r8rwr!r!r"rxBsz1SoSPredicate._report_forbidden..)r[rVryrE)rJrzr{r|r}r!r!r"_report_forbidden8s$zSoSPredicate._report_forbiddencCs*|j|j|jrdndg}dj|jS)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$ )r~rrCrElstrip)rJrzr!r!r"report_failureEszSoSPredicate.report_failurecCsTt|j|j|j|j|j|jgs$dS|joR|joR|j oR|j oR|j oR|j S)z#Predicate evaluation hook. T) rRrDrFrGrHrIrCrdrgrjrprv)rJr!r!r"__bool__PszSoSPredicate.__bool__c s|_t|_t|_t|_t|_t|ts>|g}|_|jjdj B_ dddddd_ j j fddj Dgggggd_ gggggd_dS)z-Initialise a new SoSPredicate object cmdlineoptsrR)rDrFrGrHrIcs(i|] \}}|j|kr||qSr!)rW)r8r9rw)rWrJr!r" msz)SoSPredicate.__init__..)rDrFrGrHrrN)r_listrDrFrGrI isinstancerHcommonsrCrWupdaterVrYr[) rJownerrCrDrFrGrHrIrWr!)rWrJr"__init__^s"       zSoSPredicate.__init__)Fr$r$)__name__ __module__ __qualname____doc__r_rCrDrFrGrHrIrNrOrQrXr]rdrgrjrorprvr~rrrrr!r!r!r"r7Ms2'        r7c@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|jj|dS)N)__dict__r)rJkwargsr!r!r"rszSoSCommand.__init__cCsdjddt|jjDS)zIReturn a human readable string representation of this SoSCommand z, css |]\}}|d|VqdS)=Nr!)r8Zparamr}r!r!r"rxsz%SoSCommand.__str__..)rEsortedrrV)rJr!r!r"rOs zSoSCommand.__str__N)rrrrrrOr!r!r!r"r|s 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|_|dk r:t|tsB|g}n|jg}||_dS)N) namedefaultdesc long_descvaluerr __class__val_type)rJrrrrrr!r!r"rs zPluginOpt.__init__cCs@d|jd|jdd|jd|jg}ddj|dS) Nzname=zdesc=''zvalue=zdefault=(z, rP)rrrrrE)rJrVr!r!r"rOs    zPluginOpt.__str__cCs|jS)N)rO)rJr!r!r"rQszPluginOpt.__repr__c std|jkrt|_dStfdd|jDsg}xX|jD]N}|dkrNq@|jdkrd|jdq@|jdkrz|jdq@|jdkr@|jd q@Wtd |jd |j d d j |dtj|_dS)Nr$c3s|]}t|VqdS)N)r)r8Z_t)r}r!r"rxsz&PluginOpt.set_value..boolz boolean true/false (on/off, etc)strzstring (no spaces)intzinteger valueszPlugin option 'r'z' takes z, z, not ) typerrrrRrrZ ExceptionpluginrrE)rJr}Zvalidr5r!)r}r" set_values"       .zPluginOpt.set_value)rNr$r$N)rrrrrrZenabledrrrrrrrOrQrr!r!r!r"rs  rc@seZdZdZdZfZfZfZfZfZ fZ dZ dZ dZ fZdZeZeZdZiZiZgZdZdZdZdZddZdd Zd d Zd d ZddZdddZ ddZ!e"ddZ#e"ddZ$ddZ%ddZ&e'ddZ(e'ddZ)e'd d!Z*e'd"d#Z+d$d%Z,d&d'Z-d(d)Z.d*d+Z/d,d-Z0d.d/Z1d0d1Z2d2d3Z3d4d5Z4d6d7Z5d8d9Z6d:d;Z7dd?Z9d@dAZ:dBdCZ;dDdEZddJdKZ?ddLdMZ@ddOdPZAdQdRZBddSdTZCdUdVZDdWdXZEdYdZZFd[d\ZGd]d^ZHd_d`ZIdadbZJdcddZKdedfZLdgdhZMdidjZNddkdlZOdmdnZPdodpZQddrdsZRdtduZSdvdwZTdxdyZUdzd{ZVddd|dgddfd}d~ZWddd|ddddgggddf ddZXddd|ddddgddf ddZYddZZddd|ddddgddddf ddZ[dddd|d|ddddddddgdddddddfddZ\ddZ]ddZ^dddZ_ddZ`ddZadddZbddZcddgfddZddddd|d|dddddddgddddddfddZedddd|d|ddddddddgdfddZfdddZgddZhddZid ddZjd ddZkd ddZld ddZmd ddZndddZodddZpdddZqdddZrddZsddZtddZuddZvdddZwddZxddÄZyddńZzddDŽZ{ddɄZ|dd˄Z}dd̈́Z~ddτZejdgfddфZddӄZddՄZddׄZddلZddۄZdd݄Zdd߄ZddZddZdddZddZddZddZddZddZddZddZddZddZddZdddZdddZdS(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`` Nr&Fzcs:g_g_t_g_d_|_g_t_g_ g_ g_ i_ |d_ |d_|d_d_|dj_|dj_i_g_djkrjdntjd_j jjxj D]}jj |_qWx$jD]}j|_|j |j<qWtfdd tjD_ j!t"dS) Nr$sysrootrsdevicesrsoslogZsosc3s|]}j|VqdS)N)is_snap_installed)r8ri)rJr!r"rxOsz"Plugin.__init__..)# copied_filesexecuted_commandsry _env_varsalerts custom_textrforbidden_paths copy_pathscontainer_copy_paths copy_strings collect_cmdsoptionsrrsrmanifest skip_files skip_commandsdefault_environment_tail_files_listloggingZ getLoggerrrget_default_plugin_optsrr option_listrRrrGis_snap set_predicater7)rJrZpoptoptr!)rJr"r+s>         zPlugin.__init__cCs0tdd tddtdd tddtddtd dd S) Ntimeoutr-z7Timeout in seconds for plugin to finish all collections)rrrz cmd-timeoutz4Timeout in seconds for individual commands to finishpostprocTz(Enable post-processing of collected data)rz cmd-timeoutrr)rrr)rJr!r!r"rUszPlugin.get_default_plugin_optscCs||_|jjdd|jjdd|jjdd|jjdd|jjdd|jjdd|jjdd|jjd d|jjd d|jjd |j|jjd d |jjd|j|jjdg|jjdg|jjdi|jjdi|jjdgdS)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)rJrr!r!r"set_plugin_manifestes$zPlugin.set_plugin_manifestcCs.t|tstd||_|jd|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_debug)rJenv_varsr!r!r"set_default_cmd_environments  z"Plugin.set_default_cmd_environmentcCs4t|tstd|jd|d|jj|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)rrrrrr)rJrr!r!r"add_default_cmd_environments z"Plugin.add_default_cmd_environmentcCs8|dkr|jSt|ts td|jj}|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)rJenv_envr!r!r"_get_cmd_environments   zPlugin._get_cmd_environmentc Csd}yl|j|}t|j|}|dkr,|}nB|dk rT|dkrT|tkrJ|}qnt|}n|dk rj|dkrj|}ndSWntk r|SX|dk r|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-rrr)r`rr rU)rJZoptnameZ plugoptnameZdefault_timeout_timeoutZ opt_timeoutZ own_timeoutr!r!r"timeout_from_optionss$  zPlugin.timeout_from_optionscCs|jdd|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)rJrr!r!r"rszPlugin.timeoutcCs|jdd|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_timeoutz cmd-timeout)rr)rJZ _cmdtimeoutr!r!r"rszPlugin.cmdtimeoutcCs*d|_|jjdtj|jjdddS)NTrr) _timeout_hitrrrZnow)rJr!r!r"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`` )r)rJr!r!r" check_timeoutszPlugin.check_timeoutcCs|jr |jS|jjS)zsGet the name of the plugin :returns: The name of the plugin, in lowercase :rtype: ``str`` ) plugin_namerlower)clsr!r!r"rsz Plugin.namecCs$|jdkr|j|n |j|dS)N)rdisplay_self_helpdisplay_plugin_help)rsectionr!r!r" display_helps  zPlugin.display_helpcCsddlm}|j|jjd|jd}y6d}|jd}|tkrP|jrP|j}|jr`||j7}Wnt k rzd}YnX|j d|r|n|t |j |j |j|j|j|jgs|j dnrx>d2D]6}t||dr|j d|ddjt||ddqWt|dr2|j ddjdd|jDdd|jr`|j ddjdd|jDddt|dr|j ddjdd|jDdd|jtjk r|j d|jsdS|jd}|j dtd|jd d!|j td"d#d$d%d&d'd(d)d&ddd#d*}x|jD]} | j} | dks:| dkr>d+} t| jtr^| jrZd,} nd-} d#d$| jd&| d(| jd&} |j t j!| ||d.dd| j"r|d/} d3} |j t j!| j"| | | d1ddqWdS)4Nr)TERMSIZEz Plugin Information - z8 Detailed information is not available for this plugin. r$r-z z)This plugin is always enabled by default.rGrr kernel_modsrFz Enabled by z: z, F)newlinerz+Enabled by containers with names matching: css|] }|VqdS)Nr!)r8cr!r!r"rx9sz-Plugin.display_plugin_help..z%Enabled with the following profiles: css|] }|VqdS)Nr!)r8r>r!r!r"rx@sverify_packagesz) Verfies packages (when using --verify): css|] }|VqdS)Nr!)r8rir!r!r"rxHszThis 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<20ZDefaultz<30Z Description6z None/UnsetzTrue/Onz False/Off)widthsubsequent_indent )rZinitial_indentr)rGrrrrFz )#Zsos.helpr set_titlertitle short_desc__mro__rrradd_textrRrGrrrrFrgetattrrEprofileshasattrrrr add_sectionrrrrrrtextwrapZfillr)rrrZmissingZ_docZ_scZtrigoptsecZ opt_indentrZ_defZ_ln_sizeZspacer!r!r"rs             zPlugin.display_plugin_helpcCs|jd|jdtdd|jd}|jd|jdtdd td d |jd td d|jd}|jdtddtdd|jd}ddd}|jddjdd|jDdddS)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>8z<30Nr!)r8Zsecrr!r!r"rxsz+Plugin.display_self_help..F)r)rrrrrErV)rrZsubsecrZseealsoZ_alsor!r!r"r}s,    zPlugin.display_self_helpcCs d|jd|jddjS)Nz[plugin:z] zutf-8replace)rencodedecode)rJrzr!r!r" _format_msgszPlugin._format_msgcCs|jj|j|dS)N)rerrorr)rJrzr!r!r" _log_errorszPlugin._log_errorcCs|jj|j|dS)N)rZwarningr)rJrzr!r!r" _log_warnszPlugin._log_warncCs|jj|j|dS)N)rinfor)rJrzr!r!r" _log_infoszPlugin._log_infocCs|jj|j|dS)N)rdebugr)rJrzr!r!r"rszPlugin._log_debugcCs4|js |S|jr0|j|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 startswithlen)rJpathr!r!r" strip_sysroots zPlugin.strip_sysrootcCs|jtjjtjkS)zDetermine if the configured sysroot needs to be used :returns: ``True`` if sysroot is not `/`, else ``False`` :rtype: ``bool`` )rosr abspathsep)rJr!r!r"r szPlugin.use_sysrootcCs(|jpd}||jjg}tjj||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_dirrr  commonprefix)rJZ_sysrootpathsr!r!r"tmp_in_sysroots zPlugin.tmp_in_sysrootcCst|jjj|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 rspackage_managerZall_pkgs_by_name)rJ package_namer!r!r"rhs zPlugin.is_installedcCs"|jjj|}|dk o |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)rsrZ pkg_by_name)rJrrir!r!r"rs zPlugin.is_snap_installedcCs|jjj|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`` )rs init_system is_service)rJrr!r!r"rs zPlugin.is_servicecCs|jjj|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`` )rsrZ is_enabled)rJrr!r!r"is_service_enableds zPlugin.is_service_enabledcCs|jjj|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`` )rsrZ is_disabled)rJrr!r!r"is_service_disableds zPlugin.is_service_disabledcCs|jjj|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`` )rsrZ is_running)rJrr!r!r"re$s zPlugin.is_service_runningcCs|jjj|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`` rk)rsrget_service_status)rJrr!r!r"r0s zPlugin.get_service_statuscCs|jjj|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`` )rsrget_service_names)rJrr!r!r"r;s 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) predicate)rJpredr!r!r"rFszPlugin.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_predicate)rJr r!r!r"set_cmd_predicateNszPlugin.set_cmd_predicatecCs&|dk r |S|r |jdk r |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)r!r)rJr?r r!r!r" get_predicateXs zPlugin.get_predicatecCs"|j||d}|dk rt|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?r NF)r#r)rJr?r r!r!r"test_predicatens zPlugin.test_predicatecCs>|dkrt|}d|d|j}|r0|d7}|j|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 'z': z3 Use '--allow-system-changes' to enable collection.)r7rr)rJr?r changesrzr!r!r"log_skipped_cmds zPlugin.log_skipped_cmdr$cCs>|js dS|jd||r,td|nt}|j|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)rJr?rrr!r!r"do_cmd_private_subs  zPlugin.do_cmd_private_subc CsHd|d}t|dr|jn|}|jd|d|d|d|jsHdSd}yx|jD]}|d dkrhqV|d d kr|jd |d dqVtj|d|rVtjj|j d|d }|jd|d|j j |} t j ||| j\} }|rV|j j| |qVWWnBtk rB} z$d} |j| |d | fd}WYdd} ~ XnX|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`` *patternzsubstituting 'z' for 'z' in commands matching 'rrNfilebinaryyesz3Cannot apply regex substitution to binary output: 'exer?cmddirzapplying substitution to 'z-regex substitution failed for '%s' with: '%s')rr,rrrfnmatchrr rErrZ open_filersubnr add_stringrr) rJr?regexpsubstZglobstrr, replacementsZcalledr readablermerzr!r!r"r(s6     zPlugin.do_cmd_output_subcst|jd|tj|j|r.td|nt}fdd|jD}x(|D] }|d}|s^qL|j|t|qLWdS)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|qS)srcpathr!)r8r )rur!r"r;sz.Plugin.do_file_private_sub..dstpathN)rrcompilerur'r do_file_subr))rJZ pathregexrr file_listir r!)rur"do_file_private_subs  zPlugin.do_file_private_subcCsyd|j|}|jd|d|jt|drDd|d|d|jn||sRdS|jj|||}Wn\tk r}z@|jtjkrd}|j||nd}|j |||fd}WYd d }~XnX|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 'rr,zsubstituting 'z' for '%s' in 'rz-file '%s' not collected, substitution skippedz-regex substitution failed for '%s' with: '%s'N) _get_dest_for_srcpathrrr,rr=OSErrorerrnoENOENTr)rJr:r5r6r r7r9rzr!r!r"r=s" " zPlugin.do_file_subcCs0t|tr|g}x|D]}|j|ddqWdS)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)rJZ pathspecsr r!r!r"do_paths_http_sub+s  zPlugin.do_paths_http_subcsRt|dstj|}|jfdd|jD}x|D]}|j|d||q4WdS)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`` rucsg|]}|dr|qS)r:r!)r8r )rur!r"r;Ksz,Plugin.do_path_regex_sub..r:N)rrr<rurr=)rJZpathexpr5r6r>r-r!)rur"rE:s    zPlugin.do_path_regex_subcCs t||S)N)r#)rJrrr!r!r"do_regex_find_allOszPlugin.do_regex_find_allc Cstj|}tjjtjj||}tjj|}|j|rP|jd|d|dStjj|rtjj tjj|}tjj ||d}|j r|t tj tjd}|jd|d|dn|}|jd|d|d |j||j|}|jj|||j|r|jd |d dS|jj||d |d ytj|WnFtk r}z(|jdkrt|jd |ddSWYdd}~XnX|jd|d|d||kr|j|jo|jj} |j|| dn|jd |ddS)Nzskipping 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...r/)r:r;symlinkZpointsto(z3' is part of a file system loop, skipping target...znormalized link target 'z' as ')forcez&' points to itself, skipping target...)rreadlinkr rEdirnamenormpath_is_skipped_pathrisabsrealpathrelpathr r rpardirrrradd_linkrrZr.rBrCr rrsZ _in_container _do_copy_path) rJr:ZlinkdestdestZabsdestZrealdirZreldestr;r9rKr!r!r" _copy_symlinkRsF    "     zPlugin._copy_symlinkcCsyHxB|j|D]4}|jd|d|dtjj||}|j|qWWntk r}zd|jtjksltj rd}|j d|d|dS|jtj krd}|j d|d |ddSWYdd}~XnXdS) Nzrecursively adding 'z' from 'rzPermission deniedz _copy_dir: 'z' z)Too many levels of symbolic links copyingz _copy_dir: z ') rrrr rErUrBrCZEPERMZEACCESrZELOOPr)rJr:rr r9rzr!r!r" _copy_dirs zPlugin._copy_dircCs:|jr|j|}x"|jD]}||dkr|dSqWdS)Nr:r;)r rr)rJr:Zcopiedr!r!r"rAs     zPlugin._get_dest_for_srcpathcstfdd|jDS)Nc3s|]}tj|VqdS)N)rru)r8forbid)r r!r"rxsz,Plugin._is_forbidden_path..)rRr)rJr r!)r r"_is_forbidden_pathszPlugin._is_forbidden_pathcstfdd|jjDS)Nc3s|]}tj|VqdS)N)r2)r8fp)r r!r"rxsz3Plugin._is_policy_forbidden_path..)rRrsr)rJr r!)r r"_is_policy_forbidden_pathsz Plugin._is_policy_forbidden_pathcCs$x|jD]}tj||rdSqWdS)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)rr2)rJr Z _skip_pathr!r!r"rOs  zPlugin._is_skipped_pathcCs:tj|j}tj|j}|j}|jj||tj||dS)N)rmajorst_rdevminorr3rZadd_nodemakedev)rJr r4Zdev_majZdev_minmoder!r!r" _copy_nodes  zPlugin._copy_nodecCs~|jr dS|j|r*|jd|ddS|s2|}|jrD|j|}ytj|}Wn&tk rx|jd|ddSXt j |j r|j |dSt j |j rtj|tjr|j|s|jj|dS|j|dSt j|j pt j |j s t|}|jd|d|d|j||dS|jd|d|d|j d @sT|jjd |n|jj|||d |jj||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. Nzskipping forbidden path 'rzfailed to stat 'z creating z node at archive:'zcopying path 'z' to archive:'i$r$)rKno)r:r;rI)rrZrr rrlstatrBrr.S_ISLNKr3rWS_ISDIRaccessR_OKrrZadd_dirrXS_ISREGr6rbr4Zadd_filerrZ)rJr:rVrKr4Zntyper!r!r"rUsJ          zPlugin._do_copy_pathcslt|tr|g}jr*fdd|D}x<|D]4}jd|dd|krXtj|}jj|q0WdS)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|]}j|qSr!)r)r8r )rJr!r"r;sz-Plugin.add_forbidden_path..zadding forbidden path 'rr+N)rrr rr2 translaterrZ)rJZ forbiddenrYr!)rJr"add_forbidden_path s   zPlugin.add_forbidden_pathcCsR||jkrNy|j|j|dStk rL}z|j|WYdd}~XnXdS)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)rJ optionnamererrr!r!r" set_options  zPlugin.set_optionrcCsNd }||krt|jd |S||jkrJ|j|}| s@|jd k rF|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_logsr^r journal_sizelog_sizersinceverifyrN)ror^rrprqrrrrs)rrrr)rJrlrZglobal_optionsrr!r!r"r`4s  zPlugin.get_optioncCs|jj|dS)N)rr)rJrr!r!r"_add_copy_pathsTszPlugin._add_copy_pathscCs:x(|D] }t||tr||g||<qW|jj|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)rJtagdictrr!r!r" add_file_tagsWs zPlugin.add_file_tagscCs6g}x,|jjD]\}}tj||r|j|qW|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 )rurVrruextend)rJrtagsr|r}r!r!r"get_tags_for_filehs  zPlugin.get_tags_for_filecCszxt|jjD]f\}}|g|d}g}x2|jD](}tj||dr,|j|djdq,W|r ||d<|jjj|q WdS)zAfter file collections have completed, retroactively generate manifest entries to apply tags to files copied by generic copyspecs ) specification files_copiedryr:r;r&r|N) rurVrrrurZrrr)rJZ file_regextagZ manifest_dataZ matched_filescfiler!r!r"generate_copyspec_tagsxs zPlugin.generate_copyspec_tagsTc sd|jdr|jdtjdtjd|jdd|j|dsj|jd|d |j|dd dS|dkr||jd }|jd rd}|r|d29}|sdSt|tr|g}t|tr|g}dd} ddfdd} x|D]} | ot | sdS|s:|j r|j| } |j | } t | dkr@qn| g} g} t | dkr| | d}|rn| j || j |j| d| j |tt| } |rt|tr|g}x|D]}|j| r|dkrؐqd}|rd| }|j|||d}|ddkr^yt|d}||kr&d}Wn2tk rZ|jd| d|dwYnXn$|jd| d|d |dq|jj || ||| |f|jd!| d"|d#qWqsƈrtt| | } | jdd$d}d}g}x| D]}||jkr|jd%|d#q|j|r@|jd&|d#q|j|rb|jd'|d#q|j|r|jd(|d#q|r|jd)|d*qytj|tj}Wn>t k r|j!|rd}n|jd+|d,wYnX||7}|rv||krvd}|rt"|r6|jd-|d.q|jd-|d/|||}|j#j ||f|j |j$d0n*|j |j$d0|j%|g|o||k}qW|s|j&r|j&j'j | || d1qWdS)3aAdd 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`. Nrrz".*((\.(zip|gz|bz2|xz))|[-.][\d]+)$^Zetcz/*)r zskipped copy spec 'z' due to predicate (rPrqroiFcSsB|jd rdS|jdd }|jdd}|jdr>|jd dSdS)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. /proc/sysNr&r--r%.conf.log.txtr')rrr)rrr)r splitrendswith)rZ_fnamer!r!r"get_filename_tags    z.Plugin.add_copy_spec..get_filename_tagc Ss&y tjj|Stk r dSXdS)z Files should be sorted in most-recently-modified order, so that we collect the newest data first before reaching the limit.rN)rr getmtimerB)r r!r!r"rs z&Plugin.add_copy_spec..getmtimecs\j|dksj|dk r dS|}tj|}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 filedatetime)configfile_patternrlogarchive_patternmaxagerrr!r" time_filters  z)Plugin.add_copy_spec..time_filterrr-z stat -c %s ) containerrunasrkr@Tzunable to determine size of 'z' in container 'z'. Skipping collection.z stat of 'z' failed, skipping collection: zadded collection of 'z' from container 'r)r|reversezskipping redundant file 'zskipping forbidden path 'z skipping policy forbidden path 'zskipping excluded path 'z skipping 'z' over size limitzfailed to stat 'z ', 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{r|ryi)(r`rr<rr$rr#rrr r _expand_copy_specrZrxrzrrycontainer_existsexec_cmdrrUrrfiltersortrrZr\rOrr.ST_SIZErBrrrrrtrr)rJZ copyspecs sizelimitrtailitr ryrrrrcopyspecrZ _spec_tags_specconZ_tailr?retZconsizeZ current_sizeZ limit_reachedZ_manifest_files_fileZ file_sizeZadd_sizer!)rrrrrrr" add_copy_specs0                                zPlugin.add_copy_specrcsg}t| tr| g} t|tr$|g}t|j|}rVttrDgfdd|D}r|ttrjgfdd|D}|j| |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 |]}tjd|VqdS)z(.*)?N)rru)r8Zwl)dr!r"rxsz3Plugin.add_device_cmd...)rR)r8) whitelist)rr"r;sz)Plugin.add_device_cmd..cs&g|]tfddDsqS)c3s |]}tjd|VqdS)z(.*)?N)rru)r8Zbl)rr!r"rxsz3Plugin.add_device_cmd...)rR)r8) blacklist)rr"r;s) rrchrootrunatrr. prepend_pathryprioritysubdirN)rrrrrx_add_device_cmd)rJcmdsrrrrrrr.rrrryrr _dev_tagsZ_devsr!)rrr"add_device_cmds&5       zPlugin.add_device_cmdc Cst|tr|g}t|tr |g}|p,|jd}xd|D]\} xV|D]N}|g}|j| | rb|j| |}| d|i}|j||||||||| | d q>Wq4WdS)zCRun a command against all specified devices on the system. rqZdev) r?rrrrrr.ryrrN)rrr`rxr_add_cmd_output)rJrrrrrrrr.rryrrr?ZdevicerZ_cmdr!r!r"rs"       zPlugin._add_device_cmdcKsLd|kr|jdnt|}d|kr*d|d<d|kr:d|d<ttf|dd rt|jdsd|dd krtd |d<d |d <d|kr|jdtf|}|jd t|x4|jD]*}tj|j |r|jd |j ddSqW|j d |dr4|j j |d}t|dddk rd|j d}|jd|j d|n|j|j ||jddS)z?Internal helper to add a single command to the collection list.r rrr%Fsnap_cmdrorrTto_filezpacked command: zskipping excluded command 'rN)r?r r$rz , as the z userzadded cmd output ')r%)popr7rrr`rrrr2r?r$rrZrrr&r%)rJrr soscmdZ _skip_cmduserr!r!r"rs0    zPlugin._add_cmd_outputc st|tr|g}r,fdd|D}nfdd|D}|sbd|rLdnd| rX| nd}nd}xB|D]:}j|r|dnd d |d ||||||| | d qlWd 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))rr)container_path_exists)r8r>)rrrJr!r"r;,sz*Plugin.add_dir_listing..csg|]}j|r|qSr!)r )r8r>)rJr!r"r;0sZalZRr$ZlptreeZlsz -r) rrrr rryrrsuggest_filenameN)rradd_cmd_output)rJrr recursiverrrr rryrrrZ extra_optsrr r!)rrrJr"add_dir_listings   zPlugin.add_dir_listingcCst|tr|g}t|dkr.|s$|r.|jd| dkr@|jd} | dkrT|jdd} x|D]|}d}|r|}||f}|j||||d}|s|jd|d |d qZ|j||||||||| | | | || |||||||d qZWdS) 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 listNrqT)r?)runtimerzSkipping command 'z' as the requested container 'z' does not exist.)r?r root_symlinkrstderrrrrr.rr rryr% foregroundr cmd_as_tagr container_cmdrr) rrr rr`r#fmt_container_cmdrr)rJrrrrrrrrr.rr rr%rryrrrrrrrr?rZocmdr!r!r"r@s6Z      zPlugin.add_cmd_outputcCs:x(|D] }t||tr||g||<qW|jj|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)rJrvr?r!r!r" add_cmd_tagss zPlugin.add_cmd_tagscCs,x&|jjD]\}}tj||r |Sq WgS)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`` )rrVrru)rJr?r|r}r!r!r"get_tags_for_cmds  zPlugin.get_tags_for_cmdcCsBtjj|jjd|j}|r,tjj||}|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)rr rErrrmakedirs)rJrZmakeZcmd_output_pathr!r!r"get_cmd_output_paths zPlugin.get_cmd_output_pathcGst|f|S)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)rJr5fnamesr!r!r" file_greps zPlugin.file_grepcCs|jj}t||S)N)rr+r,)rJr0r+r!r!r"r,s zPlugin._mangle_commandc Cs|j}|r|d|7}tjj|jd|}|j|}tjjtjj|jj||rd}|jj }xvd|}|} |t | t |kr| d|t | t |} | |} tjjtjj|jj|| s| }P|d7}qfWtjj||S)z@The internal function to build up a filename based on a command.r&r1r-r'N) rrr rErr,existsrrr+r ) rJr0rZ plugin_dirZoutdiroutfnZincr+rMZnewfnr!r!r"_make_command_filenames*      zPlugin._make_command_filenamecCs<t|ts|g}x&|D]}|jj||j|jgqWdS)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)rJrrr!r!r" add_env_var s  zPlugin.add_env_varcCs|jd|ds,|jd|j|dddS|r4dnd}tjj||j|}t|tr\|g}|j j |||f|j 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 F)r?r z!skipped string due to predicate ()r rPNr sos_stringszadded string as 'r) r$rr#rr rErrrrrZr)rJZcontentfilenamer Zplug_dirryZsos_dirr!r!r"add_string_as_file- s  zPlugin.add_string_as_filec'Cs<|jr dS|dkr|j}g}t|tr,|g}|j||j|j||r^|jtjdd|t t |}|j |}|s|j dj dkr|j}nd}|r|j|| }n |j|| }|t|j ddd}|r|jd|d |jj|ttjj|jj|}nd }t}t||||||| | |j| |||d }t}||}|d d krd|d|d}|j||rd|} |j|| |jdd|jddd||r|nd|d|d |||||d }!|d dks|d dkr|r\|dkr\|j dj dkr\|jd|jdd|dt||d ||| | |j||d }t|}|jd|d|d d1kr|jr|jj j|!|S|jd|jdd|d | d!|dr|jd|jdd"|}"|j!d#d$d%}|r|jj|td&d'}#tj"||#|sJ| r8|jj#|d(|n|jj$|d(||drtjj|jj|}$tjj|jj|"}%tjj%|$|%}&|&j!d)d*d}&|jj&|&|"|r|jj&|||j'j||| rd+nd,d-|rtjj|jj|nd*|d.<|jr8||!d/<||!d0<|jj j|!|r8|j(|!j)|||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%ralwaysr1r-z collecting 'z' output directly to diskF) rrrchdirrr.rpollerrrtacrrk|z command 'z' timed out after r=z3 - output up until the timeout may be available at rr truncated) r* parametersexecfilepathrZ return_coderrrrry~r&z' not found in z - re-trying in host root) rrrrr.rrrrzcould not run 'z': command not foundzcollected output of 'z' in z (changes=rPz' was truncatedrrz.tailedT)rKr@z../r$r/rc)r?r-r.rrr)rr)*rrrrrxrrZrr(rryrrrrrr rr check_pathrrr rEZget_archive_pathrrrrrrrrrrenameZ add_binaryr4rRrTr_add_container_cmd_to_manifestr)'rJr?rrrrrrrr.rrr%rryrrrrrrZ_tagsrrootrZ outfn_stripZout_filerHrmendrwarnrzZ manifest_cmdZlinkfnrVZ _outfn_pathZ _link_pathZrpathr!r!r"_collect_cmd_outputR 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`` T)r?r )r%Nr$)rkr@r) rrrrrrrr.rrrryr)r$r&r)rJr?rrrrrrrr.rr r%rrryrr!r!r"collect_cmd_output s=zPlugin.collect_cmd_outputc Csddd}|jd|ds|S|dkr*|j}|s>|jdjdkrF|j}nd}|j|}| r|jdkr|jd|d | d |S|j| | s| dk r|j | || | | }n|jd|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$)rkr@T)r?r rrzCannot run cmd 'z' in container z: no runtime detected on host.z: no such container is running.)rrrr.rrrr) r$rrrrr_get_container_runtimerrrr)rJr?rrrrrr.r rrquotecmdrrZ_defaultrrr!r!r"rU s*7     zPlugin.exec_cmdcCs@||jjkrggd|jj|<|jj|dj|||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 )rrr)r{r|ryN)rrrZ)rJrr Zarcpathryr!r!r"_add_container_file_to_manifest s  z&Plugin._add_container_file_to_manifestc Cs|\}}||jjkr&ggd|jj|<||d<|jdd|d<|jddd|d<d |d |j}d |d }|r|n|j|}|d |} |jj| trtj ||jj | | |d <|jj|dj |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`` )rrrrrr*r-Nrzsos_containers/z/sos_commands/z ../../../../rr&r) rrrrr,rrrrrI dest_pathrZ) rJrcontupZ suggest_fnamer?rZ_cdirZ_outlocZcmdfnZconlnkr!r!r"r s  z%Plugin._add_container_cmd_to_manifestcCsX|dkr&d|jjjkrT|jjdSn.x,t|jjjD]}||kr8|jj|Sq8WdS)zjBased on policy and request by the plugin, return a usable ContainerRuntime if one exists Nr)rsZruntimeskeysr)rJrZ pol_runtimer!r!r"r szPlugin._get_container_runtimecCs4|j|p |j}|dk r0|j|p.|j|dk SdS)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_name)rJrr_runtimer!r!r"r s  zPlugin.container_existscs2|j}|dk r.|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) N)get_allcs g|]}tj|dr|qS)r-)rru)r8r)rr!r"r; sz6Plugin.get_all_containers_by_regex..)rget_containers)rJrrrZ _containersr!)rr"get_all_containers_by_regex s  z"Plugin.get_all_containers_by_regexcCs |j|}|dk r|j|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)rJrrrr!r!r"r s  zPlugin.get_container_by_namecCs.|j|d}|dk r*|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`` )rNT)r)rrr)rJrrrr!r!r"r' s   zPlugin.get_containerscCs|j|d}|dk r|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`` )rN)rZimages)rJrrr!r!r"get_container_images? s zPlugin.get_container_imagescCs|j|d}|dk r|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`` )rN)rZvolumes)rJrrr!r!r"get_container_volumesR s zPlugin.get_container_volumesc Ksh|j}|dk rdt|tr |g}xB|D]:}|j||}x(|D] }|j|d}|j|f|q.__expandr+T)r)rrgrhrrrrremoverxr rErrry)rJrZexpandedZrecursed_files_pathr!)rrJr"rE s     zPlugin._expand_copy_speccCs@x2t|jddD] }|jd|d|j|qW|jdS)NT)rzcollecting path 'r)rrrrUr)rJr r!r!r"_collect_copy_specsq szPlugin._collect_copy_specsc s>|js dS|j}|s$|jddS|js:|jddSx|jD]}|\}}}}}}|jd|d|dd|d|jd} |jj| |dkrtnt|jj | } |dkr|j ||t j j | jt j j|r|ndd n|j|d |d } |j| d |d } | ddkr|s$|dk r6|jj| d| |j||| ||jj|| dd| j|jdxȇfddt| jdDD]} d| }|j|r|jd|d|t j j| }t j j|rtj|n t j|n |jj|d|d| ddqWqD|jd|d|d| dqDWdS)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.z collecting 'z' from container 'rzsos_containers/r&)rzcat Fr)rrrkrr@rc)r:r;rIcsg|]}|jjqSr!)Z relative_toZas_posix)r8r-)base_dirr!r"r; sz8Plugin._collect_container_copy_specs..r+zskipping forbidden path 'z'from container zerror copying 'z': ) rrrZcheck_can_copyrrrrrrZget_copy_commandrr rMrstriprrrr4rrrZZ removesuffixrZrglobrZrrEisdirshutilZrmtreer)rJZrtrrr rrryrZarcdestrVZcpcmdZcpretZrelnameZabsnamefullnamer!)rr"_collect_container_copy_specsw sT   B      z$Plugin._collect_container_copy_specscCs|jjdddxj|jD]`}|jdt|d}t|dddk rTd|jd}|jd |jd ||jf|j qWdS) NcSs|jS)N)r)xr!r!r" sz&Plugin._collect_cmds..)r|zunpacked command: r$rz , as the z userzcollecting output of 'r) rrrrrrrr?rr)rJrrr!r!r" _collect_cmds s zPlugin._collect_cmdscCsx|jD]\}}|jd|d|}|dtjkr@|jtj}|jtjjdd}|jt|||tjj dtjj |}tjj |d|j |}|j j||qWdS)Nzcollecting tail of 'z' due to size limitrr'z.tailedr&r)rrrrrrr rr rRrMrErrrT)rJrr file_nameZstrfileZrel_pathZ link_pathr!r!r"_collect_tailed_files s   zPlugin._collect_tailed_filescCsx|jD]\}}}|jrdS|jd|dy:|jj|||jdd jdd}||d|jj|<Wqt k r}z|j d|d |WYdd}~XqXqWdS) Nzcollecting string as 'rr&r-r'r%)r ryzcould not add string 'z': r) rrrrr4rrrrrr)rJstringr ry_namer9r!r!r"_collect_strings szPlugin._collect_stringscCsDy |jWn2tk r>}z|jd|WYdd}~XnXdS)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)rJrmr!r!r"_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. Nr!)rJr!r!r"r szPlugin.collectc csyt}|j||d}|jj|t|jj|}t|ddd}|jd||VWdQRXt}||} |jd|d| t |t r|g}|j j j |||d Wn8tk r} z|jd |d | WYdd} ~ XnXdS) 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`` )rwzutf-8)encodingzmanual collection file opened: Nzmanual collection 'z' finished in )rrryzError with collection file 'z': )rrrrrropenrrrrrrrZr) rJrrryrHZ_pfnamer rrZrunrmr!r!r"collection_file s&  zPlugin.collection_filecCsZt}|j|j|j|j|j|j|jd|jdt|dS)zCollect the data for a plugin.zcollected plugin 'z' in N) rrrr rr rrr)rJrHr!r!r"collect_plugin' szPlugin.collect_pluginc Cs y|jStk rdSXdS)z8This function will return the description for the pluginzN)rr)rJr!r!r"get_description3 szPlugin.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|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) rRrrGrrrFr architecturesrr_check_plugin_triggers)rJr!r!r" check_enabled: s$          zPlugin.check_enabledcst|||||gsjStfdd|Dstfdd|Dstfdd|DstfddjDstfdd|Dstfdd|DojS)Nc3s|]}j|VqdS)N)r )r8r)rJr!r"rxl sz0Plugin._check_plugin_triggers..c3s|]}j|VqdS)N)rh)r8ri)rJr!r"rxm sc3s|]}t|jVqdS)N)r r)r8r?)rJr!r"rxn sc3s|]}j|VqdS)N)ra)r8mod)rJr!r"rxo sc3s|]}j|VqdS)N)r)r8rf)rJr!r"rxp sc3s|]}j|VqdS)N)r)r8Zcntr)rJr!r"rxq s)rRcheck_is_architecturer)rJrrGrrFrr!)rJr"re szPlugin._check_plugin_triggerscCs4|jdkrdSddj|jd}tj||jjS)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`` NTz(?:rqrP)rrErrursrt)rJrr!r!r"rt s zPlugin.check_is_architecturecCsdS)zwThis decides whether a plugin should be automatically loaded or only if manually specified in the command line.Tr!)rJr!r!r"default_enabled szPlugin.default_enabledcCs\x,|jD]"}|j|r|j||j|qWx(|jD]}|j|r6|jd|q6WdS)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)rFrrrrrar)rJrrbr!r!r"add_default_collections s     zPlugin.add_default_collectionscCs|jt|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)rrr)rJr!r!r"setup sz Plugin.setupcCsXt|ds2t|dr.|jr.dd|jD|_ndS|jj}|j|j}|rT|j|dS)NrrGcSsg|] }|dqS)$r!)r8r>r!r!r"r; sz'Plugin.setup_verify..)rrGrrsrZbuild_verify_commandr)rJZpmZ verify_cmdr!r!r" 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 )rr)r)rJr rrr!r!r"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 r)rJr r!r!r"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`` )rr)rJr r!r!r"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`` )rr)rJr r!r!r"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`` )rr)rJr r!r!r"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`` )rr)rJr r!r!r"r s zPlugin.listdircGst|f|d|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)rJr r>r!r!r"r s zPlugin.path_joincCsdS)zLPerform any postprocessing. To be replaced by a plugin if required. Nr!)rJr!r!r"r szPlugin.postproccCsvd}d}yTtj|}xD|D]<}t|j|ddd}|jj}||krLd}WdQRXqWWntk rpdSX|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`` Fz/proc/[0-9]*/cmdlinerzutf-8)rTN)rrrrr)IOError)rJprocessrk cmd_line_globcmd_line_pathsr Zpfilecmd_liner!r!r"check_process_by_names      zPlugin.check_process_by_namecCsg}d}tj|}xp|D]h}yLt|ddd4}|jjd}tj||r\|j|jddWdQRXWqtk r~wYqXqW|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`` z/proc/[0-9]*/cmdliner!zutf-8)rr&N) rrrr)rrurZrr")rJr#pidsr$r%r r r&r!r!r"get_process_pids%s    " zPlugin.get_process_pidscCsg}|j|}xl|D]d}y tjt|tj|j|Wqtk rv}z"|jd|d|d|WYdd}~XqXqWt 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 'z': N) r+rkillrsignalSIGUSR1rZrrrminr )rJr#Z signalledr*pidrmr!r!r"signal_process_usr1;s   .zPlugin.signal_process_usr1cCs8|dkr |jdjr |jdj}|j|jdd||S)Nr namespacesZnetwork)rr3filter_namespaces)rJ ns_patternns_maxr!r!r"get_network_namespacesWs zPlugin.get_network_namespacescCsg}d}|r*ddj|jjddd}xR|D]J}|rLttj|| rLq0|j||r0t||kr0|jd|dPq0W|S) zFilter a list of namespaces by regex pattern or max number of namespaces (options originally present in the networking plugin.) Nz(?:z$|r+z.*z$)z&Limiting namespace iteration to first z namespaces found) rErrrrrurZr r)rJZns_listr5r6Zout_nsr,nsr!r!r"r4]s   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)rrrrrrGrrrrFrrrrrrr rrrrrurrrr!rrrrrrrrpropertyrrrr classmethodrrrrrrrrrrr rrhrrrrrerrrr"r#r$r&r*r(r@r=rFrErGrWrXrArZr\rOrbrUrkrnr`rtrwrzrrrrrrrrrrrr,rrrrrrrrrrrrrrrrrrarrrrrrrr r rrr contextlibcontextmanagerrrrrrrrrrr rr rrrrrrr'r+r2r7r4r!r!r!r"rsr-* ,   f 9             8 %C <  N!* q   $2G S!            m,I  & +       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 N)rrrrr!r!r!r"r=zsr=c@seZdZdZdS) RedHatPluginz/Tagging class for Red Hat's Linux distributionsN)rrrrr!r!r!r"r>sr>c@seZdZdZdS) UbuntuPluginzTagging class for Ubuntu LinuxN)rrrrr!r!r!r"r?sr?c@seZdZdZdS) DebianPluginzTagging class for Debian LinuxN)rrrrr!r!r!r"r@sr@c@seZdZdZdS) SuSEPluginz*Tagging class for SuSE Linux distributionsN)rrrrr!r!r!r"rAsrAc@seZdZdZdS)OpenEulerPluginz/Tagging class for openEuler linux distributionsN)rrrrr!r!r!r"rBsrBc@seZdZdZdS) CosPluginz(Tagging class for Container-Optimized OSN)rrrrr!r!r!r"rCsrCc@seZdZdZdS)IndependentPluginz6Tagging class for plugins that can run on any platformN)rrrrr!r!r!r"rDsrDc@seZdZdZdS)ExperimentalPluginz=Tagging class that indicates that this plugin is experimentalN)rrrrr!r!r!r"rEsrEc@seZdZdZdS) AzurePluginzTagging class for Azure LinuxN)rrrrr!r!r!r"rFsrFcCsd|}|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_fqnamer!r!r" import_plugins rG)N)r?r@rArBrCrDrErFrGr!r!r!r" s~  H 1Q0