3 ܓizV@sddlZddlZddlZddlZddlZddlZddlZddlZddlZddl m Z ddl m Z ddl mZmZmZmZmZmZmZddlmZddlmZmZmZmZddlmZmZddlm Z dd l!m"Z#d d Z$iddd dd fddZ%GdddZ&dS)N)getpwuid)fill) NO_PRESETGENERIC_PRESETS PRESETS_PATHPresetDefaultsDESCNOTEOPTS)PackageManager)ImporterHelper import_moduleget_human_readablebold)IndependentPluginExperimentalPlugin) SoSOptions)_sosc Cs.d|}y t|tStk r(dSXdS)Nzsos.policies.distros.)r Policy ImportError)nameZ policy_fqnamer/usr/lib/python3.6/__init__.py import_policys   rTc Csd|kr|jdSddl}t|jj}xD|jD]8}x2t|D]&} | j|dr>| ||||d|d<Pq>Wq0Wtj dkr~t dd|kr|jjj |d<|dS)Npolicyr)remote)sysrootinit probe_runtime remote_execlinuxz%SoS is not supported on this platform) getZsos.policies.distrosr ZpoliciesZdistrosZ get_modulesrchecksysplatform ExceptionZGenericLinuxPolicy) cacherrrr Z remote_checksoshelpermodulerrrrload s       r+c@sneZdZdZedZdZdZdZdZ dJgZ dZ dZ dZ deiZeZd ZdKd d ZedLddZeddZeddZddZddZddZddZddZddZd d!ZdMd"d#Z d$d%Z!d&d'Z"d(d)Z#d*d+Z$d,d-Z%d.d/Z&d0d1Z'd2d3Z(d4d5Z)ed6d7Z*dNd8d9Z+d:d;Z,dd?Z.d@dAZ/dBdCZ0dPdDdEZ1d d d e2fdFdGZ3dQdHdIZ4d S)RraPolicies represent distributions that sos supports, and define the way in which sos behaves on those distributions. A policy should define at minimum a way to identify the distribution, and a package manager to allow for package based plugin enablement. Policies also control preferred ContainerRuntime()'s, upload support to default locations for distribution vendors, disclaimer text, and default presets supported by that distribution or vendor's products. Every Policy will also need at least one "tagging class" for plugins. :param sysroot: Set the sysroot for the system, if not / :type sysroot: ``str`` or ``None`` :param probe_runtime: Should the Policy try to load a ContainerRuntime :type probe_runtime: ``bool`` :param remote_exec: If this policy is loaded for a remote node, use this to facilitate executing commands via the SoSTransport in use :type remote_exec: ``SoSTranport.run_command()`` :cvar os_release_name: The name of the distribution as it appears in the os-release (-esque) file for the NAME variable. :vartype os_release_name: ``str`` :cvar os_release_id: The ID variable to match in a distribution's release file. :vartype os_release_id: ``str`` :cvar os_release_file: The filepath of the distribution's os-release file :vartype os_release_file: ``str`` :cvar vendor: The name of the vendor producing the distribution :vartype vendor: ``str`` :cvar vendor_urls: List of URLs for the vendor's website, or support portal :vartype vendor_urls: ``list`` of ``tuples`` formatted ``(``description``, ``url``)`` :cvar vendor_text: Additional text to add to the banner message :vartype vendor_text: ``str`` :cvar name_pattern: The naming pattern to be used for naming archives generated by sos. Values of `legacy`, and `friendly` are preset patterns. May also be set to an explicit custom pattern, see `get_archive_name()` :vartype name_pattern: ``str`` ayThis command will collect system configuration and diagnostic information from this %(os_release_name)s system. For more information on %(vendor)s visit: %(vendor_urls)s The generated archive may contain data considered sensitive and its content should be reviewed by the originating organization before being passed to any third party. %(changes_text)s %(vendor_text)s ZUnknownr Example URLhttp://www.example.com/zsz*Policy.get_archive_name..r.z -%Y%m%d%H%M%Sz sosreport-Zfriendly-z -%Y-%m-%d) Zget_local_namesplitr2commonslabeljoinrange name_patternZsanitize_filenametimeZstrftime)r7rZcaserTZdateZrandZnstrrrrget_archive_names    zPolicy.get_archive_namecCs|S)Nr)r7Zbinaryrrr_get_pkg_name_for_binaryszPolicy._get_pkg_name_for_binarycCs|s tjS|S)N)tempfileZ gettempdir)r7Z opt_tmp_dirrrr get_tmp_dirszPolicy.get_tmp_dircCs6t|dkr.x |D]}t||jdr|SqW|dS)azDetermine what subclass of a Plugin should be used based on the tagging classes assigned to the Plugin :param plugin_classes: The classes that the Plugin subclasses :type plugin_classes: ``list`` :returns: The first tagging class that matches one of the Policy's `valid_subclasses` :rtype: ``PluginDistroTag`` r)len issubclassr4)r7Zplugin_classesprrr match_plugins  zPolicy.match_plugincs0tg|j}|r|tg7}tfdd|DS)a# Verifies that the plugin_class should execute under this policy :param plugin_class: The tagging class being checked :type plugin_class: ``PluginDistroTag`` :returns: ``True`` if the `plugin_class` is allowed by the policy :rtype: ``bool`` c3s|]}t|VqdS)N)r_)rMZclass_) plugin_classrrrO9sz)Policy.validate_plugin..)rr4rany)r7rbZ experimentalr4r)rbrvalidate_plugin,s   zPolicy.validate_plugincCsdS)z> This function is called prior to collection. Nr)r7rrrpre_work<szPolicy.pre_workcCsdS)zR This function is called after the sos report has been generated. Nr)r7rrr post_workAszPolicy.post_workcCs |jj|S)zWrapper to retrieve a package from the Policy's package manager :param pkg: The name of the package :type pkg: ``str`` :returns: The first package that matches `pkg` :rtype: ``str`` )r3 pkg_by_name)r7ZpkgrrrrgFs zPolicy.pkg_by_namecCsBtj\}}}}}}||_||_||_|jddk|_||_dS)Nr]ZSMP)r%unamesystemZhostnamereleaserRZsmpmachine)r7riZnoderjversionrk_rrrr1Qs zPolicy._parse_unamecCs ||_dS)z9Set common host data for the Policy to reference N)rS)r7rSrrr set_commonsZszPolicy.set_commonscCs|tjd<dS)NPATH)osenviron)r7pathrrr _set_PATH_szPolicy._set_PATHcCs|j|jdS)N)rsro)r7rrrr5bszPolicy.set_exec_pathcCs tjdkS)zThis method should return true if the user calling the script is considered to be a superuser :returns: ``True`` if user is superuser, else ``False`` :rtype: ``bool`` r)rpgetuid)r7rrris_rooteszPolicy.is_rootcCsdS)zRReturns the string name of the hashlib-supported checksum algorithm to useZsha256r)r7rrrget_preferred_hash_namenszPolicy.get_preferred_hash_namecCs|jd|jd|jdtddtdd|jdd d d d d }|jd}|jdx4|jD](\}}|jdd|d|dddqjWdS)Nz SoS PolicieszPolicies help govern how SoS operates on across different distributions of Linux. They control aspects such as plugin enablement, $PATH determination, how/which package managers are queried, default upload specifications, and more.z0When SoS intializes most functions, for example z sos reportz and z sos collecta, one of the first operations is to determine the correct policy to load for the local system. Policies will determine the proper package manager to use, any applicable container runtime(s), and init systems so that SoS and report plugins can properly function for collections. Generally speaking a single policy will map to a single distribution; for example there are separate policies for Debian, Ubuntu, RHEL, and Fedora.zRIt is currently not possible for users to directly control which policy is loaded.z*The Google Cloud-Optimized OS distributionzThe Debian distributionz=Red Hat family distributions, not necessarily including forkszUbuntu/Canonical distributions)z policies.coszpolicies.debianzpolicies.redhatzpolicies.ubuntuzSee Alsoz9For more information on distribution policies, see below  z>8z<20z<30F)newline)Z set_titleZadd_textrZ add_sectionitems)r:ZsectionZpolsZseealsoZpolvaluerrr display_helpss    zPolicy.display_helpcCs| r| rdS|r*|jjtd||r|jjtd|d|jjtdt|j|jjtdt|jjn|jjtd|d|r|jjd|jd ||jjtd d S) ahDisplay final information about a generated archive :param archive: The name of the archive that was generated :type archive: ``str`` :param directory: The build directory for sos if --build was used :type directory: ``str`` :param checksum: The checksum of the archive :type checksum: ``str`` :param archivestat: stat() information for the archive :type archivestat: `os.stat_result` :param map_file: If sos clean was invoked, the location of the mapping file for this run :type map_file: ``str`` Fz3 A mapping of obfuscated elements is available at z3 Your sos report has been generated and saved in:  z Size z Owner z3Your sos report build tree has been generated in: rw z7 Please send this file to your support representative. N) r0informrst_sizerst_uidZpw_namerv)r7archiveZ directoryZchecksumZ archivestatZmap_filerrrdisplay_resultss&  zPolicy.display_resultscCsr|jdjrd}nd}d}|j|j|j|j|j|jd|d}d}x&|jD]}|t||dd d }qPW|S) a_This method is used to prepare the preamble text to display to the user in non-batch mode. If your policy sets self.os_release_name, that text will be substituted accordingly. You can also override this method to do something more complicated. :returns: Formatted banner message string :rtype: ``str`` rJz,Changes CAN be made to system configuration.z0No changes will be made to system configuration.Htmpdir)os_release_namevendor vendor_urls vendor_textr changes_textrF)Zreplace_whitespacer|) rSZallow_system_changesmsgrr_fmt_vendor_urlsr splitlinesr)r7rwidthZ_msgZ_fmtlinerrrget_msgs  zPolicy.get_msgcs.tdd|jDdjfdd|jDS)zFormats all items in the ``vendor_urls`` class attr into a usable string for the banner message. :returns: Formatted string of URLS :rtype: ``str`` css|]}t|dVqdS)rN)r^)rMvrrrrOsz*Policy._fmt_vendor_urls..r|c3s.|]&}d|ddd|dVqdS)r}r`` objects specifying the command line defaults. :param presets: dictionary of presets to add or replace :param replace: replace presets rather than merge new presets. N)presetsupdate)r7rreplacerrrr6szPolicy.register_presetscCs(x"|jjD]\}}||kr |Sq WdS)zFind a preset profile matching the specified preset string. :param preset: a string containing a preset profile name. :returns: a matching PresetProfile. N)rry)r7presetmatchrzrrr find_preset szPolicy.find_presetcCs |jtS)zReturn a ``PresetDefaults`` object matching the runing host. Stub method to be implemented by derived policy classes. :returns: a ``PresetDefaults`` object. )rr)r7rrr probe_presetszPolicy.probe_presetc Cs|p|j}tjj|sdSxtj|D]}tjj||}t|dd,}ytj|}Wnt k rjw&YnXWdQRXx|j D]}t |t d}||}t |kr|t nd|_t|kr|tnd|_t|krx&|tD]}t|j||t|qWd|_||j|<qWq&WdS)zLoad presets from disk. Read JSON formatted preset data from the specified path, or the default location at ``/etc/sos/presets.d``. :param presets_path: a directory containing JSON presets. Nzutf-8)encoding)optsrF) presets_pathrprrexistslistdirrUopenjsonr+ ValueErrorkeysrrrdescr noter setattrrbuiltinr) r7rZ preset_pathZpfZ preset_datarZpddataargrrr load_presets#s(  zPolicy.load_presetscCs\|j}|std||jkr,td|dt||||d}d|_||j|j<|j|dS)zAdd a new on-disk preset and write it to the configured presets path. :param preset: the new PresetDefaults to add zPreset name cannot be emptyzA preset with name 'z' already exists)rrrrFN)rrrrrrwrite)r7rrrrrrrrr add_presetCs  zPolicy.add_presetcCs^| s||jkr td|d|j|}|jrBtd|jd|j|j|jj|dS)NzUnknown profile: ''zCannot delete built-in preset ')rrrrdeleterpop)r7rrrrr del_presetVs  zPolicy.del_preset)r,r-)NTN)r)F)NN)F)N)r)5__name__ __module__ __qualname____doc__rmrrZos_release_fileZ os_release_idrrrrorWrrrrrDr8 classmethodr#propertyrCr<rErFrHrYrZr\rardrerfrgr1rnrsr5rurvr{rrrr6rrrrrrrrrrr8s^1     5     * 8   r)'r/rpr%rXrr[rKrLr$pwdrtextwraprZ sos.presetsrrrrrr r Zsos.policies.package_managersr Z sos.utilitiesr r rrZsos.report.pluginsrrZ sos.optionsrr(rrmrr+rrrrrs(  $